android.arch.persistence.db.SupportSQLiteDatabase Java Examples

The following examples show how to use android.arch.persistence.db.SupportSQLiteDatabase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApplicationDatabase.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 6 votes vote down vote up
public static ApplicationDatabase getInstance(final Context context) throws Exception {
    if (sInstance == null) {
        synchronized (ApplicationDatabase.class) {
            if (sInstance == null) {
                SafeHelperFactory factory = new SafeHelperFactory(KeyGenHelper.getSecretKeyAsChar(context));

                sInstance = Room.databaseBuilder(context.getApplicationContext(),ApplicationDatabase.class, DATABASE_NAME)
                        .openHelperFactory(factory)
                        .allowMainThreadQueries()
                        .addCallback(new Callback() {
                            @Override
                            public void onCreate(@NonNull SupportSQLiteDatabase db) {
                                super.onCreate(db);
                                try {
                                    ApplicationDatabase database = ApplicationDatabase.getInstance(context);
                                    // notify that the database was created and it's ready to be used
                                    database.setDatabaseCreated();
                                } catch (Exception e) {
                                    Log.e("ApplicationDatabase", e.getMessage());
                                }
                            }
                        }).build();

            }
        }
    }
    return sInstance;
}
 
Example #2
Source File: BriteDatabase.java    From sqlbrite with Apache License 2.0 6 votes vote down vote up
/**
 * Update rows in the specified {@code table} and notify any subscribed queries. This method
 * will not trigger a notification if no rows were updated.
 *
 * @see SupportSQLiteDatabase#update(String, int, ContentValues, String, Object[])
 */
@WorkerThread
public int update(@NonNull String table, @ConflictAlgorithm int conflictAlgorithm,
    @NonNull ContentValues values, @Nullable String whereClause, @Nullable String... whereArgs) {
  SupportSQLiteDatabase db = getWritableDatabase();

  if (logging) {
    log("UPDATE\n  table: %s\n  values: %s\n  whereClause: %s\n  whereArgs: %s\n  conflictAlgorithm: %s",
        table, values, whereClause, Arrays.toString(whereArgs),
        conflictString(conflictAlgorithm));
  }
  int rows = db.update(table, conflictAlgorithm, values, whereClause, whereArgs);

  if (logging) log("UPDATE affected %s %s", rows, rows != 1 ? "rows" : "row");

  if (rows > 0) {
    // Only send a table trigger if rows were affected.
    sendTableTrigger(Collections.singleton(table));
  }
  return rows;
}
 
Example #3
Source File: BriteDatabase.java    From sqlbrite with Apache License 2.0 6 votes vote down vote up
/**
 * Delete rows from the specified {@code table} and notify any subscribed queries. This method
 * will not trigger a notification if no rows were deleted.
 *
 * @see SupportSQLiteDatabase#delete(String, String, Object[])
 */
@WorkerThread
public int delete(@NonNull String table, @Nullable String whereClause,
    @Nullable String... whereArgs) {
  SupportSQLiteDatabase db = getWritableDatabase();

  if (logging) {
    log("DELETE\n  table: %s\n  whereClause: %s\n  whereArgs: %s", table, whereClause,
        Arrays.toString(whereArgs));
  }
  int rows = db.delete(table, whereClause, whereArgs);

  if (logging) log("DELETE affected %s %s", rows, rows != 1 ? "rows" : "row");

  if (rows > 0) {
    // Only send a table trigger if rows were affected.
    sendTableTrigger(Collections.singleton(table));
  }
  return rows;
}
 
Example #4
Source File: BriteDatabase.java    From sqlbrite with Apache License 2.0 6 votes vote down vote up
/**
 * Insert a row into the specified {@code table} and notify any subscribed queries.
 *
 * @see SupportSQLiteDatabase#insert(String, int, ContentValues)
 */
@WorkerThread
public long insert(@NonNull String table, @ConflictAlgorithm int conflictAlgorithm,
    @NonNull ContentValues values) {
  SupportSQLiteDatabase db = getWritableDatabase();

  if (logging) {
    log("INSERT\n  table: %s\n  values: %s\n  conflictAlgorithm: %s", table, values,
        conflictString(conflictAlgorithm));
  }
  long rowId = db.insert(table, conflictAlgorithm, values);

  if (logging) log("INSERT id: %s", rowId);

  if (rowId != -1) {
    // Only send a table trigger if the insert was successful.
    sendTableTrigger(Collections.singleton(table));
  }
  return rowId;
}
 
