Skip to content

Instantly share code, notes, and snippets.

@DrMabuse23
Last active November 23, 2016 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrMabuse23/a082e4446eeb0034fc0657569d9949d8 to your computer and use it in GitHub Desktop.
Save DrMabuse23/a082e4446eeb0034fc0657569d9949d8 to your computer and use it in GitHub Desktop.
batchInserts(table : string, fields : Array < string >, rows : Array < any >, chunkSize = 200) {
if (!table || !table.length) {
return Observable.throw(`table on batchinsert is required`);
}
if (!rows || !rows.length) {
return Observable.throw(`rows can not be empty on batchinsert`);
}
let inserted = 0;
return Observable
.from(rows)
.bufferCount(chunkSize)
.flatMap((items) : any => {
return Observable.create((ob : Observer < any >) => {
this
.db
.transaction((tr) => {
inserted = inserted + items.length;
console.log(`Start Insert ${items.length} from ${rows.length} into ${table}`);
Observable
.from(items)
.map((row) => {
const query = this
.sql
.insertOrReplace(table, fields, row);
// console.info(query);
if (!query) {
ob.error([row, query]);
}
tr.executeSql(query, [], (transaction, result) => {
// console.log(`Insert ${inserted} from ${rows.length} into ${table} done!`);
}, (transaction, error) => {
console.error(`batchinsert failed on ${query}`, error, row);
ob.error(error);
return true;
});
})
.subscribe({
next: (items : any) => {
ob.next(items);
},
complete: () => {
console.log(`Insert ${inserted} / ${rows.length} into ${table} done!`);
ob.complete()
}
});
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment