Beispiel #1
0
        public List <E> GetAllByField(String key, Object value)
        {
            Open();
            List <E> listObjects = new List <E>();
            String   sqlQuery    = QueryGenerator <E> .SelectQuery(tableMapping, key + "='" + value.ToString() + "'");

            Cursor cursor = databaseManager.Select(sqlQuery);

            try {
                for (cursor.MoveToNext(); !cursor.IsAfterLast(); cursor.MoveToNext())
                {
                    E obj = CursorToEntity(cursor);
                    listObjects.Add(obj);
                }
            } catch (Exception e) {
                SQLConsole.WriteLine(e.StackTrace);
            } finally {
                try {
                    cursor.Close();
                } catch (Exception e) {
                    SQLConsole.WriteLine(e.StackTrace);
                }
                Close();
            }
            return(listObjects);
        }
Beispiel #2
0
        public List <E> GetAllWithCriteria(CriteriaBuilder criteria)
        {
            List <E> listObjects = new List <E>();

            Open();
            String sqlQuery = QueryGenerator <E> .SelectQuery(tableMapping, criteria.Query(), criteria.GroupBy(), criteria.Having(), criteria.OrederBy(), criteria.Limit(), criteria.Distinct());

            SQLConsole.WriteLine(sqlQuery);
            Cursor cursor = databaseManager.Select(sqlQuery);

            try {
                for (cursor.MoveToNext(); !cursor.IsAfterLast(); cursor.MoveToNext())
                {
                    E obj = CursorToEntity(cursor);
                    listObjects.Add(obj);
                }
            } catch (Exception e) {
                SQLConsole.WriteLine(e.StackTrace);
            } finally {
                try {
                    cursor.Close();
                } catch (Exception e) {
                    SQLConsole.WriteLine(e.StackTrace);
                }
                Close();
            }
            return(listObjects);
        }
Beispiel #3
0
        /*public SQLiteAsyncConnection GetDatabaseAsync() {
         *      return new SQLiteAsyncConnection(dbPath);
         * }*/

        public void OnCreate(SQLiteConnection database)
        {
            SQLConsole.WriteLine("Creating database file...");
            SQLConsole.WriteLine(" - Name: " + Configuration.DATABASE_NAME);
            SQLConsole.WriteLine(" - Version: " + Configuration.DATABASE_VERSION);
            SQLConsole.WriteLine(" - Create: " + Configuration.DATABASE_CREATE);
            if (Configuration.DATABASE_CREATE.Equals("create") || Configuration.DATABASE_CREATE.Equals("drop-create"))
            {
                database.Execute("PRAGMA FOREIGN_KEYS = OFF");                //validateDatabase(database);
                try {
                    List <TypeInfo> types = Reflections.GetTypesFromAssembly(Configuration.DOMAIN_PACKAGE);
                    foreach (TypeInfo type in types)
                    {
                        if (type.IsSubclassOf(typeof(PersistentEntity)))
                        {
                            PersistentEntity entity = (PersistentEntity)Activator.CreateInstance(type.AsType());

                            //String query = (String)typeof(QueryGenerator<PersistentEntity>).GetTypeInfo().MakeGenericType(type.AsType()).GetTypeInfo().GetDeclaredMethod("CreateTableQuery").Invoke(null, new object[] { entity.GetTableData() });
                            //Execute(QueryGenerator<PersistentEntity>.CreateTableQuery((entity.GetTableData<PersistentEntity>()).GetTableMapping()));
                            dynamic tableData = entity.GetTableData();                            //GetType().GetTypeInfo().GetDeclaredMethod("GetTableData").MakeGenericMethod(entity.GetType()).Invoke(entity, null);
                            //Reflections.CastTo();

                            String query = (String)typeof(QueryGenerator <>).GetTypeInfo().MakeGenericType(type.AsType()).GetTypeInfo().GetDeclaredMethod("CreateTableQuery").Invoke(null, new object[] { tableData.GetTableMapping() });
                            //QueryGenerator<PersistentEntity>.CreateTableQuery(tableData);
                            //dynamic tableData = (EntityManager<PersistentEntity>)Convert.ChangeType(entity.GetType().GetTypeInfo().GetDeclaredMethod("GetTableData").MakeGenericMethod(entity.GetType()).Invoke(entity, null), typeof(EntityManager<PersistentEntity>));
                            Execute(query);
                        }
                    }
                } catch (System.IO.FileNotFoundException e) {
                    Debug.WriteLine(e.ToString());
                }
                database.Execute("PRAGMA FOREIGN_KEYS = ON");
            }
        }
