Android Open Source - NexusData Database Helper






From Project

Back to project page NexusData.

License

The source code is released under:

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCT...

If you think the Android project NexusData listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.github.dkharrat.nexusdata.store;
//w w w.j  ava2s  . c  o  m
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteCursorDriver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQuery;
import com.github.dkharrat.nexusdata.core.ManagedObject;
import com.github.dkharrat.nexusdata.metamodel.Entity;
import com.github.dkharrat.nexusdata.metamodel.ObjectModel;
import com.github.dkharrat.nexusdata.metamodel.Property;
import com.github.dkharrat.nexusdata.metamodel.Relationship;
import com.github.dkharrat.nexusdata.utils.SqlTableBuilder;
import com.github.dkharrat.nexusdata.utils.android.CursorUtil;
import com.github.dkharrat.nexusdata.utils.android.SQLiteDatabaseHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;
import java.util.UUID;

class DatabaseHelper extends SQLiteDatabaseHelper {

    private static final Logger LOG = LoggerFactory.getLogger(DatabaseHelper.class);

    private static final boolean DEBUG_QUERIES = false;

    private static final String METADATA_TABLE_NAME = "nxs_metadata";
    private static final String METADATA_COLUMN_VERSION = "version";
    private static final String METADATA_COLUMN_UUID = "uuid";

    private ObjectModel model;

    DatabaseHelper(Context context, File path, ObjectModel model) {
        super(context, path, DEBUG_QUERIES ? new SQLiteCursorLoggerFactory() : null, model.getVersion());
        this.model = model;
    }

    static <T extends ManagedObject> String getTableName(Entity<T> entity) {
        return entity.getType().getSimpleName();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        LOG.info("Creating database: " + db.getPath());

        // create the metadata table
        SqlTableBuilder tableBuilder = new SqlTableBuilder();
        tableBuilder.tableName(METADATA_TABLE_NAME);
        tableBuilder.column(METADATA_COLUMN_VERSION, SqlTableBuilder.ColumnType.INTEGER).setUnique(SqlTableBuilder.ConflictAction.ABORT);
        tableBuilder.column(METADATA_COLUMN_UUID, SqlTableBuilder.ColumnType.TEXT);
        tableBuilder.createTable(db);

        for (Entity<?> entity : model.getEntities()) {
            tableBuilder = new SqlTableBuilder();
            tableBuilder.tableName(getTableName(entity));
            tableBuilder.primaryKey(AndroidSqlPersistentStore.COLUMN_ID_NAME, SqlTableBuilder.ColumnType.INTEGER);

            for (Property property : entity.getProperties()) {
                SqlTableBuilder.ColumnType columnType;
                Class<?> propType = property.getType();

                if (property.isRelationship()) {
                    Relationship relationship = (Relationship) property;
                    if (relationship.isToOne()) {
                        columnType = SqlTableBuilder.ColumnType.INTEGER;
                    } else {
                        continue;
                    }
                }
                else if (int.class.isAssignableFrom(propType) || Integer.class.isAssignableFrom(propType) ||
                        long.class.isAssignableFrom(propType) || Long.class.isAssignableFrom(propType)) {
                    columnType = SqlTableBuilder.ColumnType.INTEGER;
                } else if (String.class.isAssignableFrom(propType) || Enum.class.isAssignableFrom(propType)) {
                    columnType = SqlTableBuilder.ColumnType.TEXT;
                } else if (boolean.class.isAssignableFrom(propType) || Boolean.class.isAssignableFrom(propType)) {
                    columnType = SqlTableBuilder.ColumnType.BOOLEAN;
                } else if (float.class.isAssignableFrom(propType) || Float.class.isAssignableFrom(propType)) {
                    columnType = SqlTableBuilder.ColumnType.REAL;
                } else if (double.class.isAssignableFrom(propType) || Double.class.isAssignableFrom(propType)) {
                    columnType = SqlTableBuilder.ColumnType.REAL;
                } else if (Date.class.isAssignableFrom(property.getType())) {
                    columnType = SqlTableBuilder.ColumnType.DATETIME;
                } else {
                    throw new UnsupportedOperationException("Unsupported field type " + property.getType() + " for " + entity.getType());
                }

                tableBuilder.column(property.getName(), columnType);
                if (property.isRequired()) {
                    tableBuilder.setNullable(false);
                }
            }

            tableBuilder.createTable(db);
        }

        generateMetadata(db);
    }

    private UUID generateMetadata(SQLiteDatabase db) {
        UUID uuid = UUID.randomUUID();

        ContentValues metadataValues = new ContentValues();
        metadataValues.put(METADATA_COLUMN_VERSION, model.getVersion());
        metadataValues.put(METADATA_COLUMN_UUID, uuid.toString());
        db.insert(METADATA_TABLE_NAME, null, metadataValues);

        return uuid;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        LOG.info("Upgrading DB from " + oldVersion + " to " + newVersion);

        //TODO: ideally, DB should be migrated to newer version as opposed to re-creating it
        clearDatabase(db);
    }

    private void clearDatabase(SQLiteDatabase db) {
        dropTables(db);
        onCreate(db);
    }

    private static void dropTables(SQLiteDatabase db) {
        String TABLES_SQL = "select 'drop table if exists ' || name || ';' from sqlite_master where type='table' "+
                "and name not like 'android%' "+
                "and name not like 'sqlite%';"+
                "and name not like '"+METADATA_TABLE_NAME+"';";
        Cursor c = db.rawQuery(TABLES_SQL, null);
        while(c.moveToNext()) {
            String dropTableSql = c.getString(0);
            LOG.info("Executing: " + dropTableSql);
            db.execSQL(dropTableSql);
        }
    }

    static UUID getDatabaseUuid(SQLiteDatabase db, int version) {
        UUID uuid = null;
        Cursor cursor = db.query(METADATA_TABLE_NAME, null, METADATA_COLUMN_VERSION+"=?", new String[]{String.valueOf(version)}, null, null, null);
        if (cursor.moveToFirst()) {
            uuid = UUID.fromString(CursorUtil.getString(cursor, METADATA_COLUMN_UUID));
        }
        return uuid;
    }

    private static class SQLiteCursorLoggerFactory implements SQLiteDatabase.CursorFactory {

        @SuppressWarnings("deprecation")
        @Override
        public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,
                                String editTable, SQLiteQuery query) {
            LOG.debug(query.toString());

            // non-deprecated API is only available in API 11
            return new SQLiteCursor(db, masterQuery, editTable, query);
        }
    }
}




Java Source Code List

