Last active
November 23, 2016 23:24
-
-
Save DrMabuse23/a082e4446eeb0034fc0657569d9949d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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