Skip to content

Instantly share code, notes, and snippets.

@kumarparth380
Created September 30, 2020 01:27
Show Gist options
  • Save kumarparth380/d8088417f0fb813ef6e694c7da90e1ca to your computer and use it in GitHub Desktop.
Save kumarparth380/d8088417f0fb813ef6e694c7da90e1ca to your computer and use it in GitHub Desktop.
Sqlite DB Migration (React-native)
/**
* extend this to make new migrations
*/
import * as Sentry from "@sentry/react-native";
export class RNSqliteMigration {
constructor(db, sql, version) {
this.version = version;
this._db = db;
this._sql = sql;
}
execute(){
function exec(tx, sql) {
tx.executeSql(sql);
}
function migrateV0toV1(tx){
if (Array.isArray(this._sql)) {
this._sql.forEach(s => exec(tx,s));
} else {
exec(tx,this._sql);
}
}
try{
this._db.transaction(txn => {
txn.executeSql("SELECT version FROM schema_migrations LIMIT 1", [], (tx, result) => {
version = (result.rows.raw()).length;
while(version < this.version) {
switch(version){
case 0: migrateV0toV1(tx); break;
/* you can have more migration based on the version */
// case 1: migrateV1toV2(tx); break;
}
version = this.version;
tx.executeSql('INSERT INTO schema_migrations (version) VALUES (:version)', [this.version]);
}
});
}, error => {
Sentry.captureException(error, { logger: 'sqlite.migrations' });
});
}catch(error){
console.log("catch error ",error)
}
}
}
//Usage
/* import the class `RNSqliteMigration` wherever you want to use */
const sql = [
"UPDATE table_name SET lastSync=NULL where 1",
"UPDATE TABLE table_name ADD COLUMN id TEXT",
"CREATE TABLE IF NOT EXISTS table_name(id VARCHAR(255) NOT NULL UNIQUE PRIMARY KEY, code VARCHAR(20))"
];
/* OR */
const sql = "UPDATE table_name SET lastSync=NULL where 1";
try{
const migration = new RNSqliteMigration(this.db, sql, 1);
migration.execute();
}
catch(error){
console.log("Error of migration: ", error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment