예제 #1
0
 public void Close()
 {
     if (_open && Handle != NullHandle)
     {
         try
         {
             if (_mappings != null)
             {
                 foreach (TableMapping value in _mappings.Values)
                 {
                     value.Dispose();
                 }
             }
             SQLite3.Result result = SQLite3.Close(Handle);
             if (result != 0)
             {
                 string errmsg = SQLite3.GetErrmsg(Handle);
                 throw SQLiteException.New(result, errmsg);
             }
         }
         finally
         {
             Handle = NullHandle;
             _open  = false;
         }
     }
 }
예제 #2
0
        public T ExecuteScalar <T>()
        {
            if (_conn.Trace)
            {
                _conn.InvokeTrace("Executing Query: " + this);
            }
            T result = default(T);

            lock (_conn.SyncObject)
            {
                IntPtr stmt = Prepare();
                try
                {
                    SQLite3.Result result2 = SQLite3.Step(stmt);
                    switch (result2)
                    {
                    case SQLite3.Result.Row:
                    {
                        SQLite3.ColType type = SQLite3.ColumnType(stmt, 0);
                        return((T)ReadCol(stmt, 0, type, typeof(T)));
                    }

                    default:
                        throw SQLiteException.New(result2, SQLite3.GetErrmsg(_conn.Handle));

                    case SQLite3.Result.Done:
                        return(result);
                    }
                }
                finally
                {
                    Finalize(stmt);
                }
            }
        }
        /// <summary>
        /// Return a list of table names
        /// </summary>
        public string[] GetTableNames()
        {
            string        tableSQL  = "SELECT name FROM sqlite_master WHERE type='table'";
            List <string> tables    = new List <string>();
            var           statement = SQLite3.Prepare2(connection.Handle, tableSQL);

            try
            {
                bool done = false;
                while (!done)
                {
                    SQLite3.Result result = SQLite3.Step(statement);
                    if (result == SQLite3.Result.Row)
                    {
                        var tableName = SQLite3.ColumnString(statement, 0);
                        tables.Add(tableName);
                    }
                    else if (result == SQLite3.Result.Done)
                    {
                        done = true;
                    }
                    else
                    {
                        throw SQLiteException.New(result, SQLite3.GetErrmsg(connection.Handle));
                    }
                }
            }
            finally
            {
                SQLite3.Finalize(statement);
            }
            return(tables.ToArray());
        }
예제 #4
0
 protected NotNullConstraintViolationException(SQLite3.Result r, string message, TableMapping mapping, object obj) : base(r, message)
 {
     if (mapping != null && obj != null)
     {
         this.Columns = from c in mapping.Columns where c.IsNullable == false && c.GetValue(obj) == null select c;
     }
 }
예제 #5
0
 public static ServiceResultStatus FromSQLiteResult(
     SQLite3.Result sqliterResult)
 {
     return(StatusDictionary.ContainsKey(sqliterResult)
         ? StatusDictionary[sqliterResult]
         : ServiceResultStatus.Unknown);
 }
예제 #6
0
        public T ExecuteScalar <T>()
        {
            if (_conn.Trace)
            {
                Debug.WriteLine("Executing Query: " + this);
            }

            T val = default(T);

            IntPtr stmt = Prepare();

            try {
                SQLite3.Result r = SQLite3.Step(stmt);
                if (r == SQLite3.Result.Row)
                {
                    SQLite3.ColType colType = SQLite3.ColumnType(stmt, 0);
                    val = (T)ReadCol(stmt, 0, colType, typeof(T));
                }
                else if (r == SQLite3.Result.Done)
                {
                }
                else
                {
                    throw SQLiteException.New(r, SQLite3.GetErrmsg(_conn.Handle));
                }
            } finally {
                Finalize(stmt);
            }

            return(val);
        }
