Beispiel #1
0
        /// <summary>
        /// Creates the new.
        /// </summary>
        /// <param name="connectionLock">The connection lock.</param>
        /// <param name="databasePath">The database path.</param>
        /// <param name="openFlags">The open flags.</param>
        /// <returns></returns>
        private static SQLiteParallelConnection CreateNew(
            SemaphoreSlim connectionLock,
            string databasePath,
            SQLiteOpenFlags openFlags)
        {
            // Only return new connection if cancellation is not requested
            if (!PoolCancellationToken.Token.IsCancellationRequested)
            {
                DelegateRetry retry = new DelegateRetry(3, new TimeSpan(0, 0, 0, 500), true /*double delay*/);

                Func <SQLiteParallelConnection> function = delegate
                {
                    return(new SQLiteParallelConnection(connectionLock, databasePath, openFlags)
                    {
                        BusyTimeout = TimeSpan.FromMinutes(3)
                    });
                };

                // if there is a transient exception such as the file not getting created as we expect we run this to retry the creaton of the connection.
                // this becomes particuarly important for the first writer which actually creates teh db today. A better design would be to do a check in the create database call
                return(retry.RetryN <SQLiteParallelConnection>(function, new Func <Exception, bool>(DelegateRetry.IsTransientSqlException)));
            }

            return(null);
        }
Beispiel #2
0
            public Entry(SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags)

            {
                ConnectionString = connectionString;

                Connection = new SQLiteConnectionWithLock(connectionString, openFlags);
            }
        /// <summary>
        /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
        /// </summary>
        /// <param name="databasePath">
        /// Specifies the path to the database file.
        /// </param>
        /// <param name="openFlags">
        /// Flags controlling how the connection should be opened.
        /// </param>
        /// <param name="storeDateTimeAsTicks">
        /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
        /// absolutely do want to store them as Ticks in all new projects. The value of false is
        /// only here for backwards compatibility. There is a *significant* speed advantage, with no
        /// down sides, when setting storeDateTimeAsTicks = true.
        /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
        /// the storeDateTimeAsTicks parameter.
        /// </param>
        /// <param name="key">
        /// Specifies the encryption key to use on the database. Should be a string or a byte[].
        /// </param>
        /// <param name="preKeyAction">
        /// Executes prior to setting key for SQLCipher databases
        /// </param>
        /// <param name="postKeyAction">
        /// Executes after setting key for SQLCipher databases
        /// </param>
        /// <param name="vfsName">
        /// Specifies the Virtual File System to use on the database.
        /// </param>
        /// <param name="dateTimeStringFormat">
        /// Specifies the format to use when storing DateTime properties as strings.
        /// </param>
        /// <param name="storeTimeSpanAsTicks">
        /// Specifies whether to store TimeSpan properties as ticks (true) or strings (false). You
        /// absolutely do want to store them as Ticks in all new projects. The value of false is
        /// only here for backwards compatibility. There is a *significant* speed advantage, with no
        /// down sides, when setting storeTimeSpanAsTicks = true.
        /// </param>
        public SQLiteConnectionString(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks, object key = null, Action <SQLiteConnection> preKeyAction = null, Action <SQLiteConnection> postKeyAction = null, string vfsName = null, string dateTimeStringFormat = DateTimeSqliteDefaultFormat, bool storeTimeSpanAsTicks = true)
        {
            if (key != null && !((key is byte[]) || (key is string)))
            {
                throw new ArgumentException("Encryption keys must be strings or byte arrays", nameof(key));
            }

            UniqueKey            = string.Format("{0}_{1:X8}", databasePath, (uint)openFlags);
            StoreDateTimeAsTicks = storeDateTimeAsTicks;
            StoreTimeSpanAsTicks = storeTimeSpanAsTicks;
            DateTimeStringFormat = dateTimeStringFormat;
            DateTimeStyle        = "o".Equals(DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) || "r".Equals(DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) ? System.Globalization.DateTimeStyles.RoundtripKind : System.Globalization.DateTimeStyles.None;
            Key           = key;
            PreKeyAction  = preKeyAction;
            PostKeyAction = postKeyAction;
            OpenFlags     = openFlags;
            VfsName       = vfsName;

#if NETFX_CORE
            DatabasePath = IsInMemoryPath(databasePath)
                ? databasePath
                : System.IO.Path.Combine(MetroStyleDataPath, databasePath);
#else
            DatabasePath = databasePath;
#endif
        }
