sqlite-async
Advanced tools
Comparing version 1.0.4 to 1.0.5
{ | ||
"name": "sqlite-async", | ||
"version": "1.0.4", | ||
"version": "1.0.5", | ||
"description": "ES6 Promise-based interface to the sqlite3 module.", | ||
@@ -5,0 +5,0 @@ "main": "sqlite-async.js", |
@@ -23,2 +23,15 @@ # sqlite-async | ||
## Transactions | ||
The `transaction` method allows a function returning a promise to be wrapped in a transaction. The function is passed the `Database` instance as its parameter. | ||
```javascript | ||
db.transaction(db => { | ||
return Promise.all([ | ||
db.run('INSERT INTO test VALUES (2, "two")'), | ||
db.run('INSERT INTO test VALUES (2, "three")') | ||
]) | ||
}) | ||
``` | ||
## License | ||
@@ -25,0 +38,0 @@ |
@@ -169,2 +169,16 @@ /** | ||
} | ||
transaction(fn) { | ||
return this.exec('BEGIN TRANSACTION').then(_ => { | ||
return fn(this).then(result => { | ||
return this.exec('END TRANSACTION').then(_ => { | ||
return result | ||
}) | ||
}).catch(err => { | ||
return this.exec('ROLLBACK TRANSACTION').then(_ => { | ||
return Promise.reject(err) | ||
}) | ||
}) | ||
}) | ||
} | ||
} | ||
@@ -171,0 +185,0 @@ |
@@ -23,3 +23,3 @@ const Database = require('../sqlite-async') | ||
.then(_ => { | ||
return db.exec('CREATE TABLE test (id INT, name TEXT)') | ||
return db.exec('CREATE TABLE test (id INT, name TEXT NOT NULL)') | ||
}) | ||
@@ -70,2 +70,19 @@ .then(_ => { | ||
.then(_ => { | ||
return db.transaction(db => { | ||
return Promise.all([ | ||
db.run('INSERT INTO test VALUES (2, "two")'), | ||
db.run('INSERT INTO test VALUES (3, NULL)') | ||
]) | ||
}) | ||
}) | ||
.catch(err => { | ||
expect(err.code, '"SQLITE_CONSTRAINT"') | ||
}) | ||
.then(_ => { | ||
return db.all('SELECT * FROM test') | ||
}) | ||
.then(rows => { | ||
expect(rows, '[{"id":1,"name":"test"}]') | ||
}) | ||
.then(_ => { | ||
return db.close() | ||
@@ -72,0 +89,0 @@ }) |
16566
382
59