Exemple #1
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");
            }
        }
Exemple #2
0
        public virtual void AfterDelete()
        {
            Type superClass = Reflections.GetBaseType(this.GetType());

            if (superClass != typeof(PersistentEntity))
            {
                PersistentEntity superObject = ((PersistentEntity)Reflections.GetSuperInstanceFromInstance(this));
                superObject.Delete();
            }
        }
        ///** Creates a <code>JSONObject</code> from the object.
        // *
        // * @param object to be converted in a <code>JSONObject</code>.
        // * @return the generated <code>JSONObject</code>.
        // */
        //public JSONObject wrap(E object) {
        //	JSONObject _JSONObject = new JSONObject();
        //	try {
        //		Class superClass = domainClass.getSuperclass();
        //		PersistentEntity superObject = null;
        //		if (superClass != PersistentEntity.class) {
        //		                try {
        //		                    _JSONObject = ((PersistentEntity) superClass.newInstance()).getTableData().wrap(object);
        //		                } catch (Exception e) {
        //		                    e.printStackTrace();
        //		                }
        //		            }
        //		            for (Field field : getColumnFields()) {
        //		                _JSONObject = EntityFieldHelper.setFieldInJSONObject(object, field, _JSONObject);
        //		            }
        //		        } catch (Exception e) {
        //		            e.printStackTrace();
        //		        }
        //		        return _JSONObject;
        //		    }

        //		    /** Creates a <code>JSONArray</code> from the object.
        //		     *
        //		     * @param list to be converted in a <code>JSONArray</code>.
        //		     * @return the generated <code>JSONArray</code>.
        //		     */
        //		    public JSONArray wrap(List<E> list) {
        //	JSONArray _JSONArray = new JSONArray();
        //	if (list != null) {
        //		for (E object : list) {
        //			_JSONArray.put(wrap(object));
        //		}
        //	}
        //	return _JSONArray;
        //}

        private PersistentEntity GetSuperObject(long id)
        {
            Type             superClass  = Reflections.GetBaseType(tableMapping.type);
            PersistentEntity superObject = null;

            if (superClass != typeof(PersistentEntity))
            {
                superObject = ((PersistentEntity)Activator.CreateInstance(superClass)).GetTableData().Get(id);
            }
            return(superObject);
        }
Exemple #4
0
        public virtual bool BeforeUpdate()
        {
            Type superClass = Reflections.GetBaseType(this.GetType());

            if (superClass != typeof(PersistentEntity))
            {
                PersistentEntity superObject = ((PersistentEntity)Reflections.GetSuperInstanceFromInstance(this));
                if (superObject.Update())
                {
                    this.SetId(superObject.GetId());
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
        /** 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);
            }
        }
        /** 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);
            }
        }
Exemple #7
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);
        }