Example #1
0
        static BaseDataSQLite()
        {
            #if DEBUG
            _sqliteFile = Paths.DebugSQLitePath;
            #else
            _sqliteFile = Paths.ReleaseSQLitePath;
            #endif

            //_connectionString = String.Format("Data Source=:memory:");
            //_connectionString = String.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;Synchronous=Normal;Journal Mode=WAL", _sqliteFile);
            _connectionString = String.Format("Data Source={0}", _sqliteFile);

            if (!File.Exists(_sqliteFile))
            {
                if (!File.Exists(Paths.SqlPath))
                    throw new FileNotFoundException("Cannot find SQL file: " + Paths.SqlPath);
                else {
                    // Generate database
                    var conn = new SqliteConnection(_connectionString);
                    conn.Open();
                    var sql = File.ReadAllText(Paths.SqlPath);
                    conn.Execute(sql);
                    conn.Dispose();
                }
            }
        }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual DatabaseModel Create(string connectionString, TableSelectionSet tableSelectionSet)
        {
            Check.NotEmpty(connectionString, nameof(connectionString));
            Check.NotNull(tableSelectionSet, nameof(tableSelectionSet));

            ResetState();

            using (_connection = new SqliteConnection(connectionString))
            {
                _connection.Open();
                _tableSelectionSet = tableSelectionSet;

                string databaseName = null;
                try
                {
                    databaseName = Path.GetFileNameWithoutExtension(_connection.DataSource);
                }
                catch (ArgumentException)
                {
                    // graceful fallback
                }

                _databaseModel.DatabaseName = !string.IsNullOrEmpty(databaseName)
                    ? databaseName
                    : _connection.DataSource;

                GetTables();
                GetColumns();
                GetIndexes();
                GetForeignKeys();
                return _databaseModel;
            }
        }
Example #3
0
        private static IDbConnection GetDatabaseConnectionSDS(string cs)
        {
            var rv = new Microsoft.Data.Sqlite.SqliteConnection(cs);

            if (rv == null)
            {
                throw new ArgumentException("no connection");
            }
            rv.Open();

            try {
                /*  rv.SetChunkSize(GROW_SIZE); */
            }
            catch (Exception ex) {
                LogManager.GetLogger(typeof(Sqlite)).Error(
                    "Failed to sqlite control", ex);
            }

            if (clearPool == null)
            {
                clearPool = conn =>
                {
                    /* SQLiteConnection.ClearPool(
                     * conn as SqliteConnection); */
                };
            }
            return(rv);
        }
        private static void AddHistoricMessage(Message message)
        {
            var sql = string.Format("INSERT INTO {0} (MessageId, MessageType, Topic, Timestamp, HeaderBag, Body) VALUES (@MessageId, @MessageType, @Topic, @Timestamp, @HeaderBag, @Body)", _sqliteTestHelper.TableName_Messages);
            var parameters = new[]
            {
                new SqliteParameter("MessageId", message.Id.ToString()),
                new SqliteParameter("MessageType", message.Header.MessageType.ToString()),
                new SqliteParameter("Topic", message.Header.Topic),
                new SqliteParameter("Timestamp", SqliteType.Text) { Value =message.Header.TimeStamp.ToString("s")},
                new SqliteParameter("HeaderBag",SqliteType.Text) { Value = JsonConvert.SerializeObject(message.Header.Bag)},
                new SqliteParameter("Body", message.Body.Value),
            };

            using (var connection = new SqliteConnection(_sqliteTestHelper.ConnectionString))
            using (var command = connection.CreateCommand())
            {
                connection.Open();

                command.CommandText = sql;
                //command.Parameters.AddRange(parameters); used to work... but can't with current Sqlite lib. Iterator issue
                for (var index = 0; index < parameters.Length; index++)
                {
                    command.Parameters.Add(parameters[index]);
                }
                command.ExecuteNonQuery();
            }
        }