Example #5
Source File: InfoDB.java    From Tok-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
    database.execSQL(
        "CREATE TABLE IF NOT EXISTS `friend_conversation` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `tox_key` TEXT, `last_msg_db_id` INTEGER NOT NULL, `update_time` INTEGER NOT NULL, `unread_count` INTEGER NOT NULL)");

    //db table update friend_requests
    database.execSQL("ALTER TABLE `friend_requests` RENAME TO `friend_requests_old`");
    database.execSQL(
        "CREATE TABLE IF NOT EXISTS `friend_requests` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `tox_key` TEXT, `message` TEXT, `has_read` INTEGER NOT NULL default 0)");
    database.execSQL(
        "INSERT INTO `friend_requests` (`tox_key`, `message`) SELECT `tox_key`, `message` FROM friend_requests_old");
    database.execSQL("DROP TABLE IF EXISTS `friend_requests_old`");

    //db table update friend_contacts
    database.execSQL("ALTER TABLE `friend_contacts` RENAME TO `friend_contacts_old`");
    database.execSQL(
        "CREATE TABLE IF NOT EXISTS `friend_contacts` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `tox_key` TEXT, `name` TEXT, `avatar` TEXT, `isonline` INTEGER NOT NULL, `status` TEXT, `note` TEXT, `received_avatar` INTEGER NOT NULL, `isblocked` INTEGER NOT NULL, `mute` INTEGER NOT NULL, `alias` TEXT, `contact_type` INTEGER NOT NULL, `is_bot` INTEGER NOT NULL default 0, `bot_type` INTEGER NOT NULL default 0)");
    database.execSQL(
        "INSERT INTO `friend_contacts` (`tox_key`, `name`,`avatar`,`isonline`, `status`, `note`, `received_avatar`, `isblocked`,`mute`,`alias`, `contact_type`) SELECT `tox_key`, `name`,`avatar`,`isonline`, `status`, `note`, `received_avatar`, `isblocked`,`mute`,`alias`, `contact_type` FROM friend_contacts_old");
    database.execSQL("DROP TABLE IF EXISTS `friend_contacts_old`");

    //db table update friend_messages
    database.execSQL("ALTER TABLE `friend_messages` RENAME TO `friend_messages_old`");
    database.execSQL(
        "CREATE TABLE IF NOT EXISTS `friend_messages` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `message_id` INTEGER NOT NULL, `tox_key` TEXT, `sender_key` TEXT, `sender_name` TEXT, `message` TEXT, `sent_status` INTEGER NOT NULL, `receive_status` INTEGER NOT NULL, `has_been_read` INTEGER NOT NULL, `has_played` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `size` INTEGER NOT NULL, `type` INTEGER, `file_kind` INTEGER)");
    database.execSQL(
        "INSERT INTO `friend_messages` (`message_id`, `tox_key`,`sender_key`,`sender_name`, `message`, `sent_status`, `receive_status`, `has_been_read`,`has_played`,`timestamp`, `size`, `type`, `file_kind`) SELECT `message_id`, `tox_key`,`sender_key`,`sender_name`, `message`, `sent_status`, `receive_status`, `has_been_read`,`has_played`,`timestamp`, `size`, `type`, `file_kind` FROM friend_messages_old");
    database.execSQL("DROP TABLE IF EXISTS `friend_messages_old`");

    //db table update group_peers
    database.execSQL("ALTER TABLE `group_peers` RENAME TO `group_peers_old`");
    database.execSQL(
        "CREATE TABLE IF NOT EXISTS `group_peers` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `group_number` INTEGER NOT NULL, `peer_pk` TEXT, `peer_name` TEXT, `peer_signature` TEXT)");
    database.execSQL(
        "INSERT INTO `group_peers` (`group_number`, `peer_pk`,`peer_name`,`peer_signature`) SELECT `group_number`, `peer_pk`,`peer_name`,`peer_signature` FROM group_peers_old");
    database.execSQL("DROP TABLE IF EXISTS `group_peers_old`");
}
 
