@sqlitecloud/drivers 1.0.406 → 1.0.422

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/README.md CHANGED
@@ -54,7 +54,7 @@ let database = new Database('sqlitecloud://user:password@xxx.sqlite.cloud:8860/c
54
54
 
55
55
  let name = 'Breaking The Rules'
56
56
 
57
- let results = await database.sql`SELECT * FROM tracks WHERE name = ${name}`
57
+ let results = await database.sql('SELECT * FROM tracks WHERE name = ?', name)
58
58
  // => returns [{ AlbumId: 1, Name: 'Breaking The Rules', Composer: 'Angus Young... }]
59
59
  ```
60
60
 
@@ -82,7 +82,7 @@ await pubSub.listen(PUBSUB_ENTITY_TYPE.TABLE, 'albums', (error, results, data) =
82
82
  }
83
83
  })
84
84
 
85
- await database.sql`INSERT INTO albums (Title, ArtistId) values ('Brand new song', 1)`
85
+ await database.sql("INSERT INTO albums (Title, ArtistId) values ('Brand new song', 1)")
86
86
 
87
87
  // Stop listening changes on the table
88
88
  await pubSub.unlisten(PUBSUB_ENTITY_TYPE.TABLE, 'albums')
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * connection-tls.ts - connection via tls socket and sqlitecloud protocol
3
3
  */
4
- import { type SQLiteCloudConfig, type ErrorCallback, type ResultsCallback, SQLiteCloudCommand } from './types';
5
4
  import { SQLiteCloudConnection } from './connection';
5
+ import { type ErrorCallback, type ResultsCallback, SQLiteCloudCommand, type SQLiteCloudConfig } from './types';
6
6
  /**
7
7
  * Implementation of SQLiteCloudConnection that connects to the database using specific tls APIs
8
8
  * that connect to native sockets or tls sockets and communicates via raw, binary protocol.
@@ -37,10 +37,10 @@ var __importStar = (this && this.__importStar) || (function () {
37
37
  })();
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.SQLiteCloudTlsConnection = void 0;
40
- const types_1 = require("./types");
41
40
  const connection_1 = require("./connection");
42
- const utilities_1 = require("./utilities");
43
41
  const protocol_1 = require("./protocol");
42
+ const types_1 = require("./types");
43
+ const utilities_1 = require("./utilities");
44
44
  // explicitly importing buffer library to allow cross-platform support by replacing it
45
45
  const buffer_1 = require("buffer");
46
46
  const tls = __importStar(require("tls"));
@@ -101,6 +101,10 @@ class SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {
101
101
  callback === null || callback === void 0 ? void 0 : callback.call(this, error);
102
102
  });
103
103
  });
104
+ this.socket.setKeepAlive(true);
105
+ // disable Nagle algorithm because we want our writes to be sent ASAP
106
+ // https://brooker.co.za/blog/2024/05/09/nagle.html
107
+ this.socket.setNoDelay(true);
104
108
  this.socket.on('data', data => {
105
109
  this.processCommandsData(data);
106
110
  });
@@ -117,6 +121,10 @@ class SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {
117
121
  this.close();
118
122
  this.processCommandsFinish(new types_1.SQLiteCloudError('Connection closed', { errorCode: 'ERR_CONNECTION_CLOSED' }));
119
123
  });
124
+ this.socket.on('timeout', () => {
125
+ this.close();
126
+ this.processCommandsFinish(new types_1.SQLiteCloudError('Connection ened due to timeout', { errorCode: 'ERR_CONNECTION_TIMEOUT' }));
127
+ });
120
128
  return this;
121
129
  }
122
130
  /** Will send a command immediately (no queueing), return the rowset/result or throw an error */
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * transport-ws.ts - handles low level communication with sqlitecloud server via socket.io websocket
3
3
  */
4
- import { SQLiteCloudConfig, ErrorCallback, ResultsCallback, SQLiteCloudCommand } from './types';
5
4
  import { SQLiteCloudConnection } from './connection';
5
+ import { ErrorCallback, ResultsCallback, SQLiteCloudCommand, SQLiteCloudConfig } from './types';
6
6
  /**
7
7
  * Implementation of TransportConnection that connects to the database indirectly
8
8
  * via SQLite Cloud Gateway, a socket.io based deamon that responds to sql query
@@ -4,10 +4,10 @@
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.SQLiteCloudWebsocketConnection = void 0;
7
- const types_1 = require("./types");
8
- const rowset_1 = require("./rowset");
9
- const connection_1 = require("./connection");
10
7
  const socket_io_client_1 = require("socket.io-client");
8
+ const connection_1 = require("./connection");
9
+ const rowset_1 = require("./rowset");
10
+ const types_1 = require("./types");
11
11
  /**
12
12
  * Implementation of TransportConnection that connects to the database indirectly
13
13
  * via SQLite Cloud Gateway, a socket.io based deamon that responds to sql query
@@ -17,7 +17,8 @@ const socket_io_client_1 = require("socket.io-client");
17
17
  class SQLiteCloudWebsocketConnection extends connection_1.SQLiteCloudConnection {
18
18
  /** True if connection is open */
19
19
  get connected() {
20
- return !!this.socket;
20
+ var _a;
21
+ return !!(this.socket && ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected));
21
22
  }
22
23
  /* Opens a connection with the server and sends the initialization commands. Will throw in case of errors. */
23
24
  connectTransport(config, callback) {
@@ -30,8 +31,18 @@ class SQLiteCloudWebsocketConnection extends connection_1.SQLiteCloudConnection
30
31
  const connectionstring = this.config.connectionstring;
31
32
  const gatewayUrl = ((_a = this.config) === null || _a === void 0 ? void 0 : _a.gatewayurl) || `${this.config.host === 'localhost' ? 'ws' : 'wss'}://${this.config.host}:4000`;
32
33
  this.socket = (0, socket_io_client_1.io)(gatewayUrl, { auth: { token: connectionstring } });
34
+ this.socket.on('connect', () => {
35
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null);
36
+ });
37
+ this.socket.on('disconnect', (reason) => {
38
+ this.close();
39
+ callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Disconnected', { errorCode: 'ERR_CONNECTION_ENDED', cause: reason }));
40
+ });
41
+ this.socket.on('error', (error) => {
42
+ this.close();
43
+ callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection error', { errorCode: 'ERR_CONNECTION_ERROR', cause: error }));
44
+ });
33
45
  }
