think-model-sqlite 1.3.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/socket.js CHANGED
@@ -1,5 +1,5 @@
1
1
  const thinkInstance = require('think-instance');
2
- const sqlite = require('sqlite3');
2
+ const BetterSqlite3 = require('better-sqlite3');
3
3
  const assert = require('assert');
4
4
  const helper = require('think-helper');
5
5
  const path = require('path');
@@ -23,6 +23,8 @@ const TRANSACTION = {
23
23
  end: 2
24
24
  };
25
25
 
26
+ const SELECT_SQL_RE = /^\s*(SELECT|PRAGMA|WITH|EXPLAIN)\b/i;
27
+
26
28
  class SQLiteSocket {
27
29
  constructor(config = {}) {
28
30
  // different socket may connect to different db,so use independent debounce instance
@@ -52,23 +54,24 @@ class SQLiteSocket {
52
54
  [CREATE_POOL]() {
53
55
  const factory = {
54
56
  create: () => {
55
- const deferred = helper.defer();
56
- const db = new sqlite.Database(this.savePath, err => {
57
+ return Promise.resolve().then(() => {
58
+ let timeout = this.config.timeout;
59
+ const options = {};
60
+ if (timeout) {
61
+ timeout = helper.ms(timeout);
62
+ options.timeout = timeout;
63
+ }
64
+ const db = new BetterSqlite3(this.savePath, options);
57
65
  if (this.config.logConnect) {
58
66
  this.config.logger(`sqlite:${this.savePath}`);
59
67
  }
60
- if (err) return deferred.reject(err);
61
- deferred.resolve(db);
68
+ return db;
62
69
  });
63
- let timeout = this.config.timeout;
64
- if (timeout) {
65
- timeout = helper.ms(timeout);
66
- db.configure('busyTimeout', timeout);
67
- }
68
- return deferred.promise;
69
70
  },
70
71
  destroy: (client) => {
71
- client.close();
72
+ try {
73
+ client.close();
74
+ } catch (e) {}
72
75
  return Promise.resolve();
73
76
  }
74
77
  };
@@ -94,6 +97,7 @@ class SQLiteSocket {
94
97
  return this.getConnection(connection).then(connection => {
95
98
  return this.query({
96
99
  sql: 'BEGIN TRANSACTION',
100
+ execute: true,
97
101
  transaction: TRANSACTION.start,
98
102
  debounce: false
99
103
  }, connection).then(() => connection);
@@ -106,6 +110,7 @@ class SQLiteSocket {
106
110
  commit(connection) {
107
111
  return this.query({
108
112
  sql: 'COMMIT',
113
+ execute: true,
109
114
  transaction: TRANSACTION.end,
110
115
  debounce: false
111
116
  }, connection);
@@ -117,6 +122,7 @@ class SQLiteSocket {
117
122
  rollback(connection) {
118
123
  return this.query({
119
124
  sql: 'ROLLBACK',
125
+ execute: true,
120
126
  transaction: TRANSACTION.end,
121
127
  debounce: false
122
128
  }, connection);
@@ -170,17 +176,23 @@ class SQLiteSocket {
170
176
  }
171
177
 
172
178
  let promise = null;
173
- if (sqlOptions.execute) {
174
- promise = new Promise((resolve, reject) => {
175
- connection.run(sqlOptions.sql, function(err) {
176
- if (err) return reject(err);
177
- resolve({insertId: this.lastID, affectedRows: this.changes});
178
- });
179
- });
180
- } else {
181
- const queryFn = helper.promisify(connection.all, connection);
182
- promise = queryFn(sqlOptions.sql);
183
- }
179
+ promise = Promise.resolve().then(() => {
180
+ const stmt = connection.prepare(sqlOptions.sql);
181
+ if (sqlOptions.execute) {
182
+ const ret = stmt.run();
183
+ return {
184
+ insertId: Number(ret.lastInsertRowid) || 0,
185
+ affectedRows: ret.changes || 0
186
+ };
187
+ }
188
+
189
+ if (SELECT_SQL_RE.test(sqlOptions.sql)) {
190
+ return stmt.all();
191
+ }
192
+
193
+ stmt.run();
194
+ return [];
195
+ });
184
196
  return promise.catch(err => {
185
197
  return helper.isError(err) ? err : new Error(err);
186
198
  }).then(data => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "think-model-sqlite",
3
- "version": "1.3.2",
3
+ "version": "2.0.1",
4
4
  "description": "SQLite adapter for ThinkJS 3.x",
5
5
  "scripts": {
6
6
  "test": "npm run eslint && npm run test-cov",
@@ -10,7 +10,8 @@
10
10
  },
11
11
  "repository": {
12
12
  "type": "git",
13
- "url": "git+https://github.com/thinkjs/think-model-sqlite.git"
13
+ "url": "https://github.com/thinkjs/thinkjs",
14
+ "directory": "packages/think-model-sqlite"
14
15
  },
15
16
  "keywords": [
16
17
  "thinkjs",
@@ -26,24 +27,19 @@
26
27
  },
27
28
  "homepage": "https://github.com/thinkjs/think-model-sqlite#readme",
28
29
  "dependencies": {
30
+ "better-sqlite3": "^11.10.0",
29
31
  "generic-pool": "^3.1.7",
30
- "sqlite3": "^5.1.4",
31
32
  "think-debounce": "^1.0.3",
32
33
  "think-helper": "^1.1.3",
33
34
  "think-instance": "^1.0.2",
34
35
  "think-model-abstract": "^1.6.5"
35
36
  },
36
37
  "devDependencies": {
37
- "ava": "^0.19.1",
38
+ "ava": "^8.0.0",
38
39
  "eslint": "^4.2.0",
39
40
  "eslint-config-think": "^1.0.1",
40
41
  "muk": "^0.5.3",
41
- "nyc": "^10.3.0"
42
- },
43
- "ava": {
44
- "require": [
45
- "babel-register"
46
- ],
47
- "babel": "inherit"
42
+ "nyc": "^10.3.0",
43
+ "think-model": "^1.5.4"
48
44
  }
49
45
  }
package/test/index.js CHANGED
@@ -1,2 +1,80 @@
1
- const {test} = require('ava');
2
- test.todo('todo');
1
+ const {default: test} = require('ava');
2
+ const Model = require('think-model/lib/model');
3
+ const SQLite = require('../');
4
+
5
+ const Socket = require('../lib/socket');
6
+
7
+ function createMemorySocket() {
8
+ return new Socket({
9
+ path: ':memory:',
10
+ database: 'test',
11
+ logConnect: false,
12
+ debounce: false
13
+ });
14
+ }
15
+
16
+ test('socket execute & query with better-sqlite3', async t => {
17
+ const socket = createMemorySocket();
18
+
19
+ try {
20
+ await socket.execute('CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
21
+
22
+ const insert1 = await socket.execute("INSERT INTO user(name) VALUES ('alice')");
23
+ const insert2 = await socket.execute("INSERT INTO user(name) VALUES ('bob')");
24
+ const rows = await socket.query('SELECT id, name FROM user ORDER BY id ASC');
25
+
26
+ t.true(insert1.insertId > 0);
27
+ t.is(insert1.affectedRows, 1);
28
+ t.is(insert2.affectedRows, 1);
29
+ t.deepEqual(rows, [
30
+ {id: 1, name: 'alice'},
31
+ {id: 2, name: 'bob'}
32
+ ]);
33
+ } finally {
34
+ await socket.close();
35
+ }
36
+ });
37
+
38
+ test('transaction rollback should keep data unchanged', async t => {
39
+ const socket = createMemorySocket();
40
+
41
+ try {
42
+ await socket.execute('CREATE TABLE item (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
43
+
44
+ const err = await t.throwsAsync(async () => {
45
+ await socket.transaction(async connection => {
46
+ await socket.execute("INSERT INTO item(name) VALUES ('rollback-me')", connection);
47
+ throw new Error('mock failure');
48
+ });
49
+ });
50
+
51
+ const rows = await socket.query('SELECT COUNT(1) AS cnt FROM item');
52
+ t.is(err.message, 'mock failure');
53
+ t.is(rows[0].cnt, 0);
54
+ } finally {
55
+ await socket.close();
56
+ }
57
+ });
58
+
59
+ test('think-model integration', async t => {
60
+ const userModel = new Model('user', {
61
+ handle: SQLite,
62
+ path: '/tmp',
63
+ database: 'test',
64
+ logConnect: false,
65
+ debounce: false
66
+ });
67
+
68
+ await userModel.execute('CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
69
+
70
+ const insert1 = await userModel.add({name: 'alice'});
71
+ const insert2 = await userModel.add({name: 'bob'});
72
+ const rows = await userModel.select();
73
+
74
+ t.is(insert1, 1);
75
+ t.is(insert2, 2);
76
+ t.deepEqual(rows, [
77
+ {id: 1, name: 'alice'},
78
+ {id: 2, name: 'bob'}
79
+ ]);
80
+ });