Example #6
Source File: Utils.java    From Android-Debug-Database with Apache License 2.0 5 votes vote down vote up
public static void setInMemoryRoomDatabases(SupportSQLiteDatabase... database) {
    if (BuildConfig.DEBUG) {
        try {
            Class<?> debugDB = Class.forName("com.amitshekhar.DebugDB");
            Class[] argTypes = new Class[]{HashMap.class};
            HashMap<String, SupportSQLiteDatabase> inMemoryDatabases = new HashMap<>();
            // set your inMemory databases
            inMemoryDatabases.put("InMemoryOne.db", database[0]);
            Method setRoomInMemoryDatabase = debugDB.getMethod("setInMemoryRoomDatabases", argTypes);
            setRoomInMemoryDatabase.invoke(null, inMemoryDatabases);
        } catch (Exception ignore) {

        }
    }
}
 
Example #7
Source File: Utils.java    From Android-Debug-Database with Apache License 2.0 5 votes vote down vote up
public static void setInMemoryRoomDatabases(SupportSQLiteDatabase... database) {
    if (BuildConfig.DEBUG) {
        try {
            Class<?> debugDB = Class.forName("com.amitshekhar.DebugDB");
            Class[] argTypes = new Class[]{HashMap.class};
            HashMap<String, SupportSQLiteDatabase> inMemoryDatabases = new HashMap<>();
            // set your inMemory databases
            inMemoryDatabases.put("InMemoryOne.db", database[0]);
            Method setRoomInMemoryDatabase = debugDB.getMethod("setInMemoryRoomDatabases", argTypes);
            setRoomInMemoryDatabase.invoke(null, inMemoryDatabases);
        } catch (Exception ignore) {

        }
    }
}
 
Example #8
Source File: AppModule.java    From AndroidNewArchitectureExample with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.beginTransaction();
    try {
        database.execSQL("INSERT INTO 'Weather' (CityName, Temperature, Description) VALUES ('Moscow', NULL, NULL)");
        database.execSQL("INSERT INTO 'Weather' (CityName, Temperature, Description) VALUES ('London', NULL, NULL)");
        database.execSQL("INSERT INTO 'Weather' (CityName, Temperature, Description) VALUES (git 'Berlin', NULL, NULL)");
        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}
 
Example #9
Source File: MyDatabase.java    From RoomDemo with Apache License 2.0 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.execSQL("ALTER TABLE product "
            + " ADD COLUMN price INTEGER");

    // enable flag to force update products
    App.get().setForceUpdate(true);
}
 
Example #10
Source File: Migration_19_20.java    From SABS with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE FirewallWhitelistedPackage " +
            "(id INTEGER PRIMARY KEY, " +
            "packageName TEXT NOT NULL, " +
            "policyPackageId TEXT DEFAULT 'default-policy', " +
            "FOREIGN KEY (policyPackageId) REFERENCES PolicyPackage(id))");
    database.execSQL("CREATE UNIQUE INDEX firewall_whitelisted_package_policy_package_idx " +
            "ON FirewallWhitelistedPackage (packageName, policyPackageId)");
}
 
Example #11
Source File: Migration_16_17.java    From SABS with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {

    database.execSQL("CREATE TABLE PolicyPackage " +
            "(id TEXT PRIMARY KEY, " +
            "name TEXT NOT NULL, " +
            "createdAt INTEGER, " +
            "updatedAt INTEGER) ");

    Date currentDate = new Date();
    ContentValues contentValues = new ContentValues();
    contentValues.put("id", "default-policy");
    contentValues.put("name", "Default Policy");
    contentValues.put("createdAt", currentDate.getTime());
    contentValues.put("updatedAt", currentDate.getTime());
    database.insert("PolicyPackage", SQLiteDatabase.CONFLICT_REPLACE, contentValues);

    database.execSQL("CREATE TABLE AppPermission " +
            "(id INTEGER PRIMARY KEY, " +
            "packageName TEXT NOT NULL, " +
            "permissionName TEXT NOT NULL, " +
            "permissionStatus INTEGER DEFAULT 0, " +
            "policyPackageId TEXT DEFAULT 'default-policy', " +
            "FOREIGN KEY (policyPackageId) REFERENCES PolicyPackage(id))");
    database.execSQL("CREATE UNIQUE INDEX app_permission_policy_package_idx " +
            "ON AppPermission (packageName, permissionName, policyPackageId)");

    database.execSQL("CREATE TABLE DisabledPackage " +
            "(id INTEGER PRIMARY KEY, " +
            "packageName TEXT NOT NULL, " +
            "policyPackageId TEXT DEFAULT 'default-policy', " +
            "FOREIGN KEY (policyPackageId) REFERENCES PolicyPackage(id))");
    database.execSQL("CREATE UNIQUE INDEX disabled_package_policy_package_idx " +
            "ON DisabledPackage (packageName, policyPackageId)");
}
 