com.github.dkharrat.nexusdata.core.AtomicStore.java
com.github.dkharrat.nexusdata.core.ChangedObjectsSet.java
com.github.dkharrat.nexusdata.core.FaultingSet.java
com.github.dkharrat.nexusdata.core.FetchRequest.java
com.github.dkharrat.nexusdata.core.IncrementalStore.java
com.github.dkharrat.nexusdata.core.ManagedObject.java
com.github.dkharrat.nexusdata.core.NoSuchPropertyException.java
com.github.dkharrat.nexusdata.core.ObjectContextNotifier.java
com.github.dkharrat.nexusdata.core.ObjectContext.java
com.github.dkharrat.nexusdata.core.ObjectID.java
com.github.dkharrat.nexusdata.core.ObjectsChangedNotification.java
com.github.dkharrat.nexusdata.core.PersistentStoreCoordinator.java
com.github.dkharrat.nexusdata.core.PersistentStoreRequest.java
com.github.dkharrat.nexusdata.core.PersistentStore.java
com.github.dkharrat.nexusdata.core.SaveChangesRequest.java
com.github.dkharrat.nexusdata.core.SortDescriptor.java
com.github.dkharrat.nexusdata.core.StoreCacheNode.java
com.github.dkharrat.nexusdata.metamodel.Attribute.java
com.github.dkharrat.nexusdata.metamodel.Entity.java
com.github.dkharrat.nexusdata.metamodel.ObjectModelJsonParser.java
com.github.dkharrat.nexusdata.metamodel.ObjectModel.java
com.github.dkharrat.nexusdata.metamodel.Property.java
com.github.dkharrat.nexusdata.metamodel.Relationship.java
com.github.dkharrat.nexusdata.modelgen.ModelGenerator.java
com.github.dkharrat.nexusdata.modelgen.Startup.java
com.github.dkharrat.nexusdata.modelgen.metamodel.Attribute.java
com.github.dkharrat.nexusdata.modelgen.metamodel.Entity.java
com.github.dkharrat.nexusdata.modelgen.metamodel.EnumProperty.java
com.github.dkharrat.nexusdata.modelgen.metamodel.ModelWrapper.java
com.github.dkharrat.nexusdata.modelgen.metamodel.Model.java
com.github.dkharrat.nexusdata.modelgen.metamodel.Property.java
com.github.dkharrat.nexusdata.modelgen.metamodel.Relationship.java
com.github.dkharrat.nexusdata.predicate.ComparisonPredicate.java
com.github.dkharrat.nexusdata.predicate.CompoundPredicate.java
com.github.dkharrat.nexusdata.predicate.ConstantExpression.java
com.github.dkharrat.nexusdata.predicate.ExpressionBuilder.java
com.github.dkharrat.nexusdata.predicate.ExpressionVisitor.java
com.github.dkharrat.nexusdata.predicate.Expression.java
com.github.dkharrat.nexusdata.predicate.FieldPathExpression.java
com.github.dkharrat.nexusdata.predicate.NotPredicate.java
com.github.dkharrat.nexusdata.predicate.PredicateBuilder.java
com.github.dkharrat.nexusdata.predicate.Predicate.java
com.github.dkharrat.nexusdata.predicate.ThisExpression.java
com.github.dkharrat.nexusdata.predicate.parser.ComparisonParselet.java
com.github.dkharrat.nexusdata.predicate.parser.ConstantParselet.java
com.github.dkharrat.nexusdata.predicate.parser.ExpressionNode.java
com.github.dkharrat.nexusdata.predicate.parser.GroupParselet.java
com.github.dkharrat.nexusdata.predicate.parser.InfixParselet.java
com.github.dkharrat.nexusdata.predicate.parser.LexerGrammar.java
com.github.dkharrat.nexusdata.predicate.parser.Lexer.java
com.github.dkharrat.nexusdata.predicate.parser.LogicalParselet.java
com.github.dkharrat.nexusdata.predicate.parser.NameParselet.java
com.github.dkharrat.nexusdata.predicate.parser.ParseException.java
com.github.dkharrat.nexusdata.predicate.parser.Parser.java
com.github.dkharrat.nexusdata.predicate.parser.PredicateParser.java
com.github.dkharrat.nexusdata.predicate.parser.PrefixParselet.java
com.github.dkharrat.nexusdata.predicate.parser.Token.java
com.github.dkharrat.nexusdata.store.AndroidSqlPersistentStore.java
com.github.dkharrat.nexusdata.store.DatabaseHelper.java
com.github.dkharrat.nexusdata.store.InMemoryPersistentStore.java
com.github.dkharrat.nexusdata.store.PredicateToSQL.java
com.github.dkharrat.nexusdata.utils.DateUtil.java
com.github.dkharrat.nexusdata.utils.ObjectUtil.java
com.github.dkharrat.nexusdata.utils.SqlTableBuilder.java
com.github.dkharrat.nexusdata.utils.StreamUtil.java
com.github.dkharrat.nexusdata.utils.StringUtil.java
com.github.dkharrat.nexusdata.utils.android.CursorUtil.java
com.github.dkharrat.nexusdata.utils.android.SQLiteDatabaseHelper.java
org.example.todo.MainActivity.java
org.example.todo.NewTaskActivity.java
org.example.todo.Task.java
org.example.todo.TodoApp.java
org.example.todo.User.java
org.example.todo._Task.java
org.example.todo._User.java