Beispiel #4
0
        public E GetByField(String key, Object value)
        {
            Open();
            E      obj      = null;
            String sqlQuery = QueryGenerator <E> .SelectQuery(tableMapping, key + "='" + value.ToString() + "'");

            Cursor cursor = databaseManager.Select(sqlQuery);

            try {
                if (cursor.MoveToNext())
                {
                    obj = CursorToEntity(cursor);
                }
            } catch (Exception e) {
                SQLConsole.WriteLine(e.StackTrace);
            } finally {
                try {
                    cursor.Close();
                } catch (Exception e) {
                    SQLConsole.WriteLine(e.StackTrace);
                }
                Close();
            }
            return(obj);
        }
Beispiel #5
0
        public int Execute(String query)
        {
            SQLConsole.WriteLine(query);
            int result = database.Execute(query);

            return(result);
        }
Beispiel #6
0
        public Cursor Select(String query)
        {
            SQLConsole.WriteLine(query);
            Cursor cursor = new Cursor(this.GetDatabase(), query);

            cursor.Open();
            return(cursor);
        }
Beispiel #7
0
        public virtual dynamic GetTableData()
        {
            dynamic tableData;

            try {
                FieldInfo property = GetType().GetTypeInfo().GetDeclaredField(Configuration.ACCESS_PROPERTY);
                tableData = property.GetValue(this);
            } catch (Exception e) {
                SQLConsole.WriteLine(e.StackTrace);
                tableData = null;
            }
            return(tableData);
        }
Beispiel #8
0
        public List <E> GetAllByFieldInList(String key, Object[] values)
        {
            List <E> listObjects = new List <E>();
            String   inClause    = "(";

            for (int i = 0; i < values.Length; i++)
            {
                inClause += "'" + values[i].ToString() + "'";
                if (i != (values.Length - 1))
                {
                    inClause += ",";
                }
            }
            inClause += ")";

            Open();
            String sqlQuery = QueryGenerator <E> .SelectQuery(tableMapping, key + " in " + inClause);

            Cursor cursor = databaseManager.Select(sqlQuery);

            try {
                for (cursor.MoveToNext(); !cursor.IsAfterLast(); cursor.MoveToNext())
                {
                    E obj = CursorToEntity(cursor);
                    listObjects.Add(obj);
                }
            } catch (Exception e) {
                SQLConsole.WriteLine(e.StackTrace);
            } finally {
                try {
                    cursor.Close();
                } catch (Exception e) {
                    SQLConsole.WriteLine(e.StackTrace);
                }
                Close();
            }
            return(listObjects);
        }