Example #12
Source File: AppDataBase.java    From Travel-Mate with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    // Create the new table to be used
    database.execSQL(
            "CREATE TABLE checklist_items (id INTEGER PRIMARY KEY NOT NULL, name TEXT," +
                    " isDone TEXT NOT NULL, position INTEGER DEFAULT 0 NOT NULL)");

    // Create a temp table to generate positions
    database.execSQL("CREATE TABLE seq_generator(pos INTEGER PRIMARY KEY AUTOINCREMENT," +
            "id INTEGER)");

    // Copy each of the existing id(s) into this; `pos` generated with 1-indexing
    database.execSQL("INSERT INTO seq_generator (id)" +
            "SELECT id from events_new");

    // Get old data, JOIN the position column, and insert into new table
    // `pos`-1 is done to achieve 0-indexing
    database.execSQL(
            "INSERT INTO checklist_items " +
                    "SELECT old.id, old.name, old.isDone, t.pos-1 " +
                    "FROM events_new old JOIN seq_generator t ON old.id = t.id");

    // Remove the temp table
    database.execSQL("DROP TABLE seq_generator");

    // Remove the old table
    database.execSQL("DROP TABLE events_new");

    // Change the table name to the correct one
    database.execSQL("ALTER TABLE checklist_items RENAME TO events_new");
}
 
Example #13
Source File: DbChecklist.java    From Travel-Mate with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    // Create the new table
    database.execSQL(
            "CREATE TABLE checklist_items (id INTEGER PRIMARY KEY NOT NULL, name TEXT," +
                    " isDone TEXT)");
    // Copy the data
    database.execSQL(
            "INSERT INTO checklist_items (id, name, isDone) " +
                    "SELECT id, name, isDone FROM events_new");
    // Remove the old table
    database.execSQL("DROP TABLE events_new");
    // Change the table name to the correct one
    database.execSQL("ALTER TABLE checklist_items RENAME TO events_new");
}
 
Example #14
Source File: Migration_21_22.java    From SABS with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfDisabledPackages INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfHosts INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfUserBlockedDomains INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfUserWhitelistedDomains INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfChangedPermissions INTEGER DEFAULT 0");
}
 
Example #15
Source File: DbChecklist.java    From Travel-Mate with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    // Create the new table to be used
    database.execSQL(
            "CREATE TABLE checklist_items (id INTEGER PRIMARY KEY NOT NULL, name TEXT," +
                    " isDone TEXT NOT NULL, position INTEGER DEFAULT 0 NOT NULL)");

    // Create a temp table to generate positions
    database.execSQL("CREATE TABLE seq_generator(pos INTEGER PRIMARY KEY AUTOINCREMENT," +
            "id INTEGER)");

    // Copy each of the existing id(s) into this; `pos` generated with 1-indexing
    database.execSQL("INSERT INTO seq_generator (id)" +
            "SELECT id from events_new");

    // Get old data, JOIN the position column, and insert into new table
    // `pos`-1 is done to achieve 0-indexing
    database.execSQL(
            "INSERT INTO checklist_items " +
                    "SELECT old.id, old.name, old.isDone, t.pos-1 " +
                    "FROM events_new old JOIN seq_generator t ON old.id = t.id");

    // Remove the temp table
    database.execSQL("DROP TABLE seq_generator");

    // Remove the old table
    database.execSQL("DROP TABLE events_new");

    // Change the table name to the correct one
    database.execSQL("ALTER TABLE checklist_items RENAME TO events_new");
}
 