Beispiel #4
0
        public SQLiteAsyncConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)

        {
            _openFlags = openFlags;

            _connectionString = new SQLiteConnectionString(databasePath, storeDateTimeAsTicks);
        }
Beispiel #5
0
        /// <summary>
        /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
        /// </summary>
        /// <param name="databasePath">
        /// Specifies the path to the database file.
        /// </param>
        /// <param name="storeDateTimeAsTicks">
        /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
        /// absolutely do want to store them as Ticks in all new projects. The default of false is
        /// only here for backwards compatibility. There is a *significant* speed advantage, with no
        /// down sides, when setting storeDateTimeAsTicks = true.
        /// </param>
        public SQLiteConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
        {
            DatabasePath = databasePath;
#if NETFX_CORE
            SQLite3.SetDirectory(/*temp directory type*/ 2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif

            Sqlite3DatabaseHandle handle;

#if SILVERLIGHT
            var r = SQLite3.Open(databasePath, out handle, (int)openFlags, IntPtr.Zero);
#else
            // open using the byte[]
            // in the case where the path may include Unicode
            // force open to using UTF-8 using sqlite3_open_v2
            var databasePathAsBytes = GetNullTerminatedUtf8(DatabasePath);
            var r = SQLite3.Open(databasePathAsBytes, out handle, (int)openFlags, IntPtr.Zero);
#endif

            Handle = handle;
            if (r != SQLite3.Result.OK)
            {
                throw SQLiteException.New(r, String.Format("Could not open database file: {0} ({1})", DatabasePath, r));
            }
            _open = true;

            StoreDateTimeAsTicks = storeDateTimeAsTicks;

            BusyTimeout = TimeSpan.FromSeconds(0.1);
        }
Beispiel #6
0
        /// <summary>
        /// Gets a SQLite database connection given a database name. The database will be loaded from the application's
        /// assets.
        /// </summary>
        /// <param name="databaseName">The database file name.</param>
        /// <param name="openFlags">The flags to be used while opening the database.</param>
        /// <returns>A <see cref="SQLiteConnection"/> object containing the required connection.</returns>
        public SQLiteConnection GetConnection(
            string databaseName,
            SQLiteOpenFlags openFlags)
        {
            // Copy the database to the "Local application data" folder. (This is required because we can not load a
            // SQLite database directly from the .apk package; SQLite requires R/W access and we would like to avoid
            // memory backing).
            string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Tell-OP");
            string databasePath  = Path.Combine(directoryPath, databaseName);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            if (!File.Exists(databasePath))
            {
                using (BinaryReader dbReader = new BinaryReader(Xamarin.Forms.Forms.Context.Assets.Open(databaseName)))
                {
                    using (BinaryWriter dbWriter = new BinaryWriter(new FileStream(databasePath, FileMode.Create)))
                    {
                        byte[] dbBuffer = new byte[2048];
                        int    len      = 0;
                        while ((len = dbReader.Read(dbBuffer, 0, dbBuffer.Length)) > 0)
                        {
                            dbWriter.Write(dbBuffer, 0, len);
                        }
                    }
                }
            }

            // Initialize the connection.
            return(new SQLiteConnection(databasePath, openFlags));
        }
        protected BaseSqliteDatabaseService(ISqliteConfig config)
        {
            ConnectionString = config.DatabasePath;

            _tableTypes = config.TableTypes;
            _flags      = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache;
        }
Beispiel #8
0
        public SQLiteAsyncConnection(string databasePath, SQLiteOpenFlags?flags = null, bool storeDateTimeAsTicks = false)
        {
            _flags = flags ?? (SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.NoMutex | SQLiteOpenFlags.SharedCache);

            _connectionString = new SQLiteConnectionString(databasePath, storeDateTimeAsTicks);
            _pool             = new SQLiteConnectionPool(_connectionString, _flags);
        }
 public SQLiteContactsCache(string databasePath, SQLiteOpenFlags flags)
 {
     _databasePath = databasePath ?? throw new ArgumentNullException(nameof(databasePath));
     _flags        = flags;
     // lazy-инициализация БД взята из примера: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases
     _lazyInitializer = new Lazy <SQLiteAsyncConnection>(() => new SQLiteAsyncConnection(_databasePath, _flags));
     InitializeAsync().SafeFireAndForget(false);
 }
Beispiel #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SQLiteParallelConnection"/> class.
 /// </summary>
 /// <param name="connectionLock">The connection lock.</param>
 /// <param name="databasePath">The database path.</param>
 /// <param name="openFlags">The open flags.</param>
 /// <param name="storeDateTimeAsTicks">if set to <c>true</c> [store date time as ticks].</param>
 public SQLiteParallelConnection(
     SemaphoreSlim connectionLock,
     string databasePath,
     SQLiteOpenFlags openFlags,
     bool storeDateTimeAsTicks = false) : base(databasePath, openFlags, storeDateTimeAsTicks)
 {
     this.connectionLock = connectionLock;
     this.IsReadonly     = (openFlags & SQLiteOpenFlags.ReadOnly) != 0;
 }
        public SqLiteConfig(
            string databaseName,
            bool storeDateTimeAsTicks = true,
			SQLiteOpenFlags? openFlags = null)
        {
            DatabaseName = databaseName;
            StoreDateTimeAsTicks = storeDateTimeAsTicks;
			OpenFlags = openFlags ?? SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create;
        }
Beispiel #12
0
        private static SQLiteConnection ConnectWithDb()
        {
            string documentsPath        = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            string path                 = Path.Combine(documentsPath, "PwszAlarm.db3");
            const SQLiteOpenFlags Flags = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create;
            SQLiteConnection      db    = new SQLiteConnection(path, Flags);

            return(db);
        }
        public SQLiteConnectionSettings(string databasePath, SQLiteOpenFlags openFlags, bool overridePath = false)
        {
            this.DatabasePath = databasePath;
            this.OpenFlags = openFlags;
            this.OverridePath = overridePath;
            this.HasOpenFlags = true;

            BuildKey();
        }
        private async System.Threading.Tasks.Task <bool> CreateConnectionAsync()
        {
            bool ret = false;

            try
            {
                Stopwatch sw = Stopwatch.StartNew();


                this.HistoryDic.Clear();
                this.HasChanged.WriteFullFence(false);
                this.DeletedCount.WriteFullFence(0);
                this.AddedCount.WriteFullFence(0);

                //FullMutex for safe multithreading
                SQLiteOpenFlags flags = SQLiteOpenFlags.Create | SQLiteOpenFlags.FullMutex;
                if (this.ReadOnly)
                {
                    flags = flags | SQLiteOpenFlags.ReadOnly;
                }
                else
                {
                    flags = flags | SQLiteOpenFlags.ReadWrite;
                }

                if (this.IsSQLiteDBConnected())
                {
                    this.DisposeConnection();
                }

                //If the database file doesn't exist, the default behaviour is to create a new file
                sqlite_conn = new SQLiteAsyncConnection(this.Filename, flags, true);


                //make sure table exists:
                CreateTableResult ctr = await sqlite_conn.CreateTableAsync <History>();


                await sqlite_conn.ExecuteScalarAsync <int>(@"PRAGMA journal_mode = 'WAL';", new object[] { });

                await sqlite_conn.ExecuteScalarAsync <int>(@"PRAGMA busy_timeout = 30000;", new object[] { });


                sw.Stop();

                Global.Log($"Created connection to SQLite db v{sqlite_conn.LibVersionNumber} in {sw.ElapsedMilliseconds}ms - TableCreate={ctr.ToString()}: {this.Filename}");

                HasChanged.WriteFullFence(true);
            }
            catch (Exception ex)
            {
                Global.Log("Error: " + Global.ExMsg(ex));
            }

            return(ret);
        }
Beispiel #15
0
        private static SQLiteConnection ConnectWithDb()
        {
            string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            string path          = Path.Combine(documentsPath, "FakroDatabase.db3");
            //System.IO.File.Delete(path);
            const SQLiteOpenFlags flags        = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create;
            SQLiteConnection      dbConnection = new SQLiteConnection(path, flags);

            return(dbConnection);
        }
Beispiel #16
0
        public virtual void Close(SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags)
        {
            var connection = GetConnection(connectionString, openFlags);

            lock (_entriesLock)
            {
                connection.Dispose();
                _entries.Remove(connectionString.ConnectionString);
            }
        }
 /// <sumary>
 ///     Constructor that creates database and all the tables in specified location
 ///     with specified flags
 /// </sumary>
 /// <param name="dbPath"> Path to the file with database data </param>
 /// <param name="flags"> Additional flags that the database should use </param>
 public DatabaseService(string dbPath, SQLiteOpenFlags flags)
 {
     _database = new SQLiteAsyncConnection(dbPath, flags);
     _database.CreateTableAsync <Band>().Wait();
     _database.CreateTableAsync <Genre>().Wait();
     _database.CreateTableAsync <Musician>().Wait();
     _database.CreateTableAsync <Place>().Wait();
     _database.CreateTableAsync <Skill>().Wait();
     _database.CreateTableAsync <BandGenres>().Wait();
     _database.CreateTableAsync <BandMusicians>().Wait();
     _database.CreateTableAsync <Invitation>().Wait();
 }
Beispiel #18
0
 public void Load(SQLiteOpenFlags openFlags = SQLiteOpenFlags.ReadOnly, Action <DatabaseController> onComplete = null)
 {
     Unload();
     if ((openFlags & SQLiteOpenFlags.ReadWrite) == SQLiteOpenFlags.ReadWrite)
     {
         LoadReadWrite(openFlags, onComplete);
     }
     else
     {
         LoadReadOnly(openFlags, onComplete);
     }
 }
        public SqLiteConfig(
            string databaseName, 
            bool storeDateTimeAsTicks = true,
            IBlobSerializer serializer = null,
            IContractResolver resolver = null,
            SQLiteOpenFlags? openFlags = null)
        {
            DatabaseName = databaseName;
            StoreDateTimeAsTicks = storeDateTimeAsTicks;

            BlobSerializer = serializer;
            //OpenFlags = openFlags ?? SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create;
        }
        public SQLiteConnectionString(string databasePath, bool storeDateTimeAsTicks,
            IBlobSerializer serializer = null,
            IContractResolver resolver = null,
            SQLiteOpenFlags? openFlags = null)
        {
            ConnectionString = databasePath;
            StoreDateTimeAsTicks = storeDateTimeAsTicks;

            DatabasePath = databasePath;
            Serializer = serializer;
            Resolver = resolver ?? ContractResolver.Current;
            OpenFlags = openFlags ?? SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create;
        }
        public Repository(string path, SQLiteOpenFlags flags)
        {
            lazyInitializer = new Lazy <SQLiteAsyncConnection>(() =>
            {
                return(new SQLiteAsyncConnection(path, flags));
            });

            Initialize().SafeFireAndForget(false, (e) =>
            {
                #if DEBUG
                throw e;
                #endif
            });
        }
Beispiel #22
0
        public SQLiteConnectionPool(string databasePath, SQLiteOpenFlags flags = SQLiteOpenFlags.ReadOnly, int minPoolSize = 1, int maxPoolSize = 10)
        {
            if (minPoolSize <= 0)
                throw new ArgumentOutOfRangeException(nameof(minPoolSize), minPoolSize, "minPoolSize must be 1 or greater.");

            if (maxPoolSize <= 0 || maxPoolSize < minPoolSize)
                throw new ArgumentOutOfRangeException(nameof(maxPoolSize), maxPoolSize, "maxPoolSize must be greater than 1 and minPoolSize");

            DatabasePath = databasePath;
            DatabaseOpenFlags = flags;

            MinPoolSize = minPoolSize;
            MaxPoolSize = maxPoolSize;
        }
 /// <summary>
 ///   Initializes a new instance of the <see cref="SQLiteConnectionWithLockBridge" />
 ///   class.
 /// </summary>
 /// <param name="sqlitePlatform">The sqlite platform.</param>
 /// <param name="databasePath">The database path.</param>
 /// <param name="openFlags">The open flags.</param>
 /// <param name="columnInformationProvider">The column information provider.</param>
 /// <param name="storeDateTimeAsTicks">if set to <c>true</c> [store date time as ticks].</param>
 /// <param name="serializer">The serializer.</param>
 /// <param name="tableMappings">The table mappings.</param>
 /// <param name="extraTypeMappings">The extra type mappings.</param>
 /// <param name="resolver">The resolver.</param>
 public SQLiteConnectionWithLockBridge(
     ISQLitePlatform sqlitePlatform, string databasePath, SQLiteOpenFlags openFlags,
     IColumnInformationProvider columnInformationProvider = null,
     bool storeDateTimeAsTicks = true, IBlobSerializer serializer = null,
     IDictionary <string, TableMapping> tableMappings = null,
     IDictionary <Type, string> extraTypeMappings     = null, IContractResolver resolver = null)
     : base(
         sqlitePlatform,
         new SQLiteConnectionString(
             databasePath, storeDateTimeAsTicks, serializer, resolver, openFlags), tableMappings,
         extraTypeMappings)
 {
     ColumnInformationProvider = columnInformationProvider
                                 ?? new ColumnInformationProviderBridge();
 }
        /// <summary>
        /// Establishes a new connection to the indicated database.
        /// </summary>
        /// <param name="_dbName">Db name.</param>
        /// <param name="authentication">Authentication.</param>
        public bool EstablishConnection(string _dbName, SQLiteOpenFlags authentication)
        {
            _connection = null;

            if (!File.Exists(DialogueDBAdmin.streamingPath + _dbName))
            {
                Debug.Log("Failed to Establish the Connection! The indicated Database does not exist! ");
                return(false);
            }

            _connection = new SQLiteConnection(DialogueDBAdmin.streamingPath + _dbName, authentication);

            Debug.Log("The Connection has been established successfully! ");

            return(true);
        }
Beispiel #25
0
 void LoadReadOnly(SQLiteOpenFlags openFlags, Action <DatabaseController> onComplete)
 {
     if (File.Exists(saveFilePath))
     {
         DidLoad(new SQLiteConnection(saveFilePath, openFlags, true), onComplete);
     }
     else if (!assetFilePath.Contains("://"))
     {
         DidLoad(new SQLiteConnection(assetFilePath, openFlags, true), onComplete);
     }
     else
     {
         Copy(assetFilePath, saveFilePath, delegate {
             DidLoad(new SQLiteConnection(saveFilePath, openFlags, true), onComplete);
         });
     }
 }
Beispiel #26
0
        public override SQLiteConnection GetDatabase(string name, SQLiteOpenFlags openFlags = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create,
                                                     bool storeDateTimeAsTicks = true, IBlobSerializer serializer = null,
                                                     IDictionary <string, TableMapping> tableMappings = null,
                                                     IDictionary <Type, string> extraTypeMappings     = null, IContractResolver resolver = null)
        {
            Directory.CreateDirectory(BasePath);
            ISQLitePlatform platform;

            if (RuntimeInfo.IsWindows)
            {
                platform = new SQLitePlatformWin32();
            }
            else
            {
                platform = new SQLitePlatformGeneric();
            }
            return(new SQLiteConnection(platform, Path.Combine(BasePath, $@"{name}.db"), openFlags, storeDateTimeAsTicks, serializer, tableMappings, extraTypeMappings, resolver));
        }
Beispiel #27
0
        /// <summary>
        /// Gets a SQLite database connection given a database name. The
        /// database will be loaded from the application's assets.
        /// </summary>
        /// <param name="databaseName">The database file name.</param>
        /// <param name="openFlags">The flags to be used while opening the
        /// database.</param>
        /// <returns>A <see cref="SQLiteConnection"/> object containing the
        /// required connection.</returns>
        public SQLiteConnection GetConnection(
            string databaseName,
            SQLiteOpenFlags openFlags)
        {
            // Copy the database to the "Local application data" folder.
            // (This is required because we can not load a SQLite database
            // directly from the .apk package; SQLite requires R/W access and
            // we would like to avoid memory backing).
            // TODO: do we need to add "Tell-OP" at the end? See
            // https://developer.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/
            string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "Application Support");
            string databasePath  = Path.Combine(directoryPath, databaseName);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            if (!File.Exists(databasePath))
            {
                char[]   splitChars  = { '.' };
                string[] splitDBName = databaseName.Split(splitChars);
                string   splitName;
                string   splitExt;

                if (splitChars.GetLength(0) == 1)
                {
                    splitName = splitDBName[0];
                    splitExt  = string.Empty;
                }
                else
                {
                    splitName = splitDBName[0];
                    splitExt  = splitDBName[1];
                }

                File.Copy(NSBundle.MainBundle.PathForResource(splitName, splitExt), databasePath);
            }

            // Initialize the connection.
            return(new SQLiteConnection(databasePath, openFlags));
        }
