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 TableMapping()
        {
            List <PropertyInfo> properties = Reflections.GetDeclaredFields(type);
            List <ColumnInfo>   cols       = new List <ColumnInfo>();

            foreach (PropertyInfo property in properties)
            {
                var ignore = false;                //property.GetCustomAttributes(typeof(IgnoreAttribute), true).Count() > 0;
                if (property.CanWrite && !ignore)
                {
                    cols.Add(new ColumnInfo(property));
                }
            }
            columns = cols.ToArray();
        }
Exemple #5
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);
        }
Exemple #6
0
        private void PerformActionOnChilds(Action action)
        {
            ColumnInfo[] fields = GetTableData().GetTableMapping().columns;
            foreach (ColumnInfo field in fields)
            {
                IList  childs   = new List <PersistentEntity>();
                String mappedBy = "";
                if (Reflections.IsAttributePresent(field.property, typeof(HasMany)))
                {
                    HasMany hasMany = (HasMany)Reflections.GetAttribute(field.property, typeof(HasMany));
                    mappedBy = hasMany.mappedBy;
                    childs   = (IList)field.property.GetValue(this);
                }
                else if (Reflections.IsAttributePresent(field.property, typeof(HasOne)))
                {
                    HasOne hasOne = (HasOne)Reflections.GetAttribute(field.property, typeof(HasOne));
                    mappedBy = hasOne.mappedBy;
                    childs.Add((PersistentEntity)field.property.GetValue(this));
                }
                if (childs != null)
                {
                    foreach (PersistentEntity child in childs)
                    {
                        switch (action)
                        {
                        case Action.Insert:
                            PropertyInfo childField = Reflections.GetDeclaredFieldRecursively(mappedBy, child.GetType(), typeof(PersistentEntity));
                            childField.SetValue(child, this);
                            child.Insert();
                            break;

                        case Action.Update:
                            child.Update();
                            break;

                        case Action.Delete:
                            child.Delete();
                            break;
                        }
                    }
                }
            }
        }
        /**
         * Generate the column constraints for SQL from a <code>Field</code> if <code>Constraint</code> annotation is present
         * @param field the field of the persistent entity
         * @return the column constraints
         */
        private static String ColumnConstraints(ColumnInfo column)
        {
            String result = "";

            if (Reflections.IsAttributePresent(column.property, typeof(Constraints)))
            {
                Constraints constraints = (Constraints)Reflections.GetAttribute(column.property, typeof(Constraints));
                if (constraints.unique == true)
                {
                    result += " UNIQUE";
                }
                if (constraints.nullable == false)
                {
                    result += " NOT NULL";
                }
            }
            //        if (EntityFieldHelper.isSingleRelationField(field) && !field.isAnnotationPresent(HasOne.class)) {
            //            result += " REFERENCES " + getTableName((Class<PersistentEntity>) field.getType()) + "(" + Configuration.ID_COLUMN_NAME + ")";
            //            if (field.isAnnotationPresent(BelongsTo.class)) {
            //                result += " ON DELETE CASCADE";
            //            }
            //        }
            return(result);
        }
        /******************************************************** Table queries */

        /**
         * Generate the <code>CREATE TABLE<code> query from a <code>PersistentEntity</code> class
         * @param domainClass the class of the persistent entity, must extends <code>PersistentEntity</code>
         * @return the generated <code>CREATE TABLE<code> query
         */
        public static String CreateTableQuery(TableMapping <E> table)
        {
            ColumnInfo[] columns    = table.columns;
            String       sqlCreate  = "CREATE TABLE IF NOT EXISTS " + table.name + " (" + Configuration.ID_COLUMN_NAME + " INTEGER PRIMARY KEY AUTOINCREMENT";
            Type         superClass = Reflections.GetBaseType(table.type);

            /*if (superClass != typeof(PersistentEntity)) {
             *      //TODO: hay que ver en que orden se crean las clases y como corregir que la referencia no existe
             *      //TODO: en principio esta resuelto con foreign_check = O;
             *      sqlCreate += " REFERENCES " + superClass.Name + "(" + Configuration.ID_COLUMN_NAME + ") ON DELETE CASCADE";
             *      //TODO: esto lo hice por ON DELETE CASCADE pero no funciona :S
             * }*/
            for (int i = 0; i < columns.Length; i++)
            {
                ColumnInfo column = columns[i];
                if (!column.IsMultipleRelationship)
                {
                    sqlCreate += ", " + ColumnDeclaration(column);
                }
            }
            sqlCreate += ");";
            //        TODO: Cuidado con estos replace que son solo esteticos y pueden joder la sentencia
            return(sqlCreate.Replace("  ", " ").Replace(" ,", ","));
        }
        /** 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);
            }
        }
Exemple #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);
            }
        }
Exemple #11
0
        /** Creates a <code>ContentValues</code> from the object.
         *
         * @param object to be converted in a <code>ContentValues</code> for persistent context
         * @return the generated <code>ContentValues</code>.
         */
        public Dictionary <String, object> GetContentValues(E obj)
        {
            Dictionary <String, object> values = new Dictionary <String, object>();

            if (obj.GetId() != -1)
            {
                values[Configuration.ID_COLUMN_NAME] = obj.GetId();
            }

            foreach (ColumnInfo column in this.tableMapping.columns)
            {
                if (!column.IsMultipleRelationship)
                {
                    if (column.IsSingleRelationship)
                    {
                        if (Reflections.IsAttributePresent(column.property, typeof(BelongsTo)) || !Reflections.IsAttributePresent(column.property, typeof(HasOne)))
                        {
                            values[QueryGenerator <E> .ColumnName(column)] = ((PersistentEntity)column.property.GetValue(obj)).GetServerId();
                        }
                    }
                    else
                    {
                        values[QueryGenerator <E> .ColumnName(column)] = column.property.GetValue(obj);
                    }
                }
            }
            return(values);
        }
Exemple #12
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);
        }