Example #16
Source File: LocationDatabase.java    From background_location_updates with Apache License 2.0 5 votes vote down vote up
public static LocationDatabase getLocationDatabase(Context context) {
    if (INSTANCE == null) {
        INSTANCE =
                Room.databaseBuilder(context.getApplicationContext(), LocationDatabase.class, "locations")
                        .addMigrations(new Migration(1, 2) {
                            @Override
                            public void migrate(@NonNull SupportSQLiteDatabase database) {
                                final String TABLE_TEMP = "_location_migration_1_2_temp";
                                final String TABLE_ORIG = "location";

                                final String CREATE_STMT_2 = "CREATE TABLE IF NOT EXISTS " +
                                        "`"+ TABLE_TEMP +"` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, " +
                                        "`accuracy` REAL, " +
                                        "`longitude` REAL, " +
                                        "`latitude` REAL, " +
                                        "`altitude` REAL," +
                                        " `speed` REAL, " +
                                        "`time` INTEGER, " +
                                        "`vertical_accuracy` REAL, " +
                                        "`course` REAL, " +
                                        "`course_accuracy` REAL, " +
                                        "`speed_accuracy` REAL, `provider` TEXT, `read_count` INTEGER)";

                                database.execSQL(CREATE_STMT_2);

                                database.execSQL("INSERT INTO `" + TABLE_TEMP + "` (" +
                                            "id, accuracy, longitude, latitude, altitude, time" +
                                        ") SELECT id, accuracy, longitude, latitude, altitude, time FROM " + TABLE_ORIG);

                                database.execSQL("DROP TABLE " + TABLE_ORIG);
                                database.execSQL("ALTER TABLE " + TABLE_TEMP + " RENAME TO " + TABLE_ORIG);
                            }
                        })
                        .build();
    }
    return INSTANCE;
}
 
Example #17
Source File: Migration_19_20.java    From notSABS with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE FirewallWhitelistedPackage " +
            "(id INTEGER PRIMARY KEY, " +
            "packageName TEXT NOT NULL, " +
            "policyPackageId TEXT DEFAULT 'default-policy', " +
            "FOREIGN KEY (policyPackageId) REFERENCES PolicyPackage(id))");
    database.execSQL("CREATE UNIQUE INDEX firewall_whitelisted_package_policy_package_idx " +
            "ON FirewallWhitelistedPackage (packageName, policyPackageId)");
}
 
Example #18
Source File: Migration_16_17.java    From notSABS with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {

    database.execSQL("CREATE TABLE PolicyPackage " +
            "(id TEXT PRIMARY KEY, " +
            "name TEXT NOT NULL, " +
            "createdAt INTEGER, " +
            "updatedAt INTEGER) ");

    Date currentDate = new Date();
    ContentValues contentValues = new ContentValues();
    contentValues.put("id", "default-policy");
    contentValues.put("name", "Default Policy");
    contentValues.put("createdAt", currentDate.getTime());
    contentValues.put("updatedAt", currentDate.getTime());
    database.insert("PolicyPackage", SQLiteDatabase.CONFLICT_REPLACE, contentValues);

    database.execSQL("CREATE TABLE AppPermission " +
            "(id INTEGER PRIMARY KEY, " +
            "packageName TEXT NOT NULL, " +
            "permissionName TEXT NOT NULL, " +
            "permissionStatus INTEGER DEFAULT 0, " +
            "policyPackageId TEXT DEFAULT 'default-policy', " +
            "FOREIGN KEY (policyPackageId) REFERENCES PolicyPackage(id))");
    database.execSQL("CREATE UNIQUE INDEX app_permission_policy_package_idx " +
            "ON AppPermission (packageName, permissionName, policyPackageId)");

    database.execSQL("CREATE TABLE DisabledPackage " +
            "(id INTEGER PRIMARY KEY, " +
            "packageName TEXT NOT NULL, " +
            "policyPackageId TEXT DEFAULT 'default-policy', " +
            "FOREIGN KEY (policyPackageId) REFERENCES PolicyPackage(id))");
    database.execSQL("CREATE UNIQUE INDEX disabled_package_policy_package_idx " +
            "ON DisabledPackage (packageName, policyPackageId)");
}
 
Example #19
Source File: Migration_21_22.java    From notSABS with MIT License 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfDisabledPackages INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfHosts INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfUserBlockedDomains INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfUserWhitelistedDomains INTEGER DEFAULT 0");
    database.execSQL("ALTER TABLE PolicyPackage ADD COLUMN numberOfChangedPermissions INTEGER DEFAULT 0");
}
 