Beispiel #28
0
    void LoadReadWrite(SQLiteOpenFlags openFlags, Action <DatabaseController> onComplete)
    {
        string pathToCopy = File.Exists(saveFilePath) ? saveFilePath : (File.Exists(assetFilePath) ? assetFilePath : null);

        if (!string.IsNullOrEmpty(pathToCopy))
        {
            Copy(pathToCopy, tempFilePath, delegate {
                DidLoad(new SQLiteConnection(tempFilePath, openFlags, true), onComplete);
            });
        }
        else
        {
            var tempPath = Path.Combine(Application.persistentDataPath, "Temp");
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            DidLoad(new SQLiteConnection(tempFilePath, openFlags, true), onComplete);
        }
    }
Beispiel #29
0
        public SQLiteConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
        {
            if (string.IsNullOrEmpty(databasePath))
            {
                throw new ArgumentException("Must be specified", "databasePath");
            }
            DatabasePath = databasePath;
            mayCreateSyncObject(databasePath);
            byte[] nullTerminatedUtf = GetNullTerminatedUtf8(DatabasePath);
            IntPtr db;

            SQLite3.Result result = SQLite3.Open(nullTerminatedUtf, out db, (int)openFlags, IntPtr.Zero);
            Handle = db;
            if (result != 0)
            {
                throw SQLiteException.New(result, $"Could not open database file: {DatabasePath} ({result})");
            }
            _open = true;
            StoreDateTimeAsTicks = storeDateTimeAsTicks;
            BusyTimeout          = TimeSpan.FromSeconds(0.1);
        }
