SqliteConnectionPool.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. const sqlite = require('sqlite');
  2. const SQL = require('sql-template-strings');
  3. const utils = require('../core/utils');
  4. const waitingDelay = 100; //ms
  5. class SqliteConnectionPool {
  6. constructor() {
  7. this.closed = true;
  8. }
  9. async open(connCount, dbFileName) {
  10. if (!Number.isInteger(connCount) || connCount <= 0)
  11. return;
  12. this.connections = [];
  13. this.freed = new Set();
  14. for (let i = 0; i < connCount; i++) {
  15. let client = await sqlite.open(dbFileName);
  16. client.configure('busyTimeout', 10000); //ms
  17. client.ret = () => {
  18. this.freed.add(i);
  19. };
  20. this.freed.add(i);
  21. this.connections[i] = client;
  22. }
  23. this.closed = false;
  24. }
  25. _setImmediate() {
  26. return new Promise((resolve) => {
  27. setImmediate(() => {
  28. return resolve();
  29. });
  30. });
  31. }
  32. async get() {
  33. if (this.closed)
  34. return;
  35. let freeConnIndex = this.freed.values().next().value;
  36. if (freeConnIndex == null) {
  37. if (waitingDelay)
  38. await utils.sleep(waitingDelay);
  39. return await this._setImmediate().then(() => this.get());
  40. }
  41. this.freed.delete(freeConnIndex);
  42. return this.connections[freeConnIndex];
  43. }
  44. async run(query) {
  45. const dbh = await this.get();
  46. try {
  47. let result = await dbh.run(query);
  48. dbh.ret();
  49. return result;
  50. } catch (e) {
  51. dbh.ret();
  52. throw e;
  53. }
  54. }
  55. async all(query) {
  56. const dbh = await this.get();
  57. try {
  58. let result = await dbh.all(query);
  59. dbh.ret();
  60. return result;
  61. } catch (e) {
  62. dbh.ret();
  63. throw e;
  64. }
  65. }
  66. async exec(query) {
  67. const dbh = await this.get();
  68. try {
  69. let result = await dbh.exec(query);
  70. dbh.ret();
  71. return result;
  72. } catch (e) {
  73. dbh.ret();
  74. throw e;
  75. }
  76. }
  77. async close() {
  78. for (let i = 0; i < this.connections.length; i++) {
  79. await this.connections[i].close();
  80. }
  81. this.closed = true;
  82. }
  83. // Modified from node-sqlite/.../src/Database.js
  84. async migrate(migs, table, force) {
  85. const migrations = migs.sort((a, b) => Math.sign(a.id - b.id));
  86. if (!migrations.length) {
  87. throw new Error('No migration data');
  88. }
  89. migrations.map(migration => {
  90. const data = migration.data;
  91. const [up, down] = data.split(/^--\s+?down\b/mi);
  92. if (!down) {
  93. const message = `The ${migration.filename} file does not contain '-- Down' separator.`;
  94. throw new Error(message);
  95. } else {
  96. /* eslint-disable no-param-reassign */
  97. migration.up = up.replace(/^-- .*?$/gm, '').trim();// Remove comments
  98. migration.down = down.trim(); // and trim whitespaces
  99. }
  100. });
  101. // Create a database table for migrations meta data if it doesn't exist
  102. await this.run(`CREATE TABLE IF NOT EXISTS "${table}" (
  103. id INTEGER PRIMARY KEY,
  104. name TEXT NOT NULL,
  105. up TEXT NOT NULL,
  106. down TEXT NOT NULL
  107. )`);
  108. // Get the list of already applied migrations
  109. let dbMigrations = await this.all(
  110. `SELECT id, name, up, down FROM "${table}" ORDER BY id ASC`,
  111. );
  112. // Undo migrations that exist only in the database but not in migs,
  113. // also undo the last migration if the `force` option was set to `last`.
  114. const lastMigration = migrations[migrations.length - 1];
  115. for (const migration of dbMigrations.slice().sort((a, b) => Math.sign(b.id - a.id))) {
  116. if (!migrations.some(x => x.id === migration.id) ||
  117. (force === 'last' && migration.id === lastMigration.id)) {
  118. const dbh = await this.get();
  119. await dbh.run('BEGIN');
  120. try {
  121. await dbh.exec(migration.down);
  122. await dbh.run(SQL`DELETE FROM "`.append(table).append(SQL`" WHERE id = ${migration.id}`));
  123. await dbh.run('COMMIT');
  124. dbMigrations = dbMigrations.filter(x => x.id !== migration.id);
  125. } catch (err) {
  126. await dbh.run('ROLLBACK');
  127. throw err;
  128. } finally {
  129. dbh.ret();
  130. }
  131. } else {
  132. break;
  133. }
  134. }
  135. // Apply pending migrations
  136. let applied = [];
  137. const lastMigrationId = dbMigrations.length ? dbMigrations[dbMigrations.length - 1].id : 0;
  138. for (const migration of migrations) {
  139. if (migration.id > lastMigrationId) {
  140. const dbh = await this.get();
  141. await dbh.run('BEGIN');
  142. try {
  143. await dbh.exec(migration.up);
  144. await dbh.run(SQL`INSERT INTO "`.append(table).append(
  145. SQL`" (id, name, up, down) VALUES (${migration.id}, ${migration.name}, ${migration.up}, ${migration.down})`)
  146. );
  147. await dbh.run('COMMIT');
  148. applied.push(migration.id);
  149. } catch (err) {
  150. await dbh.run('ROLLBACK');
  151. throw err;
  152. } finally {
  153. dbh.ret();
  154. }
  155. }
  156. }
  157. return applied;
  158. }
  159. }
  160. module.exports = SqliteConnectionPool;