Created
December 20, 2016 02:06
-
-
Save dantman/59488c2d8bb2b4c59efda99a0040d16c to your computer and use it in GitHub Desktop.
ReactNativeSqliteStorage driver for knex.js
This file contains 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
'use strict'; | |
import Promise from 'bluebird'; | |
import { map, clone } from 'lodash'; | |
import Client_SQLite3 from 'knex/lib/dialects/sqlite3'; | |
export default class Client_ReactNativeSqliteStorage extends Client_SQLite3 { | |
dialect: 'sqlite'; | |
driverName = 'react-native-sqlite-storage'; | |
_driver() { | |
return require('react-native-sqlite-storage'); | |
} | |
acquireRawConnection() { | |
this.driver.enablePromise(true); | |
return Promise.cast(this.driver.openDatabase(Object.assign({}, this.connectionSettings))) | |
} | |
destroyRawConnection(db) { | |
db.close().catch((err) => { | |
this.emit('error', err); | |
}); | |
} | |
_query(connection, obj) { | |
if (!connection) return Promise.reject(new Error('No connection provided.')); | |
return connection.executeSql(obj.sql, obj.bindings) | |
.then(([response]) => { | |
obj.response = response; | |
return obj; | |
}); | |
} | |
_stream(connection, sql, stream) { | |
const client = this; | |
return new Promise(function(resolver, rejecter) { | |
stream.on('error', rejecter) | |
stream.on('end', resolver) | |
return client._query(connection, sql).then(obj => | |
client.processResponse(obj) | |
).map(row => { | |
stream.write(row) | |
}).catch(err => { | |
stream.emit('error', err) | |
}).then(() => { | |
stream.end() | |
}) | |
}) | |
} | |
processResponse(obj, runner) { | |
const resp = obj.response; | |
if (obj.output) return obj.output.call(runner, resp); | |
switch (obj.method) { | |
case 'pluck': | |
case 'first': | |
case 'select': { | |
let results = []; | |
for (let i = 0, l = resp.rows.length; i < l; i++) { | |
results[i] = clone(resp.rows.item(i)); | |
} | |
if (obj.method === 'pluck') results = map(results, obj.pluck); | |
return obj.method === 'first' ? results[0] : results; | |
} | |
case 'insert': | |
return [resp.insertId]; | |
case 'delete': | |
case 'update': | |
case 'counter': | |
return resp.rowsAffected; | |
default: | |
return resp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am trying to use this. But unable to do so what are the steps i need follow to work with knex in react native. Please help me.