Example #5
0
        public void RunSqlite()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = "CREATE TABLE Test(Value);";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "INSERT INTO Test VALUES(1);";
                    cmd.ExecuteNonQuery();
                }
                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText =
                        "SELECT [type], [name], [tbl_name], [rootpage], [sql], [rowid] FROM [main].[sqlite_master] WHERE [type] LIKE 'table'";
                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            System.Console.WriteLine(dr[2].ToString());
                        }
                    }
                }

                var databaseReader = new DatabaseSchemaReader.DatabaseReader(connection);
                var schema = databaseReader.ReadAll();
                var tableList = databaseReader.TableList();
                var tables = databaseReader.AllTables();
                var views = databaseReader.AllViews();
                Assert.NotEmpty(tableList);
            }
        }
 private async Task<IEnumerable<IPRangeInfo>> LocateIPv6Async(IPAddress ip)
 {
     var flatIP = new FlatIPAddress(ip);
     using (var connection = new SqliteConnection(_connectionString))
     {
         connection.Open();
         return await connection.ExecuteReaderAsync(dataReader =>
         {
             return new IPRangeInfo
             {
                 IPRange = new IPRange
                 {
                     Start = new FlatIPAddress { Low = (long)dataReader["StartLow"], High = (long)dataReader["StartHigh"] }.ToIPAddress(),
                     End = new FlatIPAddress { Low = (long)dataReader["EndLow"], High = (long)dataReader["EndHigh"] }.ToIPAddress(),
                 },
                 AreaId = Convert.ToInt32(dataReader["AreaId"]),
                 ProviderId = Convert.ToInt32(dataReader["ProviderId"]),
             };
         }, @"
             SELECT * FROM IPRangeInfos 
             WHERE (StartHigh < {1} OR (StartHigh = {1} AND StartLow <= {0}))
             AND (EndHigh > {1} OR (EndHigh = {1} AND EndLow >= {0}));",
         flatIP.Low, flatIP.High);
     }
 }
Example #7
0
 public void CreateDatabase()
 {
     using (Microsoft.Data.Sqlite.SqliteConnection connection = new Microsoft.Data.Sqlite.SqliteConnection(connectionString))
     {
         connection.Open();
     }
 }
        private SqliteTestStore CreateTransient(bool sharedCache)
        {
            _connection = new SqliteConnection(CreateConnectionString(_name, sharedCache));

            _connection.Open();

            return this.AsTransient();
        }
Example #9
0
        public InspectionTest()
        {
            var logConn = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:");

            logConn.Open();
            _insp = new JobLogDB(new FMSSettings(), logConn);
            _insp.CreateTables(firstSerialOnEmpty: null);
        }
Example #10
0
 private SqliteConnection Open(string connectionString)
 {
     var connection = new SqliteConnection(connectionString);
     connection.Open();
     connection.EnableExtensions();
     connection.LoadExtension(_spatialiteExtensionName);
     return connection;
 }