Beispiel #9
0
        /** Creates an object from the stored data in the cursor.
         *
         * @param cursor with the data of the query. It's should be pointing to the needed row.
         * @return the generated instance.
         */
        public E CursorToEntity(Cursor cursor)
        {
            try {
                E obj = (E)Activator.CreateInstance(tableMapping.type);

                obj.SetId(cursor.GetValue <long>(Configuration.ID_COLUMN_NAME));

                /*foreach (ColumnInfo column in this.tableMapping.columns) {
                 *      //object value = typeof(Cursor).GetTypeInfo().GetDeclaredMethod("GetValue").MakeGenericMethod(column.propertyType).Invoke(cursor, new object[] { column.name });
                 *      object value = cursor.GetValue(column.name, column.propertyType);
                 *      column.property.SetValue(obj, value);
                 * }*/

                for (int i = 1; i <= this.tableMapping.columns.Length; i++)
                {
                    ColumnInfo column = this.tableMapping.columns[i - 1];
                    if (column.IsPrimitiveField)
                    {
                        object value = cursor.GetValue(i, column.propertyType);
                        column.property.SetValue(obj, value);
                    }
                    else if (column.IsSingleRelationship)
                    {
                        object           value          = cursor.GetValue <long>(i);
                        PersistentEntity relationObject = (PersistentEntity)Activator.CreateInstance(column.propertyType);
                        if (Reflections.IsAttributePresent(column.property, typeof(BelongsTo)) ||
                            (Reflections.IsAttributePresent(column.property, typeof(HasOne)) &&
                             ((HasOne)Reflections.GetAttribute(column.property, typeof(HasOne))).lazy))
                        {
                            relationObject.SetServerId((long)value);
                            column.property.SetValue(obj, relationObject);
                        }
                        else
                        {
                            value = relationObject.GetTableData().GetByServerId((dynamic)value);
                            column.property.SetValue(obj, value);
                        }
                    }
                    else if (column.IsMultipleRelationship)
                    {
                        if (Reflections.IsAttributePresent(column.property, typeof(HasMany)))
                        {
                            HasMany hasMany = (HasMany)Reflections.GetAttribute(column.property, typeof(HasMany));
                            if (hasMany.lazy)
                            {
                                column.property.SetValue(obj, Activator.CreateInstance(column.propertyType));
                            }
                            else
                            {
                                Type   relationType           = column.propertyType.GenericTypeArguments[0];
                                String columnName             = "id" + hasMany.mappedBy.ToUpper().ToCharArray()[0] + hasMany.mappedBy.Substring(1);
                                List <PersistentEntity> value = ((PersistentEntity)Activator.CreateInstance(relationType)).GetTableData().GetAllByField(columnName);
                                column.property.SetValue(obj, value);
                            }
                        }
                        else
                        {
                            throw new NotSupportedException("Use relationships not supported in lists, you must create an auxiliar table");
                        }
                    }
                }

                PersistentEntity superObject = GetSuperObject(obj.GetId());
                if (superObject != null)
                {
                    Reflections.SetInstanceFromSuperInstance(obj, superObject);
                }

                return(obj);
            } catch (Exception e) {
                SQLConsole.WriteLine(e.ToString());
                return(null);
            }
        }
Beispiel #10
0
        /** Creates an object from the stored data in the JSON.
         *
         * @param _JSONObject with the data of the object.
         * @return the generated instance.
         */
        public E Parse(JToken _JSONObject)
        {
            try {
                E obj = (E)Activator.CreateInstance(tableMapping.type);
                for (int i = 0; i < this.tableMapping.columns.Length; i++)
                {
                    ColumnInfo column = this.tableMapping.columns[i];
                    if (column.IsPrimitiveField)
                    {
                        if (_JSONObject[column.name] != null)
                        {
                            object value = column.propertyType == typeof(String) ? _JSONObject[column.name].Value <String>() : JsonConvert.DeserializeObject(_JSONObject[column.name].ToString(), column.propertyType);
                            column.property.SetValue(obj, value);
                        }
                        else
                        {
                            column.property.SetValue(obj, null);
                        }
                    }
                    else if (column.IsSingleRelationship)
                    {
                        object           value          = null;
                        PersistentEntity relationObject = (PersistentEntity)Activator.CreateInstance(column.propertyType);

                        if (_JSONObject[QueryGenerator <E> .ColumnName(column)] != null)
                        {
                            relationObject.SetServerId(JsonConvert.DeserializeObject <long>(_JSONObject[QueryGenerator <E> .ColumnName(column)].ToString()));
                            value = relationObject;
                        }
                        else if (_JSONObject[column.property.Name] != null)
                        {
                            value = relationObject.GetTableData().Parse(_JSONObject[column.name]);
                        }

                        column.property.SetValue(obj, value);
                    }
                    else if (column.IsMultipleRelationship)
                    {
                        if (_JSONObject[column.name] != null)
                        {
                            PersistentEntity        relationObject = (PersistentEntity)Activator.CreateInstance(column.propertyType.GenericTypeArguments[0]);
                            List <PersistentEntity> value          = relationObject.GetTableData().Parse(JArray.Parse(_JSONObject[column.name].ToString()));
                            column.property.SetValue(obj, value);
                        }
                        else
                        {
                            column.property.SetValue(obj, null);
                        }
                    }
                }

                Type baseType = Reflections.GetBaseType(this.tableMapping.type);
                if (baseType != typeof(PersistentEntity))
                {
                    Reflections.SetInstanceFromSuperInstance(obj, ((PersistentEntity)Activator.CreateInstance(baseType)).GetTableData().Parse(_JSONObject));
                }
                return(obj);
            } catch (Exception e) {
                SQLConsole.WriteLine(e.ToString());
                return(null);
            }
        }