예제 #7
0
        public int ExecuteNonQuery()
        {
            if (_conn.Trace)
            {
                Debug.WriteLine("Executing: " + this);
            }

            SQLite3.Result r    = SQLite3.Result.OK;
            IntPtr         stmt = Prepare();

            r = SQLite3.Step(stmt);
            Finalize(stmt);
            if (r == SQLite3.Result.Done)
            {
                int rowsAffected = SQLite3.Changes(_conn.Handle);
                return(rowsAffected);
            }

            if (r == SQLite3.Result.Error)
            {
                string msg = SQLite3.GetErrmsg(_conn.Handle);
                throw SQLiteException.New(r, msg);
            }

            if (r == SQLite3.Result.Constraint)
            {
                if (SQLite3.ExtendedErrCode(_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull)
                {
                    throw NotNullConstraintViolationException.New(r, SQLite3.GetErrmsg(_conn.Handle));
                }
            }

            throw SQLiteException.New(r, r.ToString());
        }
예제 #8
0
        public int ExecuteNonQuery()
        {
            if (_conn.Trace)
            {
                _conn.InvokeTrace("Executing: " + this);
            }
            SQLite3.Result result = SQLite3.Result.OK;
            lock (_conn.SyncObject)
            {
                IntPtr stmt = Prepare();
                result = SQLite3.Step(stmt);
                Finalize(stmt);
            }
            switch (result)
            {
            case SQLite3.Result.Done:
                return(SQLite3.Changes(_conn.Handle));

            case SQLite3.Result.Error:
            {
                string errmsg = SQLite3.GetErrmsg(_conn.Handle);
                throw SQLiteException.New(result, errmsg);
            }

            case SQLite3.Result.Constraint:
                if (SQLite3.ExtendedErrCode(_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull)
                {
                    throw NotNullConstraintViolationException.New(result, SQLite3.GetErrmsg(_conn.Handle));
                }
                break;
            }
            throw SQLiteException.New(result, result.ToString());
        }
예제 #9
0
        public static void Convert(string filename, string outFilename)
        {
            Trace.WriteLine("Opening " + filename);

            sqlite3 handle;

            SQLite3.Result result = SQLite3.Open(filename, out handle);

            try {
                if (result != SQLite3.Result.OK)
                {
                    string msg = SQLite3.GetErrmsg(handle);
                    throw new Exception(msg);
                }

                Trace.WriteLine("Opened");

                List <string> tableNames = new List <string>();
                var           writer     = new LiteWriter();

                GetTableNames(handle, tableNames);
                // build the table definitions, add the data
                CreateTables(handle, tableNames, writer);

                writer.Write(outFilename);
            } finally {
                if (handle != null)
                {
                    SQLite3.Close(handle);
                    handle = null;
                }
            }
        }
예제 #10
0
        private bool InitializeDB()
        {
            int    result     = -1;
            IntPtr db_namePtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(DB_NAME);

            result = GoodDynamics.Sqlite3Enc.sqlite3enc_open(db_namePtr, out _database);

            if (result != 0)
            {
                return(false);
            }

            string query     = SQL_CREATE_TABLE;
            IntPtr queryPtr  = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(query);
            IntPtr statement = IntPtr.Zero;
            IntPtr errorPtr  = IntPtr.Zero;

            var sqliteResult = SQLite3.Prepare2(_database, queryPtr, query.Length, out statement, out errorPtr);

            if (sqliteResult != SQLite3.Result.OK)
            {
                return(false);
            }

            SQLite3.Result sqliteenum = (SQLite3.Result)SQLite3.Step(statement);
            if ((SQLite3.Result)sqliteResult != SQLite3.Result.OK)
            {
                SQLite3.Finalize(statement);
                return(false);
            }

            SQLite3.Finalize(statement);
            return(true);
        }
        public static List <string> Tables(this SQLiteConnection connection)
        {
            const string  GET_TABLES_QUERY = "SELECT NAME from sqlite_master";
            List <string> tables           = new List <string> ();
            var           statement        = SQLite3.Prepare2(connection.Handle, GET_TABLES_QUERY);

            try {
                bool done = false;
                while (!done)
                {
                    SQLite3.Result result = SQLite3.Step(statement);
                    if (result == SQLite3.Result.Row)
                    {
                        var tableName = SQLite3.ColumnString(statement, 0);
                        tables.Add(tableName);
                    }
                    else if (result == SQLite3.Result.Done)
                    {
                        done = true;
                    }
                    else
                    {
                        throw SQLiteException.New(result, SQLite3.GetErrmsg(connection.Handle));
                    }
                }
            }
            finally {
                SQLite3.Finalize(statement);
            }
            return(tables);
        }
예제 #12
0
 /// <summary>
 /// Internal convenience method to throw exception on replication error
 /// and log exception at the same time.
 /// </summary>
 /// <param name="dbResult">result from an SQLite function, expected to
 /// return OK if successful or error code otherwise</param>
 /// <param name="message">information about action being performed (that failed)</param>
 private void IfNotOKThenThrowReplicationException(SQLite3.Result dbResult, string message)
 {
     if (dbResult != SQLite3.Result.OK)
     {
         var e = new ReplicationException(message, dbResult);
         logger.Error(e, "Sync failed - " + message);
         throw e;
     }
 }
 public void EnableLoadExtension(int onoff)
 {
     SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff);
     if (r != SQLite3.Result.OK)
     {
         string msg = SQLite3.GetErrmsg(Handle);
         throw SQLiteException.New(r, msg);
     }
 }
예제 #14
0
 public void EnableLoadExtension(int onoff)
 {
     SQLite3.Result result = SQLite3.EnableLoadExtension(Handle, onoff);
     if (result != 0)
     {
         string errmsg = SQLite3.GetErrmsg(Handle);
         throw SQLiteException.New(result, errmsg);
     }
 }
예제 #15
0
        public IntPtr Prepare()
        {
            IntPtr ppStmt = IntPtr.Zero;

            SQLite3.Result n = SQLite3.Prepare2(_db, CommandText, CommandText.Length, out ppStmt, IntPtr.Zero);
            if (n != SQLite3.Result.OK)
            {
                throw new SQLiteException(n, SQLiteLastError());
            }
            BindAll(ppStmt);
            return(ppStmt);
        }
 //-------------------------------------------------------------------------------------------------------------
 public void DatabaseEditorOpenKey(string tDatabasePathEditor)
 {
     if (IsSecure())
     {
         string         tEditorPass      = NWDAppConfiguration.SharedInstance().GetEditorPass();
         SQLite3.Result trResultPassword = SQLite3.Key(SQLiteEditorHandle, tEditorPass, tEditorPass.Length);
         if (trResultPassword != SQLite3.Result.OK)
         {
             throw SQLiteException.New(trResultPassword, string.Format("Could not open database file with password: {0} ({1})", tDatabasePathEditor, trResultPassword));
         }
     }
 }
 //-------------------------------------------------------------------------------------------------------------
 public void DatabaseAccountOpenKey(string tDatabasePathAccount, string sSurProtection)
 {
     if (IsSecure())
     {
         string         tAccountPass     = NWDAppConfiguration.SharedInstance().GetAccountPass(sSurProtection);
         SQLite3.Result trResultPassword = SQLite3.Key(SQLiteDeviceHandle, tAccountPass, tAccountPass.Length);
         if (trResultPassword != SQLite3.Result.OK)
         {
             throw SQLiteException.New(trResultPassword, string.Format("Could not open database file with password: {0} ({1})", tDatabasePathAccount, trResultPassword));
         }
     }
 }
        public int ExecuteNonQuery(object[] source)
        {
            if (this.Connection.Trace)
            {
                Debug.WriteLine("Executing: " + this.CommandText);
            }

            SQLite3.Result r = SQLite3.Result.OK;

            if (!this.Initialized)
            {
                this.Statement   = Prepare();
                this.Initialized = true;
            }

            //bind the values.
            if (source != null)
            {
                for (int i = 0; i < source.Length; i++)
                {
                    SQLiteCommand.BindParameter(this.Statement, i + 1, source[i], this.Connection.StoreDateTimeAsTicks);
                }
            }
            r = SQLite3.Step(this.Statement);

            if (r == SQLite3.Result.Done)
            {
                int rowsAffected = SQLite3.Changes(this.Connection.Handle);
                SQLite3.Reset(this.Statement);
                return(rowsAffected);
            }

            if (r == SQLite3.Result.Error)
            {
                string msg = SQLite3.GetErrmsg(this.Connection.Handle);
                SQLite3.Reset(this.Statement);
                throw SQLiteException.New(r, msg);
            }

            if (r == SQLite3.Result.Constraint &&
                SQLite3.ExtendedErrCode(this.Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull)
            {
                SQLite3.Reset(this.Statement);
                throw NotNullConstraintViolationException.New(r, SQLite3.GetErrmsg(this.Connection.Handle));
            }

            SQLite3.Reset(this.Statement);
            throw SQLiteException.New(r, r.ToString());
        }
예제 #19
0
        public int ExecuteNonQuery <T>(T toInsert)
        {
            IntPtr stmt;

            SQLite3.Result n = SQLite3.Prepare2(_db, CommandText, CommandText.Length, out stmt, IntPtr.Zero);
            if (n != SQLite3.Result.OK)
            {
                throw new SQLiteException(n, SQLiteLastError());
            }

            var props = GetProps(typeof(T));
            var ncols = SQLite3.ColumnCount(stmt);
            var cols  = new System.Reflection.PropertyInfo[ncols];

            _bindings.Clear();
            for (int i = 0; i < props.Length; i++)
            {
                Bind("@" + props[i].Name, props[i].GetValue(toInsert, null));
            }
            BindAll(stmt);
            var r = SQLite3.Step(stmt);

            switch (r)
            {
            case SQLite3.Result.Error:
                string msg = SQLite3.GetErrmsg(_db);
                SQLite3.Finalize(stmt);
                throw new SQLiteException(r, msg);

            case SQLite3.Result.Done:
                int rowsAffected = SQLite3.Changes(_db);
                SQLite3.Finalize(stmt);
                return(rowsAffected);

            case SQLite3.Result.CannotOpen:
                SQLite3.Finalize(stmt);
                throw new SQLiteException(r, "Cannot open database file");

            case SQLite3.Result.Constraint:
                string msgC = SQLite3.GetErrmsg(_db);
                SQLite3.Finalize(stmt);
                throw new SQLiteException(r, msgC);

            default:
                SQLite3.Finalize(stmt);
                throw new SQLiteException(r, "Unknown error");
            }
        }
예제 #20
0
        public int ExecuteNonQuery(object[] source)
        {
            if (Connection.Trace)
            {
                Connection.InvokeTrace("Executing: " + CommandText);
            }
            SQLite3.Result result = SQLite3.Result.OK;
            if (!Initialized)
            {
                Statement   = Prepare();
                Initialized = true;
            }
            if (source != null)
            {
                for (int i = 0; i < source.Length; i++)
                {
                    SQLiteCommand.BindParameter(Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks);
                }
            }
            result = SQLite3.Step(Statement);
            switch (result)
            {
            case SQLite3.Result.Done:
            {
                int result2 = SQLite3.Changes(Connection.Handle);
                SQLite3.Reset(Statement);
                return(result2);
            }

            case SQLite3.Result.Error:
            {
                string errmsg = SQLite3.GetErrmsg(Connection.Handle);
                SQLite3.Reset(Statement);
                throw SQLiteException.New(result, errmsg);
            }

            case SQLite3.Result.Constraint:
                if (SQLite3.ExtendedErrCode(Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull)
                {
                    SQLite3.Reset(Statement);
                    throw NotNullConstraintViolationException.New(result, SQLite3.GetErrmsg(Connection.Handle));
                }
                break;
            }
            SQLite3.Reset(Statement);
            throw SQLiteException.New(result, result.ToString());
        }
예제 #21
0
        public void Open()
        {
            SQLite3.Result n = SQLite3.Open(Database, out _db);
            if (n != SQLite3.Result.OK)
            {
                throw new SQLiteException(SQLite3.Result.OK, "Could not open database file: " + Database);
            }
            string errMsg = string.Empty;

            /*n = SQLite3.(_db, "PRAGMA journal_mode=PERSIST", (SQLite3.dx)this.callback, null, ref errMsg);
             * if (n != SQLite3.SQLITE_OK)
             * {
             *  SQLite3.SQLite3_close(_db);
             *  _db = null;
             *  _open = false;
             *  throw new SQLiteException(n, "Cannot set journal mode to PERSIST: " + Database);
             * }       */
            _open = true;
        }
예제 #22
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);
        }
예제 #23
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);
        }
