Join sql.js to sqlite ionic storage

390 views Asked by At

could anyone help me with this? I have a SQLite pre-populated database .. using SQL.JS However I saw that it is not possible to insert data in it, I have already tried in several ways but without success. So I'm trying to create a database with Cordova Sqlite Storage to be able to enter data. I am getting the data in the application from SQL.JS, and I was able to open the database through storage, however: Accessing the database by device, the database is not the same (although it is sqlite) In case I am having 2 databases many different. Some help? I would like to insert data into a table that I created by SQlite Studio in my SQL.JS database

@Injectable()
export class DatabaseProvider {
database: SQLiteObject;
private databaseReady: BehaviorSubject<boolean>;
dbName: string;

 constructor(public http: Http, private sqlitePorter: SQLitePorter, private storage: Storage, private sqlite: SQLite, private platform: Platform) {

this.databaseReady = new BehaviorSubject(false);
this.platform.ready().then(() => {
  this.sqlite.create({
    name: 'dbvidacarioca.sqlite',
    location: 'default'
  })
  .then((db: SQLiteObject) => {
    this.database = db;
    this.storage.get('database_filled').then(val => {
      if (val) {
        this.databaseReady.next(true);
      } else {
        this.fillDatabase();
      }
    })
  });
});


this.dbName = "dbvidacarioca.sqlite";    /* NOME DO BANCO DE DADOS */


 fillDatabase() {
this.http.get('assets/dummyDump.sql')
.map(res => res.text())
.subscribe(sql => {
  this.sqlitePorter.importSqlToDb(this.database, sql)
  .then(data => {
    this.databaseReady.next(true);
    this.storage.set('database_filled', true);
  })
  .catch(e => console.log(e));
});
}

addDeveloper(email) {
let data = [email];
console.log('insert data: ', data);
return this.database.executeSql("INSERT INTO tb_usuario (email) VALUES (?)", 
data).then(res => {
  return res;
})
.catch(err => {
  console.log('error: ', err);
});
}

  getDatabaseState() {
return this.databaseReady.asObservable();
  }

  getAllDevelopers() {
return this.database.executeSql("SELECT * FROM tb_usuario", []).then(data => 
  {
  let usuarios = [];
  if (data.rows.length > 0) {
    for (var i = 0; i < data.rows.length; i++) {
      usuarios.push({email: data.rows.item(i).email})
    }
  }
  return usuarios;
}, err => {
  console.log('Error: ', err);
  return [];
})
}

executeQuery(sql: string) {
let db: any;
return new Promise<any>((resolve, reject) => {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', this.dbName, true);
  xhr.responseType = 'arraybuffer';

  xhr.onload = (e) => {
    let uInt8Array = new Uint8Array(xhr.response);
    db = new SQL.Database(uInt8Array);
    let contents = db.exec(sql);
    if (contents.length > 0)
      resolve(contents[0].values);
    else resolve()
  };
  xhr.send();

});

}

0

There are 0 answers