Beispiel #11
0
        public void OnUpgrade(SQLiteConnection database, int oldVersion, int newVersion)
        {
            SQLConsole.WriteLine("Updating database file...");
            SQLConsole.WriteLine(" - Name: " + Configuration.DATABASE_NAME);
            SQLConsole.WriteLine(" - Version: " + oldVersion);

            if (Configuration.DATABASE_CREATE.Equals("drop-create"))
            {
                database.Execute("PRAGMA FOREIGN_KEYS = OFF");
                try {
                    List <TypeInfo> types = Reflections.GetTypesFromAssembly(Configuration.DOMAIN_PACKAGE);
                    foreach (TypeInfo type in types)
                    {
                        if (type.IsSubclassOf(typeof(PersistentEntity)))
                        {
                            PersistentEntity entity = (PersistentEntity)Activator.CreateInstance(type.AsType());

                            //String query = (String)typeof(QueryGenerator<PersistentEntity>).GetTypeInfo().MakeGenericType(type.AsType()).GetTypeInfo().GetDeclaredMethod("CreateTableQuery").Invoke(null, new object[] { entity.GetTableData() });
                            //Execute(QueryGenerator<PersistentEntity>.CreateTableQuery((entity.GetTableData<PersistentEntity>()).GetTableMapping()));
                            dynamic tableData = entity.GetTableData();                            //GetType().GetTypeInfo().GetDeclaredMethod("GetTableData").MakeGenericMethod(entity.GetType()).Invoke(entity, null);
                            //Reflections.CastTo();

                            String query = (String)typeof(QueryGenerator <>).GetTypeInfo().MakeGenericType(type.AsType()).GetTypeInfo().GetDeclaredMethod("DropTableQuery").Invoke(null, new object[] { tableData.GetTableMapping() });
                            //QueryGenerator<PersistentEntity>.CreateTableQuery(tableData);
                            //dynamic tableData = (EntityManager<PersistentEntity>)Convert.ChangeType(entity.GetType().GetTypeInfo().GetDeclaredMethod("GetTableData").MakeGenericMethod(entity.GetType()).Invoke(entity, null), typeof(EntityManager<PersistentEntity>));
                            Execute(query);
                        }
                    }
                } catch (System.IO.FileNotFoundException e) {
                    Debug.WriteLine(e.ToString());
                }
            }
            else if (Configuration.DATABASE_CREATE.Equals("update"))
            {
                database.Execute("PRAGMA FOREIGN_KEYS = OFF");

                /*ArrayList<Table> newTables = getDomainStructure();
                 * ArrayList<Table> oldTables = getDatabaseStructure(database);
                 * for (Table oldTable : oldTables) {
                 *      if (!newTables.contains(oldTable)) {
                 *              String dropTableQuery = "DROP TABLE IF EXISTS " + oldTable.name;
                 *              SQLConsole.Log(dropTableQuery);
                 *              database.execSQL(dropTableQuery);
                 *      } else {
                 *              // TODO: comprobar campos
                 *      }
                 * }
                 * for (Table newTable : newTables) {
                 *      if (!oldTables.contains(newTable)) {
                 *              String createTableQuery = SQLQueryGenerator.getCreateTable(newTable.type);
                 *              SQLConsole.Log(createTableQuery);
                 *              database.execSQL(createTableQuery);
                 *      }
                 * }*/
                database.Execute("PRAGMA FOREIGN_KEYS = ON");

                //validateDatabase(database);
            }

            OnCreate(database);
        }