Example #11
0
 public void TestLite()
 {
     using (SqliteConnection conn = new SqliteConnection(_connectionString))
     {
         conn.Open();
         //var d = conn.Query("SELECT * FROM User;");
     }
 }
        private SqliteTestStore CreateTransient()
        {
            _connection = new SqliteConnection(CreateConnectionString(_name));

            _connection.Open();

            _deleteDatabase = true;

            return this;
        }
        private void CreateAndOpenConnection(bool sharedCache = false)
        {
            _connection = new SqliteConnection(CreateConnectionString(_name, sharedCache));

            _connection.Open();

            var command = _connection.CreateCommand();
            command.CommandText = "PRAGMA foreign_keys=ON;";
            command.ExecuteNonQuery();
        }
        protected override bool CanShowOverlay(string path, FILE_ATTRIBUTE attributes)
        {
            //  Return true if the file is read only, meaning we'll show the overlay.
            try
            {
                string app = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                string dbPath = Path.Combine(app, @"yliyun\db\file_status.db");
                using (SqliteConnection conn = new SqliteConnection("Data Source =" + dbPath))
                {
                    string rootDir = @"D:\一粒云盘";

                    conn.Open();

                    SqliteCommand cmd1 = new SqliteCommand("SELECT syncRoot FROM yliyun_conf", conn);

                    SqliteDataReader reader1 = cmd1.ExecuteReader();
                    if (reader1.Read())
                    {
                        rootDir = reader1.GetString(0);
                    }

                    if (path.StartsWith(Path.Combine(rootDir, @"个人空间\"))
                        || path.StartsWith(Path.Combine(rootDir, @"群组空间\"))
                        || path.StartsWith(Path.Combine(rootDir, @"部门空间\"))
                        || path.StartsWith(Path.Combine(rootDir, @"共享空间\")))
                    {
                        string sql = "SELECT lastModified FROM file_status WHERE filePath = @fp";
                        SqliteCommand cmd = new SqliteCommand(sql, conn);
                        cmd.Parameters.AddRange(new[]
                            {
                                new SqliteParameter("@fp", path)
                            });

                        SqliteDataReader reader = cmd.ExecuteReader();

                        if (reader.Read())
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        private SqliteTestStore CreateShared(Action initializeDatabase)
        {
            CreateShared(typeof(SqliteTestStore).Name + _name, initializeDatabase);

            _connection = new SqliteConnection(CreateConnectionString(_name));

            _connection.Open();
            _transaction = _connection.BeginTransaction();

            return this;
        }
        public override IModel ConstructRelationalModel([NotNull] string connectionString)
        {
            Check.NotEmpty(connectionString, nameof(connectionString));

            var modelBuilder = new ModelBuilder(new ConventionSet());

            using (var connection = new SqliteConnection(connectionString))
            {
                connection.Open();
                var tables = new Dictionary<string, string>();
                var indexes = new List<SqliteIndexInfo>();
                var master = connection.CreateCommand();
                master.CommandText = "SELECT type, name, sql, tbl_name FROM sqlite_master";
                using (var reader = master.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var type = reader.GetString(0);
                        var name = reader.GetString(1);
                        var sql = reader.GetValue(2) as string; // can be null
                        var tableName = reader.GetString(3);

                        if (type == "table"
                            && name != "sqlite_sequence"
                            && _tableSelectionSet.Allows(TableSelection.Any, name))
                        {
                            tables.Add(name, sql);
                        }
                        else if (type == "index")
                        {
                            indexes.Add(new SqliteIndexInfo
                            {
                                Name = name,
                                TableName = tableName,
                                Sql = sql
                            });
                        }
                    }
                }

                LoadTablesAndColumns(connection, modelBuilder, tables.Keys);
                LoadIndexes(connection, modelBuilder, indexes);

                foreach (var item in tables)
                {
                    SqliteDmlParser.ParseTableDefinition(modelBuilder, item.Key, item.Value);
                }

                AddAlternateKeys(modelBuilder);
                LoadForeignKeys(connection, modelBuilder, tables.Keys);
            }

            return modelBuilder.Model;
        }
Example #17
0
        public void CreateTable()
        {
            using (Microsoft.Data.Sqlite.SqliteConnection connection = new Microsoft.Data.Sqlite.SqliteConnection(connectionString))
            {
                connection.Open();

                SqliteCommand cmd = connection.CreateCommand();
                cmd.CommandText = "CREATE TABLE IF NOT EXISTS favorite_beers(name VARCHAR(50))";
                cmd.ExecuteNonQuery();
            }
        }
Example #18
0
        public void DropTable()
        {
            using (Microsoft.Data.Sqlite.SqliteConnection connection = new Microsoft.Data.Sqlite.SqliteConnection(connectionString))
            {
                SqliteCommand cmd = connection.CreateCommand();
                cmd.CommandText = "DROP TABLE IF EXISTS favorite_beers";

                connection.Open();

                cmd.ExecuteNonQuery();
            }
        }
        public void Ctor_unsets_read_uncommitted_when_serializable()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                using (connection.BeginTransaction(IsolationLevel.Serializable))
                {
                    Assert.Equal(0L, connection.ExecuteScalar<long>("PRAGMA read_uncommitted;"));
                }
            }
        }
        public void Ctor_sets_read_uncommitted()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:;Cache=Shared"))
            {
                connection.Open();

                using (connection.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    Assert.Equal(1L, connection.ExecuteScalar<long>("PRAGMA read_uncommitted;"));
                }
            }
        }
        public void DataSource_returns_actual_filename_when_open()
        {
            using (var connection = new SqliteConnection("Data Source=test.db"))
            {
                connection.Open();

                var result = connection.DataSource;

                Assert.True(Path.IsPathRooted(result));
                Assert.Equal("test.db", Path.GetFileName(result));
            }
        }
Example #22
0
        private SqliteConnection CreateDatabaseWithTable(string dataSourceTestDb, string createTableScript)
        {
            _sqlConnection = new SqliteConnection(dataSourceTestDb);

            _sqlConnection.Open();
            using (var command = _sqlConnection.CreateCommand())
            {
                command.CommandText = createTableScript;
                command.ExecuteNonQuery();
            }

            return _sqlConnection;
        }
        public void IsolationLevel_throws_when_completed()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                var transaction = connection.BeginTransaction();
                transaction.Dispose();

                var ex = Assert.Throws<InvalidOperationException>(() => transaction.IsolationLevel);

                Assert.Equal(Strings.TransactionCompleted, ex.Message);
            }
        }
        public void Ctor_throws_when_invalid_isolation_level_without_cache()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();
                var ex = Assert.Throws<ArgumentException>(() => connection.BeginTransaction(IsolationLevel.ReadUncommitted));
                Assert.Equal(Strings.FormatInvalidIsolationLevelForUnsharedCache(IsolationLevel.ReadUncommitted), ex.Message);
            }

            using (var connection = new SqliteConnection("Data Source=:memory:;Cache=Shared"))
            {
                connection.Open();
                connection.BeginTransaction(IsolationLevel.ReadUncommitted);
            }
        }
        public void Ctor_sets_values()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    var command = new SqliteCommand("SELECT 1;", connection, transaction);

                    Assert.Equal("SELECT 1;", command.CommandText);
                    Assert.Same(connection, command.Connection);
                    Assert.Same(transaction, command.Transaction);
                }
            }
        }
Example #26
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var path       = FileSystem.Current.LocalStorage.Path;
            var connection = new Microsoft.Data.Sqlite.SqliteConnection($"Data Source= {path}/{filename}");

            connection.Open();

            var command = connection.CreateCommand();

            command.CommandText = "PRAGMA key = 'password';";
            command.ExecuteNonQuery();

            optionsBuilder.UseSqlite(connection);

            // optionsBuilder.UseSqlite($"Filename= {path}/{filename}");

            base.OnConfiguring(optionsBuilder);
        }
Example #27
0
        public StorageDB(string filepath, PropertyInfo property)
        {
            _pro = property;
            if (System.IO.Directory.Exists(Path.GetDirectoryName(filepath)) == false)
            {
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName(filepath));
            }

            _sqlCon = new SQLiteConnection($"Data Source=\"{filepath}\"");
            _sqlCon.Open();
            FixFileSize();
            if (isTableExist("main") == false)
            {
                CreateTable(_pro.PropertyType);
            }

            _sqlConForDelete = new SQLiteConnection($"Data Source=\"{filepath}\"");
            _sqlConForDelete.Open();
        }
Example #28
0
        protected void Execute(Action<SqliteCommand> action)
        {
            try
            {
                using (SqliteConnection connection = new SqliteConnection(this.connectionString))
                {
                    connection.Open();

                    using (SqliteCommand command = new SqliteCommand())
                    {
                        command.Connection = connection;
                        action.Invoke(command);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #29
0
		public void CharTest2()
		{
			using (var connection = new SqliteConnection(@"Data Source=Database\TestData.sqlite"))
			{
				connection.Open();
				var command = connection.CreateCommand();

				command.CommandText = "SELECT @p";
				var p = command.CreateParameter();
				p.Value = '1';
				p.ParameterName = "@p";

				command.Parameters.Add(p);

				var r = command.ExecuteReader();
				r.Read();

				var value = r.GetValue(0);
				Assert.AreNotEqual((long)49, value, $"{value.GetType().FullName}");
			}
		}
Example #30
0
		public void UInt32Test()
		{
			using (var connection = new SqliteConnection(@"Data Source=Database\TestData.sqlite"))
			{
				connection.Open();
				var command = connection.CreateCommand();

				command.CommandText = "SELECT @p";
				var p = command.CreateParameter();
				p.Value = UInt32.MaxValue;
				p.DbType = System.Data.DbType.UInt32;
				p.ParameterName = "@p";

				command.Parameters.Add(p);

				var r = command.ExecuteReader();
				r.Read();

				var value = r.GetValue(0);
				Assert.AreEqual(UInt32.MaxValue, value, $"{value.GetType().FullName} {value}");
			}
		}
        public virtual DatabaseModel Create(
            [NotNull] string connectionString, [NotNull] TableSelectionSet tableSelectionSet)
        {
            Check.NotEmpty(connectionString, nameof(connectionString));
            Check.NotNull(tableSelectionSet, nameof(tableSelectionSet));

            ResetState();

            using (_connection = new SqliteConnection(connectionString))
            {
                _connection.Open();
                _tableSelectionSet = tableSelectionSet;

                string databaseName = null;
                try
                {
                    databaseName = Path.GetFileNameWithoutExtension(_connection.DataSource);
                }
                catch (ArgumentException)
                {
                    // graceful fallback
                }

                _databaseModel.DatabaseName = !string.IsNullOrEmpty(databaseName) ? databaseName : _connection.DataSource;

                GetSqliteMaster();
                GetColumns();
                GetIndexes();

                foreach (var table in _databaseModel.Tables)
                {
                    SqliteDmlParser.ParseTableDefinition(table, _tableDefinitions[table.Name]);
                }

                GetForeignKeys();
                return _databaseModel;
            }
        }
Example #32
0
        public void ExecuteReader_throws_when_transaction_mismatched()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                var command = connection.CreateCommand();
                command.CommandText = "SELECT 1;";
                connection.Open();

                using (var otherConnection = new SqliteConnection("Data Source=:memory:"))
                {
                    otherConnection.Open();

                    using (var transction = otherConnection.BeginTransaction())
                    {
                        command.Transaction = transction;

                        var ex = Assert.Throws <InvalidOperationException>(() => command.ExecuteReader());

                        Assert.Equal(Strings.TransactionConnectionMismatch, ex.Message);
                    }
                }
            }
        }
Example #33
0
        public void NextResult_skips_DML_statements()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();
                connection.ExecuteNonQuery("CREATE TABLE Test(Value);");

                var sql = @"
                    SELECT 1;
                    INSERT INTO Test VALUES(1);
                    SELECT 2;";
                using (var reader = connection.ExecuteReader(sql))
                {
                    var hasResults = reader.NextResult();
                    Assert.True(hasResults);

                    var hasData = reader.Read();
                    Assert.True(hasData);

                    Assert.Equal(2L, reader.GetInt64(0));
                }
            }
        }
        public void ReadUncommitted_allows_dirty_reads()
        {
            const string connectionString = "Data Source=read-uncommitted;Mode=Memory;Cache=Shared";

            using (var connection1 = new SqliteConnection(connectionString))
                using (var connection2 = new SqliteConnection(connectionString))
                {
                    connection1.Open();
                    connection2.Open();

                    connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (0);");

                    using (connection1.BeginTransaction())
                        using (connection2.BeginTransaction(IsolationLevel.ReadUncommitted))
                        {
                            connection1.ExecuteNonQuery("UPDATE Data SET Value = 1;");

                            var value = connection2.ExecuteScalar <long>("SELECT * FROM Data;");

                            Assert.Equal(1, value);
                        }
                }
        }
Example #35
0
        public void EnsureDatabase()
        {
            try
            {
                if (sqliteFilePath.Length > 0)
                {


                    //sqlite will automatically create the db when it tries to connect but the folder must exist

                    string folderPath = Path.GetDirectoryName(sqliteFilePath);
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }

                    if (!File.Exists(sqliteFilePath))
                    {
                        using (SqliteConnection conn = new SqliteConnection(connectionString))
                        {
                            conn.Open();
                        } //this closes it


                    }



                }
            }
            catch (Exception ex)
            {
                log.LogError("SqlCe database file is not present, tried to create it but this error occurred.", ex);

            }

        }
Example #36
0
        public void NextResult_works()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                using (var reader = connection.ExecuteReader("SELECT 1; SELECT 2;"))
                {
                    var hasData = reader.Read();
                    Assert.True(hasData);
                    Assert.Equal(1L, reader.GetInt64(0));

                    var hasResults = reader.NextResult();
                    Assert.True(hasResults);

                    hasData = reader.Read();
                    Assert.True(hasData);
                    Assert.Equal(2L, reader.GetInt64(0));

                    hasResults = reader.NextResult();
                    Assert.False(hasResults);
                }
            }
        }
Example #37
0
        public void Open_decrypts_lazily_when_no_password()
        {
            try
            {
                using var connection1 = new SqliteConnection("Data Source=encrypted2.db;Password=password");
                connection1.Open();

                // NB: The file is only encrypted after writing
                connection1.ExecuteNonQuery(
                    "CREATE TABLE IF NOT EXISTS data (value); INSERT INTO data (value) VALUES (1);");

                using var connection2 = new SqliteConnection("Data Source=encrypted2.db");
                connection2.Open();
                connection2.ExecuteNonQuery("PRAGMA key = 'password';");

                var value = connection2.ExecuteScalar <long>("SELECT value FROM data;");

                Assert.Equal(1L, value);
            }
            finally
            {
                File.Delete("encrypted2.db");
            }
        }
        public void GetSchemaTable_works()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();
                connection.ExecuteNonQuery(
                    "CREATE TABLE Person (ID INTEGER PRIMARY KEY, FirstName TEXT, LastName TEXT NOT NULL, Code INT UNIQUE);");
                connection.ExecuteNonQuery("INSERT INTO Person VALUES(101, 'John', 'Dee', 123);");
                connection.ExecuteNonQuery("INSERT INTO Person VALUES(105, 'Jane', 'Doe', 456);");

                using (var reader = connection.ExecuteReader("SELECT LastName, ID, Code, ID+1 AS IncID FROM Person;"))
                {
                    var schema = reader.GetSchemaTable();
                    Assert.True(schema.Columns.Contains("ColumnName"));
                    Assert.True(schema.Columns.Contains("ColumnOrdinal"));
                    Assert.True(schema.Columns.Contains("ColumnSize"));
                    Assert.True(schema.Columns.Contains("NumericPrecision"));
                    Assert.True(schema.Columns.Contains("NumericScale"));
                    Assert.True(schema.Columns.Contains("IsUnique"));
                    Assert.True(schema.Columns.Contains("IsKey"));
                    Assert.True(schema.Columns.Contains("BaseServerName"));
                    Assert.True(schema.Columns.Contains("BaseCatalogName"));
                    Assert.True(schema.Columns.Contains("BaseColumnName"));
                    Assert.True(schema.Columns.Contains("BaseSchemaName"));
                    Assert.True(schema.Columns.Contains("BaseTableName"));
                    Assert.True(schema.Columns.Contains("DataType"));
                    Assert.True(schema.Columns.Contains("DataTypeName"));
                    Assert.True(schema.Columns.Contains("AllowDBNull"));
                    Assert.True(schema.Columns.Contains("IsAliased"));
                    Assert.True(schema.Columns.Contains("IsExpression"));
                    Assert.True(schema.Columns.Contains("IsAutoIncrement"));
                    Assert.True(schema.Columns.Contains("IsLong"));

                    Assert.Equal(4, schema.Rows.Count);

                    Assert.Equal("LastName", schema.Rows[0]["ColumnName"]);
                    Assert.Equal(0, schema.Rows[0]["ColumnOrdinal"]);
                    Assert.Equal(DBNull.Value, schema.Rows[0]["ColumnSize"]);
                    Assert.Equal(DBNull.Value, schema.Rows[0]["NumericPrecision"]);
                    Assert.Equal(DBNull.Value, schema.Rows[0]["NumericScale"]);
                    Assert.False((bool)schema.Rows[0]["IsUnique"]);
                    Assert.False((bool)schema.Rows[0]["IsKey"]);
                    Assert.Equal("", schema.Rows[0]["BaseServerName"]);
                    Assert.Equal("main", schema.Rows[0]["BaseCatalogName"]);
                    Assert.Equal("LastName", schema.Rows[0]["BaseColumnName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[0]["BaseSchemaName"]);
                    Assert.Equal("Person", schema.Rows[0]["BaseTableName"]);
                    Assert.Equal(typeof(String), schema.Rows[0]["DataType"]);
                    Assert.Equal("TEXT", schema.Rows[0]["DataTypeName"]);
                    Assert.False((bool)schema.Rows[0]["AllowDBNull"]);
                    Assert.False((bool)schema.Rows[0]["IsAliased"]);
                    Assert.False((bool)schema.Rows[0]["IsExpression"]);
                    Assert.False((bool)schema.Rows[0]["IsAutoIncrement"]);
                    Assert.Equal(DBNull.Value, schema.Rows[0]["IsLong"]);

                    Assert.Equal("ID", schema.Rows[1]["ColumnName"]);
                    Assert.Equal(1, schema.Rows[1]["ColumnOrdinal"]);
                    Assert.Equal(DBNull.Value, schema.Rows[1]["ColumnSize"]);
                    Assert.Equal(DBNull.Value, schema.Rows[1]["NumericPrecision"]);
                    Assert.Equal(DBNull.Value, schema.Rows[1]["NumericScale"]);
                    Assert.False((bool)schema.Rows[1]["IsUnique"]);
                    Assert.True((bool)schema.Rows[1]["IsKey"]);
                    Assert.Equal("", schema.Rows[1]["BaseServerName"]);
                    Assert.Equal("main", schema.Rows[1]["BaseCatalogName"]);
                    Assert.Equal("ID", schema.Rows[1]["BaseColumnName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[1]["BaseSchemaName"]);
                    Assert.Equal("Person", schema.Rows[1]["BaseTableName"]);
                    Assert.Equal(typeof(Int64), schema.Rows[1]["DataType"]);
                    Assert.Equal("INTEGER", schema.Rows[1]["DataTypeName"]);
                    Assert.True((bool)schema.Rows[1]["AllowDBNull"]);
                    Assert.False((bool)schema.Rows[1]["IsAliased"]);
                    Assert.False((bool)schema.Rows[1]["IsExpression"]);
                    Assert.False((bool)schema.Rows[1]["IsAutoIncrement"]);
                    Assert.Equal(DBNull.Value, schema.Rows[1]["IsLong"]);

                    Assert.Equal("Code", schema.Rows[2]["ColumnName"]);
                    Assert.Equal(2, schema.Rows[2]["ColumnOrdinal"]);
                    Assert.Equal(DBNull.Value, schema.Rows[2]["ColumnSize"]);
                    Assert.Equal(DBNull.Value, schema.Rows[2]["NumericPrecision"]);
                    Assert.Equal(DBNull.Value, schema.Rows[2]["NumericScale"]);
                    Assert.True((bool)schema.Rows[2]["IsUnique"]);
                    Assert.False((bool)schema.Rows[2]["IsKey"]);
                    Assert.Equal("", schema.Rows[2]["BaseServerName"]);
                    Assert.Equal("main", schema.Rows[2]["BaseCatalogName"]);
                    Assert.Equal("Code", schema.Rows[2]["BaseColumnName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[2]["BaseSchemaName"]);
                    Assert.Equal("Person", schema.Rows[2]["BaseTableName"]);
                    Assert.Equal(typeof(Int64), schema.Rows[2]["DataType"]);
                    Assert.Equal("INT", schema.Rows[2]["DataTypeName"]);
                    Assert.True((bool)schema.Rows[2]["AllowDBNull"]);
                    Assert.False((bool)schema.Rows[2]["IsAliased"]);
                    Assert.False((bool)schema.Rows[2]["IsExpression"]);
                    Assert.False((bool)schema.Rows[2]["IsAutoIncrement"]);
                    Assert.Equal(DBNull.Value, schema.Rows[2]["IsLong"]);

                    Assert.Equal("IncID", schema.Rows[3]["ColumnName"]);
                    Assert.Equal(3, schema.Rows[3]["ColumnOrdinal"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["ColumnSize"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["NumericPrecision"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["NumericScale"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["IsUnique"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["IsKey"]);
                    Assert.Equal("", schema.Rows[3]["BaseServerName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["BaseCatalogName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["BaseColumnName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["BaseSchemaName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["BaseTableName"]);
                    Assert.Equal(typeof(Int64), schema.Rows[3]["DataType"]);
                    Assert.Equal("INTEGER", schema.Rows[3]["DataTypeName"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["AllowDBNull"]);
                    Assert.True((bool)schema.Rows[3]["IsAliased"]);
                    Assert.True((bool)schema.Rows[3]["IsExpression"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["IsAutoIncrement"]);
                    Assert.Equal(DBNull.Value, schema.Rows[3]["IsLong"]);
                }
            }
        }
        public void Open_throws_when_no_connection_string()
        {
            var connection = new SqliteConnection();

            var ex = Assert.Throws<InvalidOperationException>(() => connection.Open());

            Assert.Equal(Strings.OpenRequiresSetConnectionString, ex.Message);
        }
Example #40
0
        public void Open_works_when_no_connection_string()
        {
            using var connection = new SqliteConnection();

            connection.Open();
        }
        public void Mars_works()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                var command1 = connection.CreateCommand();
                command1.CommandText = "SELECT '1A' UNION SELECT '1B';";

                using (var reader1 = command1.ExecuteReader())
                {
                    reader1.Read();
                    Assert.Equal("1A", reader1.GetString(0));

                    var command2 = connection.CreateCommand();
                    command2.CommandText = "SELECT '2A' UNION SELECT '2B';";

                    using (var reader2 = command2.ExecuteReader())
                    {
                        reader2.Read();
                        Assert.Equal("2A", reader2.GetString(0));

                        reader1.Read();
                        Assert.Equal("1B", reader1.GetString(0));

                        reader2.Read();
                        Assert.Equal("2B", reader2.GetString(0));
                    }
                }
            }
        }
        public void BeginTransaction_works()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction(IsolationLevel.Serializable))
                {
                    Assert.NotNull(transaction);
                    Assert.Equal(connection, transaction.Connection);
                    Assert.Equal(IsolationLevel.Serializable, transaction.IsolationLevel);
                }
            }
        }
Example #43
0
 private void Open_works_when_password_might_be_supported()
 {
     using var connection = new SqliteConnection("Data Source=encrypted.db;Password=password");
     connection.Open();
 }
        public void ConnectionString_setter_throws_when_open()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                var ex = Assert.Throws<InvalidOperationException>(() => connection.ConnectionString = "Data Source=test.db");

                Assert.Equal(Strings.ConnectionStringRequiresClosedConnection, ex.Message);
            }
        }
        public void Ctor_throws_when_invalid_isolation_level()
        {
            using (var connection = new SqliteConnection("Data Source=:memory:"))
            {
                connection.Open();

                var ex = Assert.Throws<ArgumentException>(() => connection.BeginTransaction(IsolationLevel.Snapshot));

                Assert.Equal(Strings.FormatInvalidIsolationLevel(IsolationLevel.Snapshot), ex.Message);
            }
        }