34
- callback === null || callback === void 0 ? void 0 : callback.call(this, null);
35
46
  }
36
47
  catch (error) {
37
48
  callback === null || callback === void 0 ? void 0 : callback.call(this, error);
@@ -71,14 +82,14 @@ class SQLiteCloudWebsocketConnection extends connection_1.SQLiteCloudConnection
71
82
  }
72
83
  /** Disconnect socket.io from server */
73
84
  close() {
74
- var _a;
85
+ var _a, _b;
75
86
  console.assert(this.socket !== null, 'SQLiteCloudWebsocketConnection.close - connection already closed');
76
87
  if (this.socket) {
77
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
88
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.removeAllListeners();
89
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.close();
78
90
  this.socket = undefined;
79
91
  }
80
92
  this.operations.clear();
81
- this.socket = undefined;
82
93
  return this;
83
94
  }
84
95
  }
@@ -1,8 +1,7 @@
1
- import { SQLiteCloudConfig, RowCountCallback, SQLiteCloudCommand } from './types';
2
- import { ErrorCallback, ResultsCallback, RowCallback, RowsCallback } from './types';
3
1
  import EventEmitter from 'eventemitter3';
4
2
  import { PubSub } from './pubsub';
5
3
  import { Statement } from './statement';
4
+ import { ErrorCallback as ConnectionCallback, ResultsCallback, RowCallback, RowCountCallback, RowsCallback, SQLiteCloudCommand, SQLiteCloudConfig } from './types';
6
5
  /**
7
6
  * Creating a Database object automatically opens a connection to the SQLite database.
8
7
  * When the connection is established the Database object emits an open event and calls
@@ -11,14 +10,17 @@ import { Statement } from './statement';
11
10
  */