Example #20
Source File: TestDb.java    From sqlbrite with Apache License 2.0 5 votes vote down vote up
@Override public void onCreate(@NonNull SupportSQLiteDatabase db) {
  db.execSQL("PRAGMA foreign_keys=ON");

  db.execSQL(CREATE_EMPLOYEE);
  aliceId = db.insert(TABLE_EMPLOYEE, CONFLICT_FAIL, employee("alice", "Alice Allison"));
  bobId = db.insert(TABLE_EMPLOYEE, CONFLICT_FAIL, employee("bob", "Bob Bobberson"));
  eveId = db.insert(TABLE_EMPLOYEE, CONFLICT_FAIL, employee("eve", "Eve Evenson"));

  db.execSQL(CREATE_MANAGER);
  db.insert(TABLE_MANAGER, CONFLICT_FAIL, manager(eveId, aliceId));
}
 
Example #21
Source File: UserDB.java    From Tok-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
    //scheme change
    database.execSQL("ALTER TABLE `users` RENAME TO `users_old`");
    database.execSQL(
        "CREATE TABLE IF NOT EXISTS `users` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `username` TEXT, `password` TEXT, `nickname` TEXT, `status` TEXT, `status_message` TEXT, `avatar` TEXT)");
    database.execSQL(
        "INSERT INTO `users` (`username`, `password`, `nickname`,`status`,`status_message`,`avatar`) SELECT `username`, `password`, `nickname`,`status`,`status_message`,`avatar` FROM users_old");

    database.execSQL("DROP TABLE IF EXISTS `users_old`");
}
 
Example #22
Source File: AppDatabase.java    From privacy-friendly-qr-scanner with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE `Histories` (" +
            "`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
            "`text` TEXT NOT NULL," +
            "`image` TEXT," +
            "`rawBytes` BLOB," +
            "`numBits` INTEGER NOT NULL DEFAULT 0," +
            "`timestamp` INTEGER NOT NULL DEFAULT 0," +
            "`format` TEXT," +
            "`resultPoints` TEXT)");
    database.execSQL("INSERT INTO Histories(text) SELECT content FROM contents");
    database.execSQL("DROP TABLE contents;");

    HistoryItem[] items = null;
    Cursor c = database.query("SELECT * FROM Histories");
    if(c != null) {
        if(c.moveToFirst()) {
            items = new HistoryItem[c.getCount()];
            int i = 0;

            while (!c.isAfterLast()) {
                items[i] = new HistoryItem();
                items[i].set_id(c.getInt(c.getColumnIndex("_id")));
                items[i].setText(c.getString(c.getColumnIndex("text")));
                items[i].setImage(Utils.generateCode(items[i].getText(), BarcodeFormat.QR_CODE, null));

                i++;
                c.moveToNext();
            }
        }
        c.close();
    }

    if(items != null) {
        for(HistoryItem item : items) {
            ContentValues cv = new ContentValues();
            cv.put("_id", item.get_id());
            cv.put("text", item.getText());
            cv.put("image", Converters.encodeImage(item.getImage()));
            cv.put("timestamp", GregorianCalendar.getInstance().getTimeInMillis());
            cv.put("format", BarcodeFormat.QR_CODE.name());
            database.update("Histories", 0, cv, "_id = ?", new String[]{Integer.toString(item.get_id())});
        }
    }
}
 
Example #23
Source File: AppDatabase.java    From privacy-friendly-qr-scanner with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE contents (_id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);");
    database.execSQL("INSERT INTO contents (content) SELECT text FROM Histories");
    database.execSQL("DROP TABLE Histories;");
}
 