Beispiel #30
0
        static SQLiteConnection EstablishConnection(string databasePath)
        {
            try
            {
                const SQLiteOpenFlags flags = SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite;

                return(new SQLiteConnection(databasePath, flags, storeDateTimeAsTicks: true));
            }
            catch (BadImageFormatException e)
            {
                throw new ApplicationException("Could not initialize SQLite connection - this is probably a sign that you've included sqlite3.dll for the wrong platform. Figure out whether your process is running as x86 or x64 and be sure to include a version of sqlite3.dll that is compiled for that platform", e);
            }
            catch (DllNotFoundException e)
            {
                throw new ApplicationException(string.Format("Unable to load sqlite3.dll - you need to make sure that the sqlite3.dll is present in the runtime directory ({0}) of your program. Figure out whether your process is running as x86 or x64 and be sure to include a version of sqlite3.dll that is compiled for that platform", AppDomain.CurrentDomain.BaseDirectory), e);
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("An error occurred when attempting to initialize SQLite database {0}", databasePath), e);
            }
        }
Beispiel #31
0
        /// <summary>
        /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
        /// </summary>
        /// <param name="databasePath">
        /// Specifies the path to the database file.
        /// </param>
        /// <param name="storeDateTimeAsTicks">
        /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
        /// absolutely do want to store them as Ticks in all new projects. The default of false is
        /// only here for backwards compatibility. There is a *significant* speed advantage, with no
        /// down sides, when setting storeDateTimeAsTicks = true.
        /// </param>
        public SQLiteConnection(string key, string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
        {
            DatabasePath = databasePath;
            mayCreateSyncObject(databasePath);

            Sqlite3DatabaseHandle handle;

            UnityEngine.Debug.Log("start SQLite3.Open");
            // open using the byte[]
            // in the case where the path may include Unicode
            // force open to using UTF-8 using sqlite3_open_v2
            var databasePathAsBytes = GetNullTerminatedUtf8(DatabasePath);
            var r = SQLite3.Open(databasePathAsBytes, out handle, (int)openFlags, IntPtr.Zero);

            UnityEngine.Debug.LogFormat("open result = {0}", r);
            if (r != SQLite3.Result.OK)
            {
                throw new Exception(String.Format("Could not open database file: {0} ({1})", DatabasePath, r));
            }

            _open  = true;
            Handle = handle;
            StoreDateTimeAsTicks = storeDateTimeAsTicks;
            BusyTimeout          = TimeSpan.FromSeconds(0.1);

            if (!string.IsNullOrEmpty(key))
            {
                UnityEngine.Debug.Log("start SQLite3.Key");
                var rr = SQLite3.Key(Handle, key, key.Length);
                UnityEngine.Debug.LogFormat("key result = {0}", rr);
                if (rr != SQLite3.Result.OK)
                {
                    string msg = SQLite3.GetErrmsg(Handle);
                    throw new Exception(msg);
                }
            }
        }
Beispiel #32
0
        public SQLiteConnection(string databasePath, string password, SQLiteOpenFlags openFlags,
                                bool storeDateTimeAsTicks = false)
        {
            if (string.IsNullOrEmpty(databasePath))
            {
                throw new ArgumentException("Must be specified", "databasePath");
            }

            DatabasePath = databasePath;

            Sqlite3DatabaseHandle handle;

            byte[]         databasePathAsBytes = GetNullTerminatedUtf8(this.DatabasePath);
            SQLite3.Result r = SQLite3.Open(databasePathAsBytes, out handle, (int)openFlags, IntPtr.Zero);

            Handle = handle;
            if (r != SQLite3.Result.OK)
            {
                throw SQLiteException.New(r,
                                          string.Format("Could not open database file: {0} ({1})", this.DatabasePath, r));
            }

            if (!string.IsNullOrEmpty(password))
            {
                SQLite3.Result result = SQLite3.Key(handle, password, password.Length);
                if (result != SQLite3.Result.OK)
                {
                    throw SQLiteException.New(r,
                                              string.Format("Could not open database file: {0} ({1})", this.DatabasePath, r));
                }
            }

            Opened = true;

            StoreDateTimeAsTicks = storeDateTimeAsTicks;
            BusyTimeout          = TimeSpan.FromSeconds(0.1);
        }
        public SQLiteConnectionWithLock GetConnection(SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags)
        {
            lock (_entriesLock)
            {
                Entry  entry;
                string key = connectionString.ConnectionString;

                if (!_entries.TryGetValue(key, out entry))
                {
                    entry         = new Entry(connectionString, openFlags);
                    _entries[key] = entry;
                }

                return(entry.Connection);
            }
        }
Beispiel #34
0
 public abstract SQLiteConnection GetDatabase(string name, SQLiteOpenFlags openFlags = SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create,
                                              bool storeDateTimeAsTicks = true, IBlobSerializer serializer = null,
                                              IDictionary <string, TableMapping> tableMappings = null,
                                              IDictionary <Type, string> extraTypeMappings     = null, IContractResolver resolver = null);
		public static extern SQLiteErrorCode sqlite3_open_v2(byte[] utf8Filename, out SqliteDatabaseHandle db, SQLiteOpenFlags flags, byte[] vfs);