예제 #24
0
 public void Close()
 {
     if (Opened && this.Handle != NullHandle)
     {
         try {
             if (Mappings != null)
             {
                 foreach (TableMapping sqlInsertCommand in Mappings.Values)
                 {
                     sqlInsertCommand.Dispose();
                 }
             }
             SQLite3.Result r = SQLite3.Close(this.Handle);
             if (r != SQLite3.Result.OK)
             {
                 string msg = SQLite3.GetErrmsg(this.Handle);
                 throw SQLiteException.New(r, msg);
             }
         } finally {
             this.Handle = NullHandle;
             Opened      = false;
         }
     }
 }
예제 #25
0
 private void Dispose(bool disposing)
 {
     if (Opened && NullHandle != Handle)
     {
         try {
             if (null != Mappings)
             {
                 foreach (var item in Mappings.Values)
                 {
                     item.Dispose();
                 }
             }
             SQLite3.Result r = SQLite3.Close(Handle);
             if (r != SQLite3.Result.OK)
             {
                 string msg = SQLite3.GetErrmsg(Handle);
                 throw SQLiteException.New(r, msg);
             }
         } finally {
             Handle = NullHandle;
             Opened = false;
         }
     }
 }
예제 #26
0
 public static NotNullConstraintViolationException New(SQLite3.Result r, string message, TableMapping mapping,
                                                       object obj)
 {
     return(new NotNullConstraintViolationException(r, message, mapping, obj));
 }
예제 #27
0
 public new static NotNullConstraintViolationException New(SQLite3.Result r, string message)
 {
     return(new NotNullConstraintViolationException(r, message));
 }
예제 #28
0
 protected NotNullConstraintViolationException(SQLite3.Result r, string message) :
     this(r, message, null, null)
 {
 }
예제 #29
0
 public static SQLiteException New(SQLite3.Result r, string message)
 {
     return(new SQLiteException(r, message));
 }
예제 #30
0
 protected SQLiteException(SQLite3.Result r, string message) : base(message)
 {
     this.Result = r;
 }
예제 #31
0
		public SQLiteException(SQLite3.Result r, string message)
			: base(message) {
			Result = r;
		}