Example #24
Source File: DatabaseMigrationInstrumentedTest.java    From privacy-friendly-qr-scanner with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testMigrationToRoomDatabase_1_2() throws Exception {

    // Create the old database with version 1
    DBHandler dbHandler = new DBHandler(InstrumentationRegistry.getTargetContext(), TEST_DB_NAME);

    dbHandler.addContent(data1);
    dbHandler.addContent(data2);
    dbHandler.addContent(data3);
    dbHandler.addContent(data4);

    dbHandler.close();

    //SupportSQLiteDatabase db = testHelper.createDatabase(TEST_DB_NAME, 1);
    SupportSQLiteDatabase db = testHelper.runMigrationsAndValidate(TEST_DB_NAME, 2, true, AppDatabase.MIGRATION_1_2);

    AppDatabase appDatabase = getMigratedRoomDatabase();

    List<HistoryItem> data = appDatabase.historyDao().getAll();

    // Assert that data was copied
    assertNotNull(data);
    assertEquals(4, data.size());
    assertEquals(data1.get_name(), data.get(3).getText());
    assertEquals(data2.get_name(), data.get(2).getText());
    assertEquals(data3.get_name(), data.get(1).getText());
    assertEquals(data4.get_name(), data.get(0).getText());

    // Assert that image was added
    assertNotNull(data.get(0).getFormat());
    assertNotNull(data.get(0).getImage());

    assertNotNull(data.get(1).getFormat());
    assertNotNull(data.get(1).getImage());

    assertNotNull(data.get(2).getFormat());
    assertNotNull(data.get(2).getImage());

    assertNotNull(data.get(3).getFormat());
    assertNotNull(data.get(3).getImage());
}
 
Example #25
Source File: AppDataBase.java    From Travel-Mate with MIT License 4 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    // Add column to the table
    database.execSQL("ALTER TABLE city ADD city_favourite INTEGER DEFAULT 0 NOT NULL");
}
 
Example #26
Source File: InMemoryDebugSQLiteDB.java    From Android-Debug-Database with Apache License 2.0 4 votes vote down vote up
public InMemoryDebugSQLiteDB(SupportSQLiteDatabase database) {
    this.database = database;
}
 
Example #27
Source File: ClientServer.java    From Android-Debug-Database with Apache License 2.0 4 votes vote down vote up
public void setInMemoryRoomDatabases(HashMap<String, SupportSQLiteDatabase> databases) {
    mRequestHandler.setInMemoryRoomDatabases(databases);
}
 
Example #28
Source File: TestDb.java    From sqlbrite with Apache License 2.0 4 votes vote down vote up
@Override
public void onUpgrade(@NonNull SupportSQLiteDatabase db, int oldVersion, int newVersion) {
  throw new AssertionError();
}
 
Example #29
Source File: DbCallback.java    From sqlbrite with Apache License 2.0 4 votes vote down vote up
@Override public void onCreate(SupportSQLiteDatabase db) {
  db.execSQL(CREATE_LIST);
  db.execSQL(CREATE_ITEM);
  db.execSQL(CREATE_ITEM_LIST_ID_INDEX);

  long groceryListId = db.insert(TodoList.TABLE, CONFLICT_FAIL, new TodoList.Builder()
      .name("Grocery List")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(groceryListId)
      .description("Beer")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(groceryListId)
      .description("Point Break on DVD")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(groceryListId)
      .description("Bad Boys 2 on DVD")
      .build());

  long holidayPresentsListId = db.insert(TodoList.TABLE, CONFLICT_FAIL, new TodoList.Builder()
      .name("Holiday Presents")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(holidayPresentsListId)
      .description("Pogo Stick for Jake W.")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(holidayPresentsListId)
      .description("Jack-in-the-box for Alec S.")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(holidayPresentsListId)
      .description("Pogs for Matt P.")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(holidayPresentsListId)
      .description("Cola for Jesse W.")
      .build());

  long workListId = db.insert(TodoList.TABLE, CONFLICT_FAIL, new TodoList.Builder()
      .name("Work Items")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(workListId)
      .description("Finish SqlBrite library")
      .complete(true)
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(workListId)
      .description("Finish SqlBrite sample app")
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder()
      .listId(workListId)
      .description("Publish SqlBrite to GitHub")
      .build());

  long birthdayPresentsListId = db.insert(TodoList.TABLE, CONFLICT_FAIL, new TodoList.Builder()
      .name("Birthday Presents")
      .archived(true)
      .build());
  db.insert(TodoItem.TABLE, CONFLICT_FAIL, new TodoItem.Builder().listId(birthdayPresentsListId)
      .description("New car")
      .complete(true)
      .build());
}
 
Example #30
Source File: RequestHandler.java    From Android-Debug-Database with Apache License 2.0 4 votes vote down vote up
public void setInMemoryRoomDatabases(HashMap<String, SupportSQLiteDatabase> databases) {
    mRoomInMemoryDatabases = databases;
}