12
11
  export declare class Database extends EventEmitter {
13
12
  /** Create and initialize a database from a full configuration object, or connection string */
14
- constructor(config: SQLiteCloudConfig | string, callback?: ErrorCallback);
15
- constructor(config: SQLiteCloudConfig | string, mode?: number, callback?: ErrorCallback);
13
+ constructor(config: SQLiteCloudConfig | string, callback?: ConnectionCallback);
14
+ constructor(config: SQLiteCloudConfig | string, mode?: number, callback?: ConnectionCallback);
16
15
  /** Configuration used to open database connections */
17
16
  private config;
18
- /** Database connections */
19
- private connections;
17
+ /** Database connection */
18
+ private connection;
19
+ /** Used to syncronize opening of connection and commands */
20
+ private operations;
20
21
  /** Returns first available connection from connection pool */
21
- private getConnection;
22
+ private createConnection;
23
+ private enqueueCommand;
22
24
  /** Handles an error by closing the connection, calling the callback and/or emitting an error event */
23
25
  private handleError;
24
26
  /**
@@ -115,7 +117,7 @@ export declare class Database extends EventEmitter {
115
117
  * object. When no callback is provided and an error occurs, an error event
116
118
  * will be emitted on the database object.
117
119
  */
118
- exec(sql: string, callback?: ErrorCallback): this;
120
+ exec(sql: string, callback?: ConnectionCallback): this;
119
121
  /**
120
122
  * If the optional callback is provided, this function will be called when the
121
123
  * database was closed successfully or when an error occurred. The first argument
@@ -124,7 +126,7 @@ export declare class Database extends EventEmitter {
124
126
  * will be emitted on the database object. If closing succeeded, a close event with no
125
127
  * parameters is emitted, regardless of whether a callback was provided or not.
126
128
  */
127
- close(callback?: ErrorCallback): void;
129
+ close(callback?: ConnectionCallback): void;
128
130
  /**
129
131
  * Loads a compiled SQLite extension into the database connection object.
130
132
  * @param path Filename of the extension to load.
@@ -134,7 +136,7 @@ export declare class Database extends EventEmitter {
134
136
  * and an error occurred, an error event with the error object as the only parameter
135
137
  * will be emitted on the database object.
136
138
  */
137
- loadExtension(_path: string, callback?: ErrorCallback): this;
139
+ loadExtension(_path: string, callback?: ConnectionCallback): this;
138
140
  /**
139
141
  * Allows the user to interrupt long-running queries. Wrapper around
140
142
  * sqlite3_interrupt and causes other data-fetching functions to be
@@ -152,6 +154,10 @@ export declare class Database extends EventEmitter {
152
154
  * metadata in case of insert, update, delete.
153
155
  */
154
156
  sql(sql: TemplateStringsArray | string | SQLiteCloudCommand, ...values: any[]): Promise<any>;
157
+ /**
158
+ * Returns true if the database connection is open.
159
+ */
160
+ isConnected(): boolean;
155
161
  /**
156
162
  * PubSub class provides a Pub/Sub real-time updates and notifications system to
157
163
  * allow multiple applications to communicate with each other asynchronously.
@@ -49,13 +49,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
49
49
  };
50
50
  Object.defineProperty(exports, "__esModule", { value: true });
51
51
  exports.Database = void 0;
52
- const rowset_1 = require("./rowset");
53
- const types_1 = require("./types");
54
- const utilities_1 = require("./utilities");
52
+ // Trying as much as possible to be a drop-in replacement for SQLite3 API
53
+ // https://github.com/TryGhost/node-sqlite3/wiki/API
54
+ // https://github.com/TryGhost/node-sqlite3
55
+ // https://github.com/TryGhost/node-sqlite3/blob/master/lib/sqlite3.d.ts
55
56
  const eventemitter3_1 = __importDefault(require("eventemitter3"));
56
- const utilities_2 = require("./utilities");
57
57
  const pubsub_1 = require("./pubsub");
58
+ const queue_1 = require("./queue");
59
+ const rowset_1 = require("./rowset");
58
60
  const statement_1 = require("./statement");
61
+ const types_1 = require("./types");
62
+ const utilities_1 = require("./utilities");
59
63
  // Uses eventemitter3 instead of node events for browser compatibility
60
64
  // https://github.com/primus/eventemitter3
61
65
  /**
@@ -67,9 +71,10 @@ const statement_1 = require("./statement");
67
71
  class Database extends eventemitter3_1.default {
68
72
  constructor(config, mode, callback) {
69
73
  super();
70
- /** Database connections */
71
- this.connections = [];
74
+ /** Used to syncronize opening of connection and commands */
75
+ this.operations = new queue_1.OperationsQueue();
72
76
  this.config = typeof config === 'string' ? { connectionstring: config } : config;
77
+ this.connection = null;
73
78
  // mode is optional and so is callback
74
79
  // https://github.com/TryGhost/node-sqlite3/wiki/API#new-sqlite3databasefilename--mode--callback
75
80
  if (typeof mode === 'function') {
@@ -77,8 +82,8 @@ class Database extends eventemitter3_1.default {
77
82
  mode = undefined;
78
83
  }
79
84
  // mode is ignored for now
80
- // opens first connection to the database automatically
81
- this.getConnection((error, _connection) => {
85
+ // opens the connection to the database automatically
86
+ this.createConnection(error => {
82
87
  if (callback) {
83
88
  callback.call(this, error);
84
89
  }
@@ -88,60 +93,71 @@ class Database extends eventemitter3_1.default {
88
93
  // private methods
89
94
  //
90
95
  /** Returns first available connection from connection pool */
91
- getConnection(callback) {
92
- var _a, _b, _c;
93
- // TODO sqlitecloud-js / implement database connection pool #10
94
- if (((_a = this.connections) === null || _a === void 0 ? void 0 : _a.length) > 0) {
95
- callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);
96
- }
97
- else {
98
- // connect using websocket if tls is not supported or if explicitly requested
99
- const useWebsocket = utilities_2.isBrowser || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.usewebsocket) || ((_c = this.config) === null || _c === void 0 ? void 0 : _c.gatewayurl);
100
- if (useWebsocket) {
101
- // socket.io transport works in both node.js and browser environments and connects via SQLite Cloud Gateway
96
+ createConnection(callback) {
97
+ var _a, _b;
98
+ // connect using websocket if tls is not supported or if explicitly requested
99
+ const useWebsocket = utilities_1.isBrowser || ((_a = this.config) === null || _a === void 0 ? void 0 : _a.usewebsocket) || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.gatewayurl);
100
+ if (useWebsocket) {
101
+ // socket.io transport works in both node.js and browser environments and connects via SQLite Cloud Gateway
102
+ this.operations.enqueue(done => {
102
103
  Promise.resolve().then(() => __importStar(require('./connection-ws'))).then(module => {
103
- this.connections.push(new module.default(this.config, error => {
104
+ this.connection = new module.default(this.config, (error) => {
104
105
  if (error) {
105
- this.handleError(this.connections[0], error, callback);
106
+ this.handleError(error, callback);
106
107
  }
107
108
  else {
108
- console.assert;
109
- callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);
109
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null);
110
110
  this.emitEvent('open');
111
111
  }
112
- }));
112
+ done(error);
113
+ });
113
114
  })
114
115
  .catch(error => {
115
- this.handleError(null, error, callback);
116
+ this.handleError(error, callback);
117
+ done(error);
116
118
  });
117
- }
118
- else {
119
- // tls sockets work only in node.js environments
119
+ });
120
+ }
121
+ else {
122
+ this.operations.enqueue(done => {
120
123
  Promise.resolve().then(() => __importStar(require('./connection-tls'))).then(module => {
121
- this.connections.push(new module.default(this.config, error => {
124
+ this.connection = new module.default(this.config, (error) => {
122
125
  if (error) {
123
- this.handleError(this.connections[0], error, callback);
126
+ this.handleError(error, callback);
124
127
  }
125
128
  else {
126
- console.assert;
127
- callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);
129
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null);
128
130
  this.emitEvent('open');
129
131
  }
130
- }));
132
+ done(error);
133
+ });
131
134
  })
132
135
  .catch(error => {
133
- this.handleError(null, error, callback);
136
+ this.handleError(error, callback);
137
+ done(error);
134
138
  });
135
- }
139
+ });
136
140
  }
137
141
  }
142
+ enqueueCommand(command, callback) {
143
+ this.operations.enqueue(done => {
144
+ let error = null;
145
+ // we don't wont to silently open a new connection after a disconnession
146
+ if (this.connection && this.connection.connected) {
147
+ this.connection.sendCommands(command, callback);
148
+ }
149
+ else {
150
+ error = new types_1.SQLiteCloudError('Connection unavailable. Maybe it got disconnected?', { errorCode: 'ERR_CONNECTION_NOT_ESTABLISHED' });
151
+ this.handleError(error, callback);
152
+ }
153
+ done(error);
154
+ });
155
+ }
138
156
  /** Handles an error by closing the connection, calling the callback and/or emitting an error event */
139
- handleError(connection, error, callback) {
157
+ handleError(error, callback) {
158
+ var _a;
140
159
  // an errored connection is thrown out
141
- if (connection) {
142
- this.connections = this.connections.filter(c => c !== connection);
143
- connection.close();
144
- }
160
+ (_a = this.connection) === null || _a === void 0 ? void 0 : _a.close();
145
161
  if (callback) {
146
162
  callback.call(this, error);
147
163
  }
@@ -195,10 +211,9 @@ class Database extends eventemitter3_1.default {
195
211
  }
196
212
  /** Enable verbose mode */
197
213
  verbose() {
214
+ var _a;
198
215
  this.config.verbose = true;
199
- for (const connection of this.connections) {
200
- connection.verbose();
201
- }
216
+ (_a = this.connection) === null || _a === void 0 ? void 0 : _a.verbose();
202
217
  return this;
203
218
  }
204
219
  /** Set a configuration option for the database */
@@ -209,21 +224,14 @@ class Database extends eventemitter3_1.default {
209
224
  run(sql, ...params) {
210
225
  const { args, callback } = (0, utilities_1.popCallback)(params);
211
226
  const command = { query: sql, parameters: args };
212
- this.getConnection((error, connection) => {
213
- if (error || !connection) {
214
- this.handleError(null, error, callback);
227
+ this.enqueueCommand(command, (error, results) => {
228
+ if (error) {
229
+ this.handleError(error, callback);
215
230
  }
216
231
  else {
217
- connection.sendCommands(command, (error, results) => {
218
- if (error) {
219
- this.handleError(connection, error, callback);
220
- }
221
- else {
222
- // context may include id of last row inserted, total changes, etc...
223
- const context = this.processContext(results);
224
- callback === null || callback === void 0 ? void 0 : callback.call(context || this, null, context ? context : results);
225
- }
226
- });
232
+ // context may include id of last row inserted, total changes, etc...
233
+ const context = this.processContext(results);
234
+ callback === null || callback === void 0 ? void 0 : callback.call(context || this, null, context ? context : results);
227
235
  }
228
236
  });
229
237
  return this;
@@ -231,24 +239,17 @@ class Database extends eventemitter3_1.default {
231
239
  get(sql, ...params) {
232
240
  const { args, callback } = (0, utilities_1.popCallback)(params);
233
241
  const command = { query: sql, parameters: args };
234
- this.getConnection((error, connection) => {
235
- if (error || !connection) {
236
- this.handleError(null, error, callback);
242
+ this.enqueueCommand(command, (error, results) => {
243
+ if (error) {
244
+ this.handleError(error, callback);
237
245
  }
238
246
  else {
239
- connection.sendCommands(command, (error, results) => {
240
- if (error) {
241
- this.handleError(connection, error, callback);
242
- }
243
- else {
244
- if (results && results instanceof rowset_1.SQLiteCloudRowset && results.length > 0) {
245
- callback === null || callback === void 0 ? void 0 : callback.call(this, null, results[0]);
246
- }
247
- else {
248
- callback === null || callback === void 0 ? void 0 : callback.call(this, null);
249
- }
250
- }
251
- });
247
+ if (results && results instanceof rowset_1.SQLiteCloudRowset && results.length > 0) {
248
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null, results[0]);
249
+ }
250
+ else {
251
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null);
252
+ }
252
253
  }
253
254
  });
254
255
  return this;
@@ -256,24 +257,17 @@ class Database extends eventemitter3_1.default {
256
257
  all(sql, ...params) {
257
258
  const { args, callback } = (0, utilities_1.popCallback)(params);
258
259
  const command = { query: sql, parameters: args };
259
- this.getConnection((error, connection) => {
260
- if (error || !connection) {
261
- this.handleError(null, error, callback);
260
+ this.enqueueCommand(command, (error, results) => {
261
+ if (error) {
262
+ this.handleError(error, callback);
262
263
  }
263
264
  else {
264
- connection.sendCommands(command, (error, results) => {
265
- if (error) {
266
- this.handleError(connection, error, callback);
267
- }
268
- else {
269
- if (results && results instanceof rowset_1.SQLiteCloudRowset) {
270
- callback === null || callback === void 0 ? void 0 : callback.call(this, null, results);
271
- }
272
- else {
273
- callback === null || callback === void 0 ? void 0 : callback.call(this, null);
274
- }
275
- }
276
- });
265
+ if (results && results instanceof rowset_1.SQLiteCloudRowset) {
266
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null, results);
267
+ }
268
+ else {
269
+ callback === null || callback === void 0 ? void 0 : callback.call(this, null);
270
+ }
277
271
  }
278
272
  });
279
273
  return this;
@@ -282,32 +276,25 @@ class Database extends eventemitter3_1.default {
282
276
  // extract optional parameters and one or two callbacks
283
277
  const { args, callback, complete } = (0, utilities_1.popCallback)(params);
284
278
  const command = { query: sql, parameters: args };
285
- this.getConnection((error, connection) => {
286
- if (error || !connection) {
287
- this.handleError(null, error, callback);
279
+ this.enqueueCommand(command, (error, rowset) => {
280
+ if (error) {
281
+ this.handleError(error, callback);
288
282
  }
289
283
  else {
290
- connection.sendCommands(command, (error, rowset) => {
291
- if (error) {
292
- this.handleError(connection, error, callback);
293
- }
294
- else {
295
- if (rowset && rowset instanceof rowset_1.SQLiteCloudRowset) {
296
- if (callback) {
297
- for (const row of rowset) {
298
- callback.call(this, null, row);
299
- }
300
- }
301
- if (complete) {
302
- ;
303
- complete.call(this, null, rowset.numberOfRows);
304
- }
305
- }
306
- else {
307
- callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Invalid rowset'));
284
+ if (rowset && rowset instanceof rowset_1.SQLiteCloudRowset) {
285
+ if (callback) {
286
+ for (const row of rowset) {
287
+ callback.call(this, null, row);
308
288
  }
309
289
  }
310
- });
290
+ if (complete) {
291
+ ;
292
+ complete.call(this, null, rowset.numberOfRows);
293
+ }
294
+ }
295
+ else {
296
+ callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Invalid rowset'));
297
+ }
311
298
  }
312
299
  });
313
300
  return this;
@@ -333,20 +320,13 @@ class Database extends eventemitter3_1.default {
333
320
  * will be emitted on the database object.
334
321
  */
335
322
  exec(sql, callback) {
336
- this.getConnection((error, connection) => {
337
- if (error || !connection) {
338
- this.handleError(null, error, callback);
323
+ this.enqueueCommand(sql, (error, results) => {
324
+ if (error) {
325
+ this.handleError(error, callback);
339
326
  }
340
327
  else {
341
- connection.sendCommands(sql, (error, results) => {
342
- if (error) {
343
- this.handleError(connection, error, callback);
344
- }
345
- else {
346
- const context = this.processContext(results);
347
- callback === null || callback === void 0 ? void 0 : callback.call(context ? context : this, null);
348
- }
349
- });
328
+ const context = this.processContext(results);
329
+ callback === null || callback === void 0 ? void 0 : callback.call(context ? context : this, null);
350
330
  }
351
331
  });
352
332
  return this;
@@ -361,11 +341,8 @@ class Database extends eventemitter3_1.default {
361
341
  */
362
342
  close(callback) {
363
343
  var _a;
364
- if (((_a = this.connections) === null || _a === void 0 ? void 0 : _a.length) > 0) {
365
- for (const connection of this.connections) {
366
- connection.close();
367
- }
368
- }
344
+ this.operations.clear();
345
+ (_a = this.connection) === null || _a === void 0 ? void 0 : _a.close();
369
346
  callback === null || callback === void 0 ? void 0 : callback.call(this, null);
370
347
  this.emitEvent('close');
371
348
  }
@@ -433,26 +410,25 @@ class Database extends eventemitter3_1.default {
433
410
  throw new Error('Invalid sql');
434
411
  }
435
412
  return new Promise((resolve, reject) => {
436
- this.getConnection((error, connection) => {
437
- if (error || !connection) {
413
+ this.enqueueCommand(commands, (error, results) => {
414
+ if (error) {
438
415
  reject(error);
439
416
  }
440
417
  else {
441
- connection.sendCommands(commands, (error, results) => {
442
- if (error) {
443
- reject(error);
444
- }
445
- else {
446
- // metadata for operations like insert, update, delete?
447
- const context = this.processContext(results);
448
- resolve(context ? context : results);
449
- }
450
- });
418
+ // metadata for operations like insert, update, delete?
419
+ const context = this.processContext(results);
420
+ resolve(context ? context : results);
451
421
  }
452
422
  });
453
423
  });
454
424
  });
455
425
  }
426
+ /**
427
+ * Returns true if the database connection is open.
428
+ */
429
+ isConnected() {
430
+ return this.connection != null && this.connection.connected;
431
+ }
456
432
  /**
457
433
  * PubSub class provides a Pub/Sub real-time updates and notifications system to
458
434
  * allow multiple applications to communicate with each other asynchronously.
@@ -464,12 +440,19 @@ class Database extends eventemitter3_1.default {
464
440
  getPubSub() {
465
441
  return __awaiter(this, void 0, void 0, function* () {
466
442
  return new Promise((resolve, reject) => {
467
- this.getConnection((error, connection) => {
468
- if (error || !connection) {
469
- reject(error);
443
+ this.operations.enqueue(done => {
444
+ let error = null;
445
+ try {
446
+ if (!this.connection) {
447
+ error = new types_1.SQLiteCloudError('Connection not established', { errorCode: 'ERR_CONNECTION_NOT_ESTABLISHED' });
448
+ reject(error);
449
+ }
450
+ else {
451
+ resolve(new pubsub_1.PubSub(this.connection));
452
+ }
470
453
  }
471
- else {
472
- resolve(new pubsub_1.PubSub(connection));
454
+ finally {
455
+ done(error);
473
456
  }
474
457
  });
475
458
  });
@@ -86,14 +86,14 @@ class PubSub {
86
86
  */
87
87
  removeChannel(name) {
88
88
  return __awaiter(this, void 0, void 0, function* () {
89
- return this.connection.sql(`REMOVE CHANNEL ?;`, name);
89
+ return this.connection.sql('REMOVE CHANNEL ?;', name);
90
90
  });
91
91
  }
92
92
  /**
93
93
  * Send a message to the channel.
94
94
  */
95
95
  notifyChannel(channelName, message) {
96
- return this.connection.sql `NOTIFY ${channelName} ${message};`;
96
+ return this.connection.sql('NOTIFY ? ?;', channelName, message);
97
97
  }
98
98
  /**
99
99
  * Ask the server to close the connection to the database and
@@ -17,6 +17,8 @@ export declare function getUpdateResults(results?: any): Record<string, any> | u
17
17
  * containing the arguments array with the callbacks removed (if any), and the callback itself.
18
18
  * If there are multiple callbacks, the first one is returned as 'callback' and the last one
19
19
  * as 'completeCallback'.
20
+ *
21
+ * @returns args is a simple list of SQLiteCloudDataTypes, we flat them into a single array
20
22
  */
21
23
  export declare function popCallback<T extends ErrorCallback = ErrorCallback>(args: (SQLiteCloudDataTypes | T | ErrorCallback)[]): {
22
24
  args: SQLiteCloudDataTypes[];