@nymphjs/driver-mysql 1.0.0-beta.14 → 1.0.0-beta.140

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.
@@ -1,26 +1,43 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const child_process_1 = __importDefault(require("child_process"));
7
- const mysql_1 = __importDefault(require("@vlasky/mysql"));
8
- const nymph_1 = require("@nymphjs/nymph");
9
- const guid_1 = require("@nymphjs/guid");
10
- const conf_1 = require("./conf");
11
- const mysql = mysql_1.default;
12
- class MySQLDriver extends nymph_1.NymphDriver {
1
+ import mysql from 'mysql2';
2
+ import SqlString from 'sqlstring';
3
+ import { NymphDriver, EntityConflictError, EntityInvalidDataError, EntityUniqueConstraintError, InvalidParametersError, NotConfiguredError, QueryFailedError, UnableToConnectError, xor, } from '@nymphjs/nymph';
4
+ import { makeTableSuffix } from '@nymphjs/guid';
5
+ import { MySQLDriverConfigDefaults as defaults, } from './conf/index.js';
6
+ /**
7
+ * The MySQL Nymph database driver.
8
+ */
9
+ export default class MySQLDriver extends NymphDriver {
10
+ config;
11
+ mysqlConfig;
12
+ prefix;
13
+ connected = false;
14
+ // @ts-ignore: this is assigned in connect(), which is called by the constructor.
15
+ link;
16
+ transaction = null;
13
17
  static escape(input) {
14
- return mysql.escapeId(input);
18
+ return SqlString.escapeId(input, true);
15
19
  }
16
20
  static escapeValue(input) {
17
21
  return mysql.escape(input);
18
22
  }
23
+ static escapeTags(tags) {
24
+ return tags.map(MySQLDriver.escapeTag);
25
+ }
26
+ static escapeTag(tag) {
27
+ return tag
28
+ .replace(/\\/g, () => '\\\\')
29
+ .replace(/_/g, () => '\\_')
30
+ .replace(/ /g, () => '_');
31
+ }
32
+ static unescapeTags(tags) {
33
+ return tags.map(MySQLDriver.unescapeTag);
34
+ }
35
+ static unescapeTag(tag) {
36
+ return tag.replace(/\\([\\_])|_/g, (_, char) => char != null ? char : ' ');
37
+ }
19
38
  constructor(config, link, transaction) {
20
39
  super();
21
- this.connected = false;
22
- this.transaction = null;
23
- this.config = { ...conf_1.MySQLDriverConfigDefaults, ...config };
40
+ this.config = { ...defaults, ...config };
24
41
  const { host, user, password, database, port, customPoolConfig } = this.config;
25
42
  this.mysqlConfig = customPoolConfig ?? {
26
43
  host,
@@ -41,6 +58,11 @@ class MySQLDriver extends nymph_1.NymphDriver {
41
58
  this.connect();
42
59
  }
43
60
  }
61
+ /**
62
+ * This is used internally by Nymph. Don't call it yourself.
63
+ *
64
+ * @returns A clone of this instance.
65
+ */
44
66
  clone() {
45
67
  return new MySQLDriver(this.config, this.link, this.transaction ?? undefined);
46
68
  }
@@ -50,22 +72,29 @@ class MySQLDriver extends nymph_1.NymphDriver {
50
72
  }
51
73
  return new Promise((resolve, reject) => this.link.getConnection((err, con) => (err ? reject(err) : resolve(con))));
52
74
  }
75
+ /**
76
+ * Connect to the MySQL database.
77
+ *
78
+ * @returns Whether this instance is connected to a MySQL database.
79
+ */
53
80
  async connect() {
81
+ // If we think we're connected, try pinging the server.
54
82
  try {
55
83
  if (this.connected) {
56
84
  const connection = await new Promise((resolve, reject) => this.link.getConnection((err, con) => err ? reject(err) : resolve(con)));
57
- await new Promise((resolve) => connection.ping(() => {
58
- resolve(0);
59
- }));
60
85
  connection.release();
61
86
  }
62
87
  }
63
88
  catch (e) {
64
89
  this.connected = false;
65
90
  }
91
+ // Connecting, selecting database
66
92
  if (!this.connected) {
67
93
  try {
68
- this.link = mysql.createPool(this.mysqlConfig);
94
+ this.link = mysql.createPool({
95
+ ...this.mysqlConfig,
96
+ charset: 'utf8mb4_bin',
97
+ });
69
98
  this.connected = true;
70
99
  }
71
100
  catch (e) {
@@ -73,15 +102,20 @@ class MySQLDriver extends nymph_1.NymphDriver {
73
102
  this.mysqlConfig.user === 'nymph' &&
74
103
  this.mysqlConfig.password === 'password' &&
75
104
  this.mysqlConfig.database === 'nymph') {
76
- throw new nymph_1.NotConfiguredError("It seems the config hasn't been set up correctly.");
105
+ throw new NotConfiguredError("It seems the config hasn't been set up correctly.");
77
106
  }
78
107
  else {
79
- throw new nymph_1.UnableToConnectError('Could not connect: ' + e?.message);
108
+ throw new UnableToConnectError('Could not connect: ' + e?.message);
80
109
  }
81
110
  }
82
111
  }
83
112
  return this.connected;
84
113
  }
114
+ /**
115
+ * Disconnect from the MySQL database.
116
+ *
117
+ * @returns Whether this instance is connected to a MySQL database.
118
+ */
85
119
  async disconnect() {
86
120
  if (this.connected) {
87
121
  await new Promise((resolve) => this.link.end(() => resolve(0)));
@@ -90,68 +124,173 @@ class MySQLDriver extends nymph_1.NymphDriver {
90
124
  return this.connected;
91
125
  }
92
126
  async inTransaction() {
127
+ if (this.transaction && this.transaction.count === 0) {
128
+ this.transaction = null;
129
+ }
93
130
  return !!this.transaction;
94
131
  }
132
+ /**
133
+ * Check connection status.
134
+ *
135
+ * @returns Whether this instance is connected to a MySQL database.
136
+ */
95
137
  isConnected() {
96
138
  return this.connected;
97
139
  }
98
- createTables(etype = null) {
99
- this.queryRunSync('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
100
- let foreignKeyDataTableGuid = '';
101
- let foreignKeyDataComparisonsTableGuid = '';
102
- let foreignKeyReferencesTableGuid = '';
103
- if (this.config.foreignKeys) {
104
- foreignKeyDataTableGuid = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
105
- foreignKeyDataComparisonsTableGuid = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
106
- foreignKeyReferencesTableGuid = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
107
- }
108
- if (etype != null) {
109
- this.queryRunSync(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (
140
+ async createEntitiesTable(etype) {
141
+ // Create the entity table.
142
+ await this.queryRun(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (
110
143
  \`guid\` BINARY(12) NOT NULL,
111
144
  \`tags\` LONGTEXT,
112
145
  \`cdate\` DOUBLE PRECISION NOT NULL,
113
146
  \`mdate\` DOUBLE PRECISION NOT NULL,
147
+ \`user\` BINARY(12),
148
+ \`group\` BINARY(12),
149
+ \`acUser\` TINYINT UNSIGNED,
150
+ \`acGroup\` TINYINT UNSIGNED,
151
+ \`acOther\` TINYINT UNSIGNED,
152
+ \`acRead\` LONGTEXT,
153
+ \`acWrite\` LONGTEXT,
154
+ \`acFull\` LONGTEXT,
114
155
  PRIMARY KEY (\`guid\`),
156
+ INDEX \`id_guid\` USING HASH (\`guid\`),
115
157
  INDEX \`id_cdate\` USING BTREE (\`cdate\`),
116
158
  INDEX \`id_mdate\` USING BTREE (\`mdate\`),
117
- FULLTEXT \`id_tags\` (\`tags\`)
118
- ) ENGINE ${this.config.engine}
119
- CHARACTER SET utf8 COLLATE utf8_bin;`);
120
- this.queryRunSync(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (
121
- \`guid\` BINARY(12) NOT NULL${foreignKeyDataTableGuid},
122
- \`name\` TEXT NOT NULL,
123
- \`value\` LONGTEXT NOT NULL,
124
- PRIMARY KEY (\`guid\`,\`name\`(255)),
125
- INDEX \`id_name\` USING HASH (\`name\`(255)),
126
- INDEX \`id_name_value\` USING BTREE (\`name\`(255), \`value\`(512))
159
+ FULLTEXT \`id_tags\` (\`tags\`),
160
+ INDEX \`id_user_acUser\` USING BTREE (\`user\`, \`acUser\`),
161
+ INDEX \`id_group_acGroup\` USING BTREE (\`group\`, \`acGroup\`),
162
+ INDEX \`id_acUser\` USING BTREE (\`acUser\`),
163
+ INDEX \`id_acGroup\` USING BTREE (\`acGroup\`),
164
+ INDEX \`id_acOther\` USING BTREE (\`acOther\`),
165
+ FULLTEXT \`id_acRead\` (\`acRead\`),
166
+ FULLTEXT \`id_acWrite\` (\`acWrite\`),
167
+ FULLTEXT \`id_acFull\` (\`acFull\`)
127
168
  ) ENGINE ${this.config.engine}
128
- CHARACTER SET utf8 COLLATE utf8_bin;`);
129
- this.queryRunSync(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} (
130
- \`guid\` BINARY(12) NOT NULL${foreignKeyDataComparisonsTableGuid},
169
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`);
170
+ }
171
+ async addTilmeldColumnsAndIndexes(etype) {
172
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`user\` BINARY(12);`);
173
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`group\` BINARY(12);`);
174
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`acUser\` TINYINT UNSIGNED;`);
175
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`acGroup\` TINYINT UNSIGNED;`);
176
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`acOther\` TINYINT UNSIGNED;`);
177
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`acRead\` LONGTEXT;`);
178
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`acWrite\` LONGTEXT;`);
179
+ await this.queryRun(`ALTER TABLE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ADD COLUMN \`acFull\` LONGTEXT;`);
180
+ await this.createEntitiesTilmeldIndexes(etype);
181
+ }
182
+ async createEntitiesTilmeldIndexes(etype) {
183
+ await this.queryRun(`CREATE INDEX \`id_user_acUser\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`user\`, \`acUser\`) USING BTREE;`);
184
+ await this.queryRun(`CREATE INDEX \`id_group_acGroup\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`group\`, \`acGroup\`) USING BTREE;`);
185
+ await this.queryRun(`CREATE INDEX \`id_acUser\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`acUser\`) USING BTREE;`);
186
+ await this.queryRun(`CREATE INDEX \`id_acGroup\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`acGroup\`) USING BTREE;`);
187
+ await this.queryRun(`CREATE INDEX \`id_acOther\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`acOther\`) USING BTREE;`);
188
+ await this.queryRun(`CREATE FULLTEXT INDEX \`id_acRead\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`acRead\`);`);
189
+ await this.queryRun(`CREATE FULLTEXT INDEX \`id_acWrite\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`acWrite\`);`);
190
+ await this.queryRun(`CREATE FULLTEXT INDEX \`id_acFull\` ON ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`acFull\`);`);
191
+ }
192
+ async createDataTable(etype) {
193
+ let foreignKey = '';
194
+ if (this.config.foreignKeys) {
195
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
196
+ }
197
+ // Create the data table.
198
+ await this.queryRun(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (
199
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
131
200
  \`name\` TEXT NOT NULL,
132
- \`truthy\` BOOLEAN,
201
+ \`value\` CHAR(1) NOT NULL,
202
+ \`json\` JSON,
133
203
  \`string\` LONGTEXT,
134
204
  \`number\` DOUBLE,
205
+ \`truthy\` BOOLEAN,
135
206
  PRIMARY KEY (\`guid\`, \`name\`(255)),
136
- INDEX \`id_name\` USING HASH (\`name\`(255))
207
+ INDEX \`id_name_guid\` USING BTREE (\`name\`(255), \`guid\`),
208
+ INDEX \`id_name_string_guid\` USING BTREE (\`name\`(255), \`string\`(500), \`guid\`),
209
+ INDEX \`id_name_number_guid\` USING BTREE (\`name\`(255), \`number\`, \`guid\`),
210
+ INDEX \`id_name_truthy_guid\` USING BTREE (\`name\`(255), \`truthy\`, \`guid\`),
211
+ INDEX \`id_name_json_guid\` USING BTREE (\`name\`(255), (CAST(\`json\` AS CHAR(500)) COLLATE utf8mb4_bin), \`guid\`)
137
212
  ) ENGINE ${this.config.engine}
138
- CHARACTER SET utf8 COLLATE utf8_bin;`);
139
- this.queryRunSync(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} (
140
- \`guid\` BINARY(12) NOT NULL${foreignKeyReferencesTableGuid},
213
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`);
214
+ }
215
+ async createReferencesTable(etype) {
216
+ let foreignKey = '';
217
+ if (this.config.foreignKeys) {
218
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
219
+ }
220
+ // Create the references table.
221
+ await this.queryRun(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} (
222
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
141
223
  \`name\` TEXT NOT NULL,
142
224
  \`reference\` BINARY(12) NOT NULL,
143
225
  PRIMARY KEY (\`guid\`, \`name\`(255), \`reference\`),
144
- INDEX \`id_name_reference\` USING BTREE (\`name\`(255), \`reference\`)
226
+ INDEX \`id_name_reference_guid\` USING HASH (\`name\`(255), \`reference\`, \`guid\`)
227
+ ) ENGINE ${this.config.engine}
228
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`);
229
+ }
230
+ async createTokensTable(etype) {
231
+ let foreignKey = '';
232
+ if (this.config.foreignKeys) {
233
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
234
+ }
235
+ // Create the tokens table.
236
+ await this.queryRun(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} (
237
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
238
+ \`name\` TEXT NOT NULL,
239
+ \`token\` INT NOT NULL,
240
+ \`position\` INT UNSIGNED NOT NULL,
241
+ \`stem\` BOOLEAN NOT NULL,
242
+ PRIMARY KEY (\`guid\`, \`name\`(255), \`token\`, \`position\`),
243
+ INDEX \`id_name_token_guid\` USING btree (\`name\`(255), \`token\`, \`guid\`)
244
+ ) ENGINE ${this.config.engine}
245
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`);
246
+ }
247
+ async createUniquesTable(etype) {
248
+ let foreignKey = '';
249
+ if (this.config.foreignKeys) {
250
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)}(\`guid\`) ON DELETE CASCADE`;
251
+ }
252
+ // Create the unique strings table.
253
+ // 255 key is max length for charset UTF8.
254
+ await this.queryRun(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} (
255
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
256
+ \`unique\` TEXT NOT NULL,
257
+ PRIMARY KEY (\`guid\`, \`unique\`(255)),
258
+ INDEX \`id_guid\` USING HASH (\`guid\`),
259
+ CONSTRAINT \`uc_unique\` UNIQUE (\`unique\`(255))
145
260
  ) ENGINE ${this.config.engine}
146
- CHARACTER SET utf8 COLLATE utf8_bin;`);
261
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`);
262
+ }
263
+ /**
264
+ * Create entity tables in the database.
265
+ *
266
+ * @param etype The entity type to create a table for. If this is blank, the default tables are created.
267
+ * @returns True on success, false on failure.
268
+ */
269
+ async createTables(etype = null) {
270
+ await this.queryRun('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
271
+ if (etype != null) {
272
+ await this.createEntitiesTable(etype);
273
+ await this.createDataTable(etype);
274
+ await this.createReferencesTable(etype);
275
+ await this.createTokensTable(etype);
276
+ await this.createUniquesTable(etype);
147
277
  }
148
278
  else {
149
- this.queryRunSync(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}uids`)} (
279
+ // Create the UID table.
280
+ await this.queryRun(`CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(`${this.prefix}uids`)} (
150
281
  \`name\` TEXT NOT NULL,
151
282
  \`cur_uid\` BIGINT(20) UNSIGNED NOT NULL,
152
- PRIMARY KEY (\`name\`(100))
283
+ PRIMARY KEY (\`name\`(128))
153
284
  ) ENGINE ${this.config.engine}
154
- CHARACTER SET utf8 COLLATE utf8_bin;`);
285
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`);
286
+ }
287
+ if (this.transaction &&
288
+ this.transaction.count > 0 &&
289
+ this.config.transactions) {
290
+ this.transaction.count = 0;
291
+ this.transaction.connection?.release();
292
+ this.transaction.connection = null;
293
+ this.transaction = null;
155
294
  }
156
295
  return true;
157
296
  }
@@ -169,190 +308,128 @@ class MySQLDriver extends nymph_1.NymphDriver {
169
308
  }
170
309
  async query(runQuery, query, etypes = []) {
171
310
  try {
311
+ this.nymph.config.debugInfo('mysql:query', query);
172
312
  return await runQuery();
173
313
  }
174
314
  catch (e) {
175
315
  const errorCode = e?.errno;
176
- if (errorCode === 1146 && this.createTables()) {
316
+ if (errorCode === 1146 && (await this.createTables())) {
317
+ // If the tables don't exist yet, create them.
177
318
  for (let etype of etypes) {
178
- this.createTables(etype);
179
- }
180
- try {
181
- return await runQuery();
182
- }
183
- catch (e2) {
184
- throw new nymph_1.QueryFailedError('Query failed: ' + e2?.errno + ' - ' + e2?.message, query);
185
- }
186
- }
187
- else if (errorCode === 2006) {
188
- if (!this.connect()) {
189
- throw new nymph_1.QueryFailedError('Query failed: ' + e?.errno + ' - ' + e?.message, query);
319
+ await this.createTables(etype);
190
320
  }
191
321
  try {
192
322
  return await runQuery();
193
323
  }
194
324
  catch (e2) {
195
- throw new nymph_1.QueryFailedError('Query failed: ' + e2?.errno + ' - ' + e2?.message, query);
325
+ throw new QueryFailedError('Query failed: ' + e2?.errno + ' - ' + e2?.message, query, e2?.errno);
196
326
  }
197
327
  }
198
- else {
199
- throw e;
200
- }
201
- }
202
- }
203
- querySync(runQuery, query, etypes = []) {
204
- try {
205
- return runQuery();
206
- }
207
- catch (e) {
208
- const errorCode = e?.errno;
209
- if (errorCode === 1146 && this.createTables()) {
210
- for (let etype of etypes) {
211
- this.createTables(etype);
212
- }
213
- try {
214
- return runQuery();
215
- }
216
- catch (e2) {
217
- throw new nymph_1.QueryFailedError('Query failed: ' + e2?.errno + ' - ' + e2?.message, query);
218
- }
328
+ else if (errorCode === 1062) {
329
+ throw new EntityUniqueConstraintError(`Unique constraint violation.`);
219
330
  }
220
331
  else if (errorCode === 2006) {
221
- if (!this.connect()) {
222
- throw new nymph_1.QueryFailedError('Query failed: ' + e?.errno + ' - ' + e?.message, query);
332
+ // If the MySQL server disconnected, reconnect to it.
333
+ if (!(await this.connect())) {
334
+ throw new QueryFailedError('Query failed: ' + e?.errno + ' - ' + e?.message, query, e?.errno);
223
335
  }
224
336
  try {
225
- return runQuery();
337
+ return await runQuery();
226
338
  }
227
339
  catch (e2) {
228
- throw new nymph_1.QueryFailedError('Query failed: ' + e2?.errno + ' - ' + e2?.message, query);
340
+ throw new QueryFailedError('Query failed: ' + e2?.errno + ' - ' + e2?.message, query, e2?.errno);
229
341
  }
230
342
  }
231
343
  else {
232
- throw e;
344
+ throw new QueryFailedError('Query failed: ' + e?.errno + ' - ' + e?.message, query, e?.errno);
233
345
  }
234
346
  }
235
347
  }
236
- queryIter(query, { etypes = [], params = {}, } = {}) {
348
+ queryArray(query, { etypes = [], params = {}, } = {}) {
237
349
  const { query: newQuery, params: newParams } = this.translateQuery(query, params);
238
350
  return this.query(async () => {
239
- const results = await new Promise((resolve, reject) => {
240
- try {
241
- (this.transaction?.connection ?? this.link).query(newQuery, newParams, (error, results) => {
242
- if (error) {
243
- reject(error);
244
- }
245
- resolve(results);
246
- });
247
- }
248
- catch (e) {
249
- reject(e);
351
+ const results = await new Promise(async (resolve, reject) => {
352
+ // Only do one query at a time in transations.
353
+ let myResolve = () => { };
354
+ const myPromise = new Promise((resolve) => {
355
+ myResolve = resolve;
356
+ });
357
+ if (this.transaction) {
358
+ const latestPromise = this.transaction.latestPromise;
359
+ this.transaction.latestPromise = myPromise;
360
+ await latestPromise;
250
361
  }
362
+ (this.transaction?.connection ?? this.link).query(newQuery, newParams, (error, results) => {
363
+ if (error) {
364
+ reject(error);
365
+ }
366
+ else {
367
+ resolve(results);
368
+ }
369
+ myResolve();
370
+ });
251
371
  });
252
372
  return results;
253
373
  }, `${query} -- ${JSON.stringify(params)}`, etypes);
254
374
  }
255
- queryIterSync(query, { etypes = [], params = {}, } = {}) {
256
- const { query: newQuery, params: newParams } = this.translateQuery(query, params);
257
- return this.querySync(() => {
258
- const output = child_process_1.default.spawnSync(process.argv0, [__dirname + '/runMysqlSync.js'], {
259
- input: JSON.stringify({
260
- mysqlConfig: this.mysqlConfig,
261
- query: newQuery,
262
- params: newParams,
263
- }),
264
- timeout: 30000,
265
- maxBuffer: 100 * 1024 * 1024,
266
- encoding: 'utf8',
267
- windowsHide: true,
268
- });
269
- try {
270
- const { results } = JSON.parse(output.stdout);
271
- return results;
272
- }
273
- catch (e) {
274
- }
275
- if (output.status === 0) {
276
- throw new Error('Unknown parse error.');
277
- }
278
- const err = JSON.parse(output.stderr);
279
- const e = new Error(err.name);
280
- for (const name in err) {
281
- e[name] = err[name];
282
- }
283
- }, `${query} -- ${JSON.stringify(params)}`, etypes);
284
- }
285
375
  queryGet(query, { etypes = [], params = {}, } = {}) {
286
376
  const { query: newQuery, params: newParams } = this.translateQuery(query, params);
287
377
  return this.query(async () => {
288
- const results = await new Promise((resolve, reject) => {
289
- try {
290
- (this.transaction?.connection ?? this.link).query(newQuery, newParams, (error, results) => {
291
- if (error) {
292
- reject(error);
293
- }
294
- resolve(results);
295
- });
296
- }
297
- catch (e) {
298
- reject(e);
378
+ const results = await new Promise(async (resolve, reject) => {
379
+ // Only do one query at a time in transations.
380
+ let myResolve = () => { };
381
+ const myPromise = new Promise((resolve) => {
382
+ myResolve = resolve;
383
+ });
384
+ if (this.transaction) {
385
+ const latestPromise = this.transaction.latestPromise;
386
+ this.transaction.latestPromise = myPromise;
387
+ await latestPromise;
299
388
  }
389
+ (this.transaction?.connection ?? this.link).query(newQuery, newParams, (error, results) => {
390
+ if (error) {
391
+ reject(error);
392
+ }
393
+ else {
394
+ resolve(results);
395
+ }
396
+ myResolve();
397
+ });
300
398
  });
301
399
  return results[0];
302
400
  }, `${query} -- ${JSON.stringify(params)}`, etypes);
303
401
  }
304
- queryRun(query, { etypes = [], params = {}, } = {}) {
402
+ queryRun(query, { etypes = [], params = {}, transaction, } = {}) {
305
403
  const { query: newQuery, params: newParams } = this.translateQuery(query, params);
306
404
  return this.query(async () => {
307
- const results = await new Promise((resolve, reject) => {
308
- try {
309
- (this.transaction?.connection ?? this.link).query(newQuery, newParams, (error, results) => {
310
- if (error) {
311
- reject(error);
312
- }
313
- resolve(results);
314
- });
315
- }
316
- catch (e) {
317
- reject(e);
405
+ const results = await new Promise(async (resolve, reject) => {
406
+ // Only do one query at a time in transations.
407
+ let myResolve = () => { };
408
+ const myPromise = new Promise((resolve) => {
409
+ myResolve = resolve;
410
+ });
411
+ const trans = transaction ?? this.transaction;
412
+ if (trans) {
413
+ const latestPromise = trans.latestPromise;
414
+ trans.latestPromise = myPromise;
415
+ await latestPromise;
318
416
  }
417
+ (trans?.connection ?? this.link).query(newQuery, newParams, (error, results) => {
418
+ if (error) {
419
+ reject(error);
420
+ }
421
+ else {
422
+ resolve(results);
423
+ }
424
+ myResolve();
425
+ });
319
426
  });
320
427
  return { changes: results.changedRows ?? 0 };
321
428
  }, `${query} -- ${JSON.stringify(params)}`, etypes);
322
429
  }
323
- queryRunSync(query, { etypes = [], params = {}, } = {}) {
324
- const { query: newQuery, params: newParams } = this.translateQuery(query, params);
325
- return this.querySync(() => {
326
- const output = child_process_1.default.spawnSync(process.argv0, [__dirname + '/runMysqlSync.js'], {
327
- input: JSON.stringify({
328
- mysqlConfig: this.mysqlConfig,
329
- query: newQuery,
330
- params: newParams,
331
- }),
332
- timeout: 30000,
333
- maxBuffer: 100 * 1024 * 1024,
334
- encoding: 'utf8',
335
- windowsHide: true,
336
- });
337
- try {
338
- const { results } = JSON.parse(output.stdout);
339
- return { changes: results.changedRows ?? 0 };
340
- }
341
- catch (e) {
342
- }
343
- if (output.status === 0) {
344
- throw new Error('Unknown parse error.');
345
- }
346
- const err = JSON.parse(output.stderr);
347
- const e = new Error(err.name);
348
- for (const name in err) {
349
- e[name] = err[name];
350
- }
351
- }, `${query} -- ${JSON.stringify(params)}`, etypes);
352
- }
353
430
  async commit(name) {
354
431
  if (name == null || typeof name !== 'string' || name.length === 0) {
355
- throw new nymph_1.InvalidParametersError('Transaction commit attempted without a name.');
432
+ throw new InvalidParametersError('Transaction commit attempted without a name.');
356
433
  }
357
434
  if (!this.transaction || this.transaction.count === 0) {
358
435
  this.transaction = null;
@@ -394,32 +471,39 @@ class MySQLDriver extends nymph_1.NymphDriver {
394
471
  guid,
395
472
  },
396
473
  });
397
- await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
474
+ await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
475
+ etypes: [etype],
476
+ params: {
477
+ guid,
478
+ },
479
+ });
480
+ await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
398
481
  etypes: [etype],
399
482
  params: {
400
483
  guid,
401
484
  },
402
485
  });
403
- await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
486
+ await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
404
487
  etypes: [etype],
405
488
  params: {
406
489
  guid,
407
490
  },
408
491
  });
409
- await this.commit('nymph-delete');
410
- if (this.nymph.config.cache) {
411
- this.cleanCache(guid);
412
- }
413
- return true;
414
492
  }
415
493
  catch (e) {
494
+ this.nymph.config.debugError('mysql', `Delete entity error: "${e}"`);
416
495
  await this.rollback('nymph-delete');
417
496
  throw e;
418
497
  }
498
+ await this.commit('nymph-delete');
499
+ return true;
419
500
  }
420
501
  async deleteUID(name) {
421
502
  if (!name) {
422
- throw new nymph_1.InvalidParametersError('Name not given for UID');
503
+ throw new InvalidParametersError('Name not given for UID');
504
+ }
505
+ if (name.length > 128) {
506
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
423
507
  }
424
508
  await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}uids`)} WHERE \`name\`=@name;`, {
425
509
  params: {
@@ -428,79 +512,242 @@ class MySQLDriver extends nymph_1.NymphDriver {
428
512
  });
429
513
  return true;
430
514
  }
431
- async exportEntities(writeLine) {
432
- writeLine('#nex2');
433
- writeLine('# Nymph Entity Exchange v2');
434
- writeLine('# http://nymph.io');
435
- writeLine('#');
436
- writeLine('# Generation Time: ' + new Date().toLocaleString());
437
- writeLine('');
438
- writeLine('#');
439
- writeLine('# UIDs');
440
- writeLine('#');
441
- writeLine('');
442
- let uids = await this.queryIter(`SELECT * FROM ${MySQLDriver.escape(`${this.prefix}uids`)} ORDER BY \`name\`;`);
443
- for (const uid of uids) {
444
- writeLine(`<${uid.name}>[${uid.cur_uid}]`);
445
- }
446
- writeLine('');
447
- writeLine('#');
448
- writeLine('# Entities');
449
- writeLine('#');
450
- writeLine('');
451
- const tables = await this.queryIter('SHOW TABLES;');
515
+ async getIndexes(etype) {
516
+ const indexes = [];
517
+ for (let [scope, suffix] of [
518
+ ['data', '_string_guid'],
519
+ ['references', '_reference_guid'],
520
+ ['tokens', '_token_guid'],
521
+ ]) {
522
+ const indexDefinitions = await this.queryArray(`SHOW INDEXES FROM ${MySQLDriver.escape(`${this.prefix}${scope}_${etype}`)} WHERE \`Key_name\` LIKE @pattern AND \`Seq_in_index\`=1;`, {
523
+ params: {
524
+ pattern: `${this.prefix}${scope}_${etype}_id_custom_%${suffix}`,
525
+ },
526
+ });
527
+ for (const indexDefinition of indexDefinitions) {
528
+ indexes.push({
529
+ scope,
530
+ name: indexDefinition.Key_name.substring(`${this.prefix}${scope}_${etype}_id_custom_`.length, indexDefinition.Key_name.length - suffix.length),
531
+ property: (indexDefinition.Expression.match(/\s*\(?\s*`?name`?\s*=\s*(?:\w*)\\*'(.*?)\\*'/) ?? [])[1] ?? '',
532
+ });
533
+ }
534
+ }
535
+ return indexes;
536
+ }
537
+ async addIndex(etype, definition) {
538
+ this.checkIndexName(definition.name);
539
+ await this.deleteIndex(etype, definition.scope, definition.name);
540
+ if (definition.scope === 'data') {
541
+ await this.queryRun(`CREATE INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${definition.name}_string_guid`)} USING btree ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`string\`(500), \`guid\`);`);
542
+ await this.queryRun(`CREATE INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${definition.name}_number_guid`)} USING btree ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`number\`, \`guid\`);`);
543
+ await this.queryRun(`CREATE INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${definition.name}_truthy_guid`)} USING btree ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`truthy\`, \`guid\`);`);
544
+ await this.queryRun(`CREATE INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${definition.name}_json_guid`)} USING btree ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), (CAST(\`json\` AS CHAR(500)) COLLATE utf8mb4_bin), \`guid\`);`);
545
+ }
546
+ else if (definition.scope === 'references') {
547
+ await this.queryRun(`CREATE INDEX ${MySQLDriver.escape(`${this.prefix}references_${etype}_id_custom_${definition.name}_reference_guid`)} USING btree ON ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`reference\`, \`guid\`);`);
548
+ }
549
+ else if (definition.scope === 'tokens') {
550
+ await this.queryRun(`CREATE INDEX ${MySQLDriver.escape(`${this.prefix}tokens_${etype}_id_custom_${definition.name}_token_guid`)} USING btree ON ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`token\`, \`guid\`);`);
551
+ }
552
+ return true;
553
+ }
554
+ async deleteIndex(etype, scope, name) {
555
+ this.checkIndexName(name);
556
+ try {
557
+ if (scope === 'data') {
558
+ await this.queryRun(`DROP INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${name}_string_guid`)} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`);
559
+ await this.queryRun(`DROP INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${name}_number_guid`)} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`);
560
+ await this.queryRun(`DROP INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${name}_truthy_guid`)} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`);
561
+ await this.queryRun(`DROP INDEX ${MySQLDriver.escape(`${this.prefix}data_${etype}_id_custom_${name}_json_guid`)} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`);
562
+ }
563
+ else if (scope === 'references') {
564
+ await this.queryRun(`DROP INDEX ${MySQLDriver.escape(`${this.prefix}references_${etype}_id_custom_${name}_reference_guid`)} ON ${MySQLDriver.escape(`${this.prefix}references_${etype}`)};`);
565
+ }
566
+ else if (scope === 'tokens') {
567
+ await this.queryRun(`DROP INDEX ${MySQLDriver.escape(`${this.prefix}tokens_${etype}_id_custom_${name}_token_guid`)} ON ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)};`);
568
+ }
569
+ }
570
+ catch (e) {
571
+ if (e?.errorCode !== 1091) {
572
+ throw e;
573
+ }
574
+ }
575
+ return true;
576
+ }
577
+ async getEtypes() {
578
+ const tables = await this.queryArray('SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix;', {
579
+ params: {
580
+ db: this.config.database,
581
+ prefix: this.prefix + 'entities_' + '%',
582
+ },
583
+ });
452
584
  const etypes = [];
453
- for (const tableRow of tables) {
454
- const table = tableRow[Object.keys(tableRow)[0]];
455
- if (table.startsWith(this.prefix + 'entities_')) {
456
- etypes.push(table.substr((this.prefix + 'entities_').length));
585
+ for (const table of tables) {
586
+ etypes.push(table.table_name.substr((this.prefix + 'entities_').length));
587
+ }
588
+ return etypes;
589
+ }
590
+ async *exportDataIterator() {
591
+ if (yield {
592
+ type: 'comment',
593
+ content: `#nex2
594
+ # Nymph Entity Exchange v2
595
+ # http://nymph.io
596
+ #
597
+ # Generation Time: ${new Date().toLocaleString()}
598
+ `,
599
+ }) {
600
+ return;
601
+ }
602
+ if (yield {
603
+ type: 'comment',
604
+ content: `
605
+
606
+ #
607
+ # UIDs
608
+ #
609
+
610
+ `,
611
+ }) {
612
+ return;
613
+ }
614
+ // Export UIDs.
615
+ let uids = await this.queryArray(`SELECT * FROM ${MySQLDriver.escape(`${this.prefix}uids`)} ORDER BY \`name\`;`);
616
+ for (const uid of uids) {
617
+ if (yield { type: 'uid', content: `<${uid.name}>[${uid.cur_uid}]\n` }) {
618
+ return;
457
619
  }
458
620
  }
621
+ if (yield {
622
+ type: 'comment',
623
+ content: `
624
+
625
+ #
626
+ # Entities
627
+ #
628
+
629
+ `,
630
+ }) {
631
+ return;
632
+ }
633
+ // Get the etypes.
634
+ const etypes = await this.getEtypes();
459
635
  for (const etype of etypes) {
460
- const dataIterator = (await this.queryIter(`SELECT LOWER(HEX(e.\`guid\`)) AS \`guid\`, e.\`tags\`, e.\`cdate\`, e.\`mdate\`, d.\`name\` AS \`dname\`, d.\`value\` AS \`dvalue\`, c.\`string\`, c.\`number\`
636
+ // Export entities.
637
+ const entityIterator = this.exportEntityInternal(etype);
638
+ for await (let content of entityIterator) {
639
+ yield { type: 'entity', content };
640
+ }
641
+ }
642
+ }
643
+ async exportEntity(etype, guid) {
644
+ const entityIterator = this.exportEntityInternal(etype, guid);
645
+ let exportContent = '';
646
+ for await (let content of entityIterator) {
647
+ exportContent += content;
648
+ }
649
+ return exportContent;
650
+ }
651
+ async *exportEntityInternal(etype, guid) {
652
+ // Export entities.
653
+ const dataIterator = (await this.queryArray(`SELECT LOWER(HEX(e.\`guid\`)) AS \`guid\`, e.\`tags\`, e.\`cdate\`, e.\`mdate\`, LOWER(HEX(e.\`user\`)) AS \`user\`, LOWER(HEX(e.\`group\`)) AS \`group\`, e.\`acUser\`, e.\`acGroup\`, e.\`acOther\`, e.\`acRead\`, e.\`acWrite\`, e.\`acFull\`, d.\`name\`, d.\`value\`, d.\`json\`, d.\`string\`, d.\`number\`
461
654
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} e
462
- LEFT JOIN ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} d ON e.\`guid\`=d.\`guid\`
463
- INNER JOIN ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} c ON d.\`guid\`=c.\`guid\` AND d.\`name\`=c.\`name\`
464
- ORDER BY e.\`guid\`;`))[Symbol.iterator]();
465
- let datum = dataIterator.next();
466
- while (!datum.done) {
467
- const guid = datum.value.guid;
468
- const tags = datum.value.tags.slice(1, -1).split(' ').join(',');
469
- const cdate = datum.value.cdate;
470
- const mdate = datum.value.mdate;
471
- writeLine(`{${guid}}<${etype}>[${tags}]`);
472
- writeLine(`\tcdate=${JSON.stringify(cdate)}`);
473
- writeLine(`\tmdate=${JSON.stringify(mdate)}`);
474
- if (datum.value.dname != null) {
475
- do {
476
- const value = datum.value.dvalue === 'N'
477
- ? JSON.stringify(datum.value.number)
478
- : datum.value.dvalue === 'S'
479
- ? JSON.stringify(datum.value.string)
480
- : datum.value.dvalue;
481
- writeLine(`\t${datum.value.dname}=${value}`);
482
- datum = dataIterator.next();
483
- } while (!datum.done && datum.value.guid === guid);
655
+ LEFT JOIN ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} d ON e.\`guid\`=d.\`guid\`${guid == null ? '' : ` WHERE e.\`guid\`=UNHEX(@guid)`}
656
+ ORDER BY e.\`guid\`, d.\`name\`;`, guid == null ? undefined : { params: { guid } }))[Symbol.iterator]();
657
+ let datum = dataIterator.next();
658
+ while (!datum.done) {
659
+ const guid = datum.value.guid;
660
+ const tags = MySQLDriver.unescapeTags(datum.value.tags
661
+ .slice(1, -1)
662
+ .split(' ')
663
+ .filter((tag) => tag)).join(',');
664
+ const cdate = datum.value.cdate;
665
+ const mdate = datum.value.mdate;
666
+ const user = datum.value.user;
667
+ const group = datum.value.group;
668
+ const acUser = datum.value.acUser;
669
+ const acGroup = datum.value.acGroup;
670
+ const acOther = datum.value.acOther;
671
+ const acRead = datum.value.acRead?.slice(1, -1).split(' ');
672
+ const acWrite = datum.value.acWrite?.slice(1, -1).split(' ');
673
+ const acFull = datum.value.acFull?.slice(1, -1).split(' ');
674
+ let currentEntityExport = [];
675
+ currentEntityExport.push(`{${guid}}<${etype}>[${tags.replace(/\n/g, () => '\\n')}]`);
676
+ currentEntityExport.push(`\tcdate=${JSON.stringify(cdate)}`);
677
+ currentEntityExport.push(`\tmdate=${JSON.stringify(mdate)}`);
678
+ if (this.nymph.tilmeld != null) {
679
+ if (user != null) {
680
+ currentEntityExport.push(`\tuser=${JSON.stringify(['nymph_entity_reference', user, 'User'])}`);
484
681
  }
485
- else {
486
- datum = dataIterator.next();
682
+ if (group != null) {
683
+ currentEntityExport.push(`\tgroup=${JSON.stringify(['nymph_entity_reference', group, 'Group'])}`);
684
+ }
685
+ if (acUser != null) {
686
+ currentEntityExport.push(`\tacUser=${JSON.stringify(acUser)}`);
687
+ }
688
+ if (acGroup != null) {
689
+ currentEntityExport.push(`\tacGroup=${JSON.stringify(acGroup)}`);
690
+ }
691
+ if (acOther != null) {
692
+ currentEntityExport.push(`\tacOther=${JSON.stringify(acOther)}`);
693
+ }
694
+ if (acRead != null) {
695
+ currentEntityExport.push(`\tacRead=${JSON.stringify(acRead)}`);
487
696
  }
697
+ if (acWrite != null) {
698
+ currentEntityExport.push(`\tacWrite=${JSON.stringify(acWrite)}`);
699
+ }
700
+ if (acFull != null) {
701
+ currentEntityExport.push(`\tacFull=${JSON.stringify(acFull)}`);
702
+ }
703
+ }
704
+ if (datum.value.name != null) {
705
+ // This do will keep going and adding the data until the
706
+ // next entity is reached. $row will end on the next entity.
707
+ do {
708
+ const value = datum.value.value === 'N'
709
+ ? JSON.stringify(datum.value.number)
710
+ : datum.value.value === 'S'
711
+ ? JSON.stringify(datum.value.string)
712
+ : datum.value.value === 'J'
713
+ ? JSON.stringify(datum.value.json)
714
+ : datum.value.value;
715
+ currentEntityExport.push(`\t${datum.value.name.replace(/\n/g, () => '\\n')}=${value}`);
716
+ datum = dataIterator.next();
717
+ } while (!datum.done && datum.value.guid === guid);
718
+ }
719
+ else {
720
+ // Make sure that datum is incremented :)
721
+ datum = dataIterator.next();
722
+ }
723
+ currentEntityExport.push('');
724
+ if (yield currentEntityExport.join('\n')) {
725
+ return;
488
726
  }
489
727
  }
490
- return;
491
728
  }
492
- makeEntityQuery(options, formattedSelectors, etype, count = { i: 0 }, params = {}, subquery = false, tableSuffix = '', etypes = []) {
729
+ /**
730
+ * Generate the MySQL query.
731
+ * @param options The options array.
732
+ * @param formattedSelectors The formatted selector array.
733
+ * @param etype
734
+ * @param count Used to track internal params.
735
+ * @param params Used to store internal params.
736
+ * @param subquery Whether only a subquery should be returned.
737
+ * @returns The SQL query.
738
+ */
739
+ makeEntityQuery(options, formattedSelectors, etype, count = { i: 0 }, params = {}, subquery = false, tableSuffix = '', etypes = [], guidSelector = undefined, guidExplicitSelector = undefined) {
493
740
  if (typeof options.class?.alterOptions === 'function') {
494
741
  options = options.class.alterOptions(options);
495
742
  }
496
743
  const eTable = `e${tableSuffix}`;
497
744
  const dTable = `d${tableSuffix}`;
498
- const cTable = `c${tableSuffix}`;
499
745
  const fTable = `f${tableSuffix}`;
500
746
  const ieTable = `ie${tableSuffix}`;
501
747
  const countTable = `count${tableSuffix}`;
502
- const sort = options.sort ?? 'cdate';
503
- const queryParts = this.iterateSelectorsForQuery(formattedSelectors, (key, value, typeIsOr, typeIsNot) => {
748
+ const sTable = `s${tableSuffix}`;
749
+ const sort = options.sort === undefined ? 'cdate' : options.sort;
750
+ const queryParts = this.iterateSelectorsForQuery(formattedSelectors, ({ key, value, typeIsOr, typeIsNot }) => {
504
751
  const clauseNot = key.startsWith('!');
505
752
  let curQuery = '';
506
753
  for (const curValue of value) {
@@ -513,7 +760,7 @@ class MySQLDriver extends nymph_1.NymphDriver {
513
760
  }
514
761
  const guid = `param${++count.i}`;
515
762
  curQuery +=
516
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
763
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
517
764
  ieTable +
518
765
  '.`guid`=UNHEX(@' +
519
766
  guid +
@@ -523,7 +770,7 @@ class MySQLDriver extends nymph_1.NymphDriver {
523
770
  break;
524
771
  case 'tag':
525
772
  case '!tag':
526
- if ((0, nymph_1.xor)(typeIsNot, clauseNot)) {
773
+ if (xor(typeIsNot, clauseNot)) {
527
774
  if (typeIsOr) {
528
775
  for (const curTag of curValue) {
529
776
  if (curQuery) {
@@ -531,13 +778,14 @@ class MySQLDriver extends nymph_1.NymphDriver {
531
778
  }
532
779
  const tag = `param${++count.i}`;
533
780
  curQuery += ieTable + '.`tags` NOT REGEXP @' + tag;
534
- params[tag] = ' ' + curTag + ' ';
781
+ params[tag] = ' ' + MySQLDriver.escapeTag(curTag) + ' ';
535
782
  }
536
783
  }
537
784
  else {
538
785
  const tag = `param${++count.i}`;
539
786
  curQuery += ieTable + '.`tags` NOT REGEXP @' + tag;
540
- params[tag] = ' (' + curValue.join('|') + ') ';
787
+ params[tag] =
788
+ ' (' + MySQLDriver.escapeTags(curValue).join('|') + ') ';
541
789
  }
542
790
  }
543
791
  else {
@@ -547,7 +795,8 @@ class MySQLDriver extends nymph_1.NymphDriver {
547
795
  const groupQueryParam = `param${++count.i}`;
548
796
  let groupQuery = '';
549
797
  for (const curTag of curValue) {
550
- groupQuery += (typeIsOr ? ' ' : ' +') + curTag;
798
+ groupQuery +=
799
+ (typeIsOr ? ' ' : ' +') + MySQLDriver.escapeTag(curTag);
551
800
  }
552
801
  curQuery +=
553
802
  'MATCH (' +
@@ -564,17 +813,38 @@ class MySQLDriver extends nymph_1.NymphDriver {
564
813
  if (curQuery) {
565
814
  curQuery += typeIsOr ? ' OR ' : ' AND ';
566
815
  }
567
- const name = `param${++count.i}`;
568
- curQuery +=
569
- ieTable +
570
- '.`guid` ' +
571
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
572
- 'IN (SELECT `guid` FROM ' +
573
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
574
- ' WHERE `name`=@' +
575
- name +
576
- ')';
577
- params[name] = curVar;
816
+ if (curVar === 'cdate' ||
817
+ curVar === 'mdate' ||
818
+ (this.nymph.tilmeld != null &&
819
+ (curVar === 'user' ||
820
+ curVar === 'group' ||
821
+ curVar === 'acUser' ||
822
+ curVar === 'acGroup' ||
823
+ curVar === 'acOther' ||
824
+ curVar === 'acRead' ||
825
+ curVar === 'acWrite' ||
826
+ curVar === 'acFull'))) {
827
+ curQuery +=
828
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
829
+ '(' +
830
+ ieTable +
831
+ '.' +
832
+ MySQLDriver.escape(curVar) +
833
+ ' IS NOT NULL)';
834
+ }
835
+ else {
836
+ const name = `param${++count.i}`;
837
+ curQuery +=
838
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
839
+ 'EXISTS (SELECT `guid` FROM ' +
840
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
841
+ ' WHERE `guid`=' +
842
+ ieTable +
843
+ '.`guid` AND `name`=@' +
844
+ name +
845
+ ')';
846
+ params[name] = curVar;
847
+ }
578
848
  }
579
849
  break;
580
850
  case 'truthy':
@@ -583,30 +853,34 @@ class MySQLDriver extends nymph_1.NymphDriver {
583
853
  if (curQuery) {
584
854
  curQuery += typeIsOr ? ' OR ' : ' AND ';
585
855
  }
586
- if (curVar === 'cdate') {
587
- curQuery +=
588
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
589
- '(' +
590
- ieTable +
591
- '.`cdate` NOT NULL)';
592
- break;
593
- }
594
- else if (curVar === 'mdate') {
856
+ if (curVar === 'cdate' ||
857
+ curVar === 'mdate' ||
858
+ (this.nymph.tilmeld != null &&
859
+ (curVar === 'user' ||
860
+ curVar === 'group' ||
861
+ curVar === 'acUser' ||
862
+ curVar === 'acGroup' ||
863
+ curVar === 'acOther' ||
864
+ curVar === 'acRead' ||
865
+ curVar === 'acWrite' ||
866
+ curVar === 'acFull'))) {
595
867
  curQuery +=
596
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
868
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
597
869
  '(' +
598
870
  ieTable +
599
- '.`mdate` NOT NULL)';
600
- break;
871
+ '.' +
872
+ MySQLDriver.escape(curVar) +
873
+ ' IS NOT NULL)';
601
874
  }
602
875
  else {
603
876
  const name = `param${++count.i}`;
604
877
  curQuery +=
605
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
878
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
879
+ 'EXISTS (SELECT `guid` FROM ' +
880
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
881
+ ' WHERE `guid`=' +
606
882
  ieTable +
607
- '.`guid` IN (SELECT `guid` FROM ' +
608
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
609
- ' WHERE `name`=@' +
883
+ '.`guid` AND `name`=@' +
610
884
  name +
611
885
  ' AND `truthy`=TRUE)';
612
886
  params[name] = curVar;
@@ -615,35 +889,61 @@ class MySQLDriver extends nymph_1.NymphDriver {
615
889
  break;
616
890
  case 'equal':
617
891
  case '!equal':
618
- if (curValue[0] === 'cdate') {
892
+ if (curValue[0] === 'cdate' ||
893
+ curValue[0] === 'mdate' ||
894
+ (this.nymph.tilmeld != null &&
895
+ (curValue[0] === 'acUser' ||
896
+ curValue[0] === 'acGroup' ||
897
+ curValue[0] === 'acOther'))) {
619
898
  if (curQuery) {
620
899
  curQuery += typeIsOr ? ' OR ' : ' AND ';
621
900
  }
622
- const cdate = `param${++count.i}`;
901
+ const value = `param${++count.i}`;
623
902
  curQuery +=
624
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
903
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
625
904
  ieTable +
626
- '.`cdate`=@' +
627
- cdate;
628
- params[cdate] = isNaN(Number(curValue[1]))
905
+ '.' +
906
+ MySQLDriver.escape(curValue[0]) +
907
+ '=@' +
908
+ value;
909
+ params[value] = isNaN(Number(curValue[1]))
629
910
  ? null
630
911
  : Number(curValue[1]);
631
- break;
632
912
  }
633
- else if (curValue[0] === 'mdate') {
913
+ else if (this.nymph.tilmeld != null &&
914
+ (curValue[0] === 'user' || curValue[0] === 'group')) {
634
915
  if (curQuery) {
635
916
  curQuery += typeIsOr ? ' OR ' : ' AND ';
636
917
  }
637
- const mdate = `param${++count.i}`;
918
+ const value = `param${++count.i}`;
638
919
  curQuery +=
639
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
920
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
640
921
  ieTable +
641
- '.`mdate`=@' +
642
- mdate;
643
- params[mdate] = isNaN(Number(curValue[1]))
644
- ? null
645
- : Number(curValue[1]);
646
- break;
922
+ '.' +
923
+ MySQLDriver.escape(curValue[0]) +
924
+ '=UNHEX(@' +
925
+ value +
926
+ ')';
927
+ params[value] = `${curValue[1]}`;
928
+ }
929
+ else if (this.nymph.tilmeld != null &&
930
+ (curValue[0] === 'acRead' ||
931
+ curValue[0] === 'acWrite' ||
932
+ curValue[0] === 'acFull')) {
933
+ if (curQuery) {
934
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
935
+ }
936
+ const value = `param${++count.i}`;
937
+ curQuery +=
938
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
939
+ ieTable +
940
+ '.' +
941
+ MySQLDriver.escape(curValue[0]) +
942
+ '=@' +
943
+ value;
944
+ params[value] = Array.isArray(curValue[1])
945
+ ? ' ' + MySQLDriver.escapeTags(curValue[1]).join(' ') + ' '
946
+ : '';
647
947
  }
648
948
  else if (typeof curValue[1] === 'number') {
649
949
  if (curQuery) {
@@ -652,11 +952,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
652
952
  const name = `param${++count.i}`;
653
953
  const value = `param${++count.i}`;
654
954
  curQuery +=
655
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
955
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
956
+ 'EXISTS (SELECT `guid` FROM ' +
957
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
958
+ ' WHERE `guid`=' +
656
959
  ieTable +
657
- '.`guid` IN (SELECT `guid` FROM ' +
658
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
659
- ' WHERE `name`=@' +
960
+ '.`guid` AND `name`=@' +
660
961
  name +
661
962
  ' AND `number`=@' +
662
963
  value +
@@ -671,11 +972,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
671
972
  const name = `param${++count.i}`;
672
973
  const value = `param${++count.i}`;
673
974
  curQuery +=
674
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
975
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
976
+ 'EXISTS (SELECT `guid` FROM ' +
977
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
978
+ ' WHERE `guid`=' +
675
979
  ieTable +
676
- '.`guid` IN (SELECT `guid` FROM ' +
677
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
678
- ' WHERE `name`=@' +
980
+ '.`guid` AND `name`=@' +
679
981
  name +
680
982
  ' AND `string`=@' +
681
983
  value +
@@ -697,139 +999,284 @@ class MySQLDriver extends nymph_1.NymphDriver {
697
999
  }
698
1000
  const name = `param${++count.i}`;
699
1001
  const value = `param${++count.i}`;
700
- curQuery +=
701
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
702
- ieTable +
703
- '.`guid` IN (SELECT `guid` FROM ' +
704
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
705
- ' WHERE `name`=@' +
706
- name +
707
- ' AND `value`=@' +
708
- value +
709
- ')';
1002
+ if (svalue.length < 500) {
1003
+ curQuery +=
1004
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1005
+ 'EXISTS (SELECT `guid` FROM ' +
1006
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1007
+ ' WHERE `guid`=' +
1008
+ ieTable +
1009
+ '.`guid` AND `name`=@' +
1010
+ name +
1011
+ ' AND (CAST(`json` AS CHAR(500)) COLLATE utf8mb4_bin)=CAST(CAST(@' +
1012
+ value +
1013
+ ' AS JSON) AS CHAR(500)))';
1014
+ }
1015
+ else {
1016
+ curQuery +=
1017
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1018
+ 'EXISTS (SELECT `guid` FROM ' +
1019
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1020
+ ' WHERE `guid`=' +
1021
+ ieTable +
1022
+ '.`guid` AND `name`=@' +
1023
+ name +
1024
+ ' AND `json`=CAST(@' +
1025
+ value +
1026
+ ' AS JSON))';
1027
+ }
710
1028
  params[name] = curValue[0];
711
1029
  params[value] = svalue;
712
1030
  }
713
1031
  break;
714
1032
  case 'contain':
715
1033
  case '!contain':
716
- if (curValue[0] === 'cdate') {
1034
+ if (curValue[0] === 'cdate' ||
1035
+ curValue[0] === 'mdate' ||
1036
+ (this.nymph.tilmeld != null &&
1037
+ (curValue[0] === 'acUser' ||
1038
+ curValue[0] === 'acGroup' ||
1039
+ curValue[0] === 'acOther'))) {
717
1040
  if (curQuery) {
718
1041
  curQuery += typeIsOr ? ' OR ' : ' AND ';
719
1042
  }
720
- const cdate = `param${++count.i}`;
1043
+ const value = `param${++count.i}`;
721
1044
  curQuery +=
722
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1045
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
723
1046
  ieTable +
724
- '.`cdate`=' +
725
- cdate;
726
- params[cdate] = isNaN(Number(curValue[1]))
1047
+ '.' +
1048
+ MySQLDriver.escape(curValue[0]) +
1049
+ '=@' +
1050
+ value;
1051
+ params[value] = isNaN(Number(curValue[1]))
727
1052
  ? null
728
1053
  : Number(curValue[1]);
729
- break;
730
1054
  }
731
- else if (curValue[0] === 'mdate') {
1055
+ else if (this.nymph.tilmeld != null &&
1056
+ (curValue[0] === 'user' || curValue[0] === 'group')) {
732
1057
  if (curQuery) {
733
1058
  curQuery += typeIsOr ? ' OR ' : ' AND ';
734
1059
  }
735
- const mdate = `param${++count.i}`;
1060
+ const value = `param${++count.i}`;
736
1061
  curQuery +=
737
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1062
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
738
1063
  ieTable +
739
- '.`mdate`=' +
740
- mdate;
741
- params[mdate] = isNaN(Number(curValue[1]))
742
- ? null
743
- : Number(curValue[1]);
744
- break;
1064
+ '.' +
1065
+ MySQLDriver.escape(curValue[0]) +
1066
+ '=UNHEX(@' +
1067
+ value +
1068
+ ')';
1069
+ params[value] = `${curValue[1]}`;
1070
+ }
1071
+ else if (this.nymph.tilmeld != null &&
1072
+ (curValue[0] === 'acRead' ||
1073
+ curValue[0] === 'acWrite' ||
1074
+ curValue[0] === 'acFull')) {
1075
+ if (curQuery) {
1076
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1077
+ }
1078
+ const queryParam = `param${++count.i}`;
1079
+ curQuery +=
1080
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1081
+ 'MATCH (' +
1082
+ ieTable +
1083
+ '.' +
1084
+ MySQLDriver.escape(curValue[0]) +
1085
+ ') AGAINST (@' +
1086
+ queryParam +
1087
+ ' IN BOOLEAN MODE)';
1088
+ params[queryParam] = '+' + curValue[1];
745
1089
  }
746
1090
  else {
747
1091
  if (curQuery) {
748
1092
  curQuery += typeIsOr ? ' OR ' : ' AND ';
749
1093
  }
750
1094
  let svalue;
751
- let stringValue;
752
1095
  if (curValue[1] instanceof Object &&
753
1096
  typeof curValue[1].toReference === 'function') {
754
1097
  svalue = JSON.stringify(curValue[1].toReference());
755
- stringValue = `${curValue[1].toReference()}`;
756
1098
  }
757
1099
  else {
758
1100
  svalue = JSON.stringify(curValue[1]);
759
- stringValue = `${curValue[1]}`;
760
1101
  }
761
1102
  const name = `param${++count.i}`;
762
1103
  const value = `param${++count.i}`;
763
- if (typeof curValue[1] === 'string') {
764
- const stringParam = `param${++count.i}`;
1104
+ curQuery +=
1105
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1106
+ 'EXISTS (SELECT `guid` FROM ' +
1107
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1108
+ ' WHERE `guid`=' +
1109
+ ieTable +
1110
+ '.`guid` AND `name`=@' +
1111
+ name +
1112
+ ' AND JSON_CONTAINS(`json`, @' +
1113
+ value +
1114
+ '))';
1115
+ params[name] = curValue[0];
1116
+ params[value] = svalue;
1117
+ }
1118
+ break;
1119
+ case 'search':
1120
+ case '!search':
1121
+ if (curValue[0] === 'cdate' ||
1122
+ curValue[0] === 'mdate' ||
1123
+ (this.nymph.tilmeld != null &&
1124
+ (curValue[0] === 'user' ||
1125
+ curValue[0] === 'group' ||
1126
+ curValue[0] === 'acUser' ||
1127
+ curValue[0] === 'acGroup' ||
1128
+ curValue[0] === 'acOther' ||
1129
+ curValue[0] === 'acRead' ||
1130
+ curValue[0] === 'acWrite' ||
1131
+ curValue[0] === 'acFull'))) {
1132
+ if (curQuery) {
1133
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1134
+ }
1135
+ curQuery +=
1136
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') + '(FALSE)';
1137
+ }
1138
+ else {
1139
+ if (curQuery) {
1140
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1141
+ }
1142
+ const parsedFTSQuery = this.tokenizer.parseSearchQuery(curValue[1]);
1143
+ if (!parsedFTSQuery.length) {
765
1144
  curQuery +=
766
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
767
- '(' +
1145
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') + '(FALSE)';
1146
+ }
1147
+ else {
1148
+ const name = `param${++count.i}`;
1149
+ const queryPartToken = (term) => {
1150
+ const value = `param${++count.i}`;
1151
+ params[value] = term.token;
1152
+ return ('EXISTS (SELECT `guid` FROM ' +
1153
+ MySQLDriver.escape(this.prefix + 'tokens_' + etype) +
1154
+ ' WHERE `guid`=' +
768
1155
  ieTable +
769
- '.`guid` IN (SELECT `guid` FROM ' +
770
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
771
- ' WHERE `name`=@' +
1156
+ '.`guid` AND `name`=@' +
772
1157
  name +
773
- ' AND INSTR(`value`, @' +
1158
+ ' AND `token`=@' +
774
1159
  value +
775
- ')) OR ' +
1160
+ (term.nostemmed ? ' AND `stem`=FALSE' : '') +
1161
+ ')');
1162
+ };
1163
+ const queryPartSeries = (series) => {
1164
+ const tokenTableSuffix = makeTableSuffix();
1165
+ const tokenParts = series.tokens.map((token, i) => {
1166
+ const value = `param${++count.i}`;
1167
+ params[value] = token.token;
1168
+ return {
1169
+ fromClause: i === 0
1170
+ ? 'FROM ' +
1171
+ MySQLDriver.escape(this.prefix + 'tokens_' + etype) +
1172
+ ' t' +
1173
+ tokenTableSuffix +
1174
+ '0'
1175
+ : 'JOIN ' +
1176
+ MySQLDriver.escape(this.prefix + 'tokens_' + etype) +
1177
+ ' t' +
1178
+ tokenTableSuffix +
1179
+ i +
1180
+ ' ON t' +
1181
+ tokenTableSuffix +
1182
+ i +
1183
+ '.`guid` = t' +
1184
+ tokenTableSuffix +
1185
+ '0.`guid` AND t' +
1186
+ tokenTableSuffix +
1187
+ i +
1188
+ '.`name` = t' +
1189
+ tokenTableSuffix +
1190
+ '0.`name` AND t' +
1191
+ tokenTableSuffix +
1192
+ i +
1193
+ '.`position` = t' +
1194
+ tokenTableSuffix +
1195
+ '0.`position` + ' +
1196
+ i,
1197
+ whereClause: 't' +
1198
+ tokenTableSuffix +
1199
+ i +
1200
+ '.`token`=@' +
1201
+ value +
1202
+ (token.nostemmed
1203
+ ? ' AND t' + tokenTableSuffix + i + '.`stem`=FALSE'
1204
+ : ''),
1205
+ };
1206
+ });
1207
+ return ('EXISTS (SELECT t' +
1208
+ tokenTableSuffix +
1209
+ '0.`guid` ' +
1210
+ tokenParts.map((part) => part.fromClause).join(' ') +
1211
+ ' WHERE t' +
1212
+ tokenTableSuffix +
1213
+ '0.`guid`=' +
776
1214
  ieTable +
777
- '.`guid` IN (SELECT `guid` FROM ' +
778
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
779
- ' WHERE `name`=@' +
1215
+ '.`guid` AND t' +
1216
+ tokenTableSuffix +
1217
+ '0.`name`=@' +
780
1218
  name +
781
- ' AND `string`=@' +
782
- stringParam +
783
- '))';
784
- params[stringParam] = stringValue;
785
- }
786
- else {
1219
+ ' AND ' +
1220
+ tokenParts.map((part) => part.whereClause).join(' AND ') +
1221
+ ')');
1222
+ };
1223
+ const queryPartTerm = (term) => {
1224
+ if (term.type === 'series') {
1225
+ return queryPartSeries(term);
1226
+ }
1227
+ else if (term.type === 'not') {
1228
+ return 'NOT ' + queryPartTerm(term.operand);
1229
+ }
1230
+ else if (term.type === 'or') {
1231
+ let queryParts = [];
1232
+ for (let operand of term.operands) {
1233
+ queryParts.push(queryPartTerm(operand));
1234
+ }
1235
+ return '(' + queryParts.join(' OR ') + ')';
1236
+ }
1237
+ return queryPartToken(term);
1238
+ };
1239
+ // Run through the query and add terms.
1240
+ let termStrings = [];
1241
+ for (let term of parsedFTSQuery) {
1242
+ termStrings.push(queryPartTerm(term));
1243
+ }
787
1244
  curQuery +=
788
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
789
- ieTable +
790
- '.`guid` IN (SELECT `guid` FROM ' +
791
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
792
- ' WHERE `name`=@' +
793
- name +
794
- ' AND INSTR(`value`, @' +
795
- value +
796
- '))';
1245
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1246
+ '(' +
1247
+ termStrings.join(' AND ') +
1248
+ ')';
1249
+ params[name] = curValue[0];
797
1250
  }
798
- params[name] = curValue[0];
799
- params[value] = svalue;
800
1251
  }
801
1252
  break;
802
1253
  case 'match':
803
1254
  case '!match':
804
- if (curValue[0] === 'cdate') {
805
- if (curQuery) {
806
- curQuery += typeIsOr ? ' OR ' : ' AND ';
807
- }
808
- const cdate = `param${++count.i}`;
809
- curQuery +=
810
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
811
- '(' +
812
- ieTable +
813
- '.`cdate` REGEXP @' +
814
- cdate +
815
- ')';
816
- params[cdate] = curValue[1];
817
- break;
818
- }
819
- else if (curValue[0] === 'mdate') {
1255
+ if (curValue[0] === 'cdate' ||
1256
+ curValue[0] === 'mdate' ||
1257
+ (this.nymph.tilmeld != null &&
1258
+ (curValue[0] === 'user' ||
1259
+ curValue[0] === 'group' ||
1260
+ curValue[0] === 'acUser' ||
1261
+ curValue[0] === 'acGroup' ||
1262
+ curValue[0] === 'acOther' ||
1263
+ curValue[0] === 'acRead' ||
1264
+ curValue[0] === 'acWrite' ||
1265
+ curValue[0] === 'acFull'))) {
820
1266
  if (curQuery) {
821
1267
  curQuery += typeIsOr ? ' OR ' : ' AND ';
822
1268
  }
823
- const mdate = `param${++count.i}`;
1269
+ const value = `param${++count.i}`;
824
1270
  curQuery +=
825
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1271
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
826
1272
  '(' +
827
1273
  ieTable +
828
- '.`mdate` REGEXP @' +
829
- mdate +
1274
+ '.' +
1275
+ MySQLDriver.escape(curValue[0]) +
1276
+ ' REGEXP @' +
1277
+ value +
830
1278
  ')';
831
- params[mdate] = curValue[1];
832
- break;
1279
+ params[value] = curValue[1];
833
1280
  }
834
1281
  else {
835
1282
  if (curQuery) {
@@ -838,11 +1285,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
838
1285
  const name = `param${++count.i}`;
839
1286
  const value = `param${++count.i}`;
840
1287
  curQuery +=
841
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1288
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1289
+ 'EXISTS (SELECT `guid` FROM ' +
1290
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1291
+ ' WHERE `guid`=' +
842
1292
  ieTable +
843
- '.`guid` IN (SELECT `guid` FROM ' +
844
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
845
- ' WHERE `name`=@' +
1293
+ '.`guid` AND `name`=@' +
846
1294
  name +
847
1295
  ' AND `string` REGEXP @' +
848
1296
  value +
@@ -853,35 +1301,31 @@ class MySQLDriver extends nymph_1.NymphDriver {
853
1301
  break;
854
1302
  case 'imatch':
855
1303
  case '!imatch':
856
- if (curValue[0] === 'cdate') {
857
- if (curQuery) {
858
- curQuery += typeIsOr ? ' OR ' : ' AND ';
859
- }
860
- const cdate = `param${++count.i}`;
861
- curQuery +=
862
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
863
- '(' +
864
- ieTable +
865
- '.`cdate` REGEXP @' +
866
- cdate +
867
- ')';
868
- params[cdate] = curValue[1];
869
- break;
870
- }
871
- else if (curValue[0] === 'mdate') {
1304
+ if (curValue[0] === 'cdate' ||
1305
+ curValue[0] === 'mdate' ||
1306
+ (this.nymph.tilmeld != null &&
1307
+ (curValue[0] === 'user' ||
1308
+ curValue[0] === 'group' ||
1309
+ curValue[0] === 'acUser' ||
1310
+ curValue[0] === 'acGroup' ||
1311
+ curValue[0] === 'acOther' ||
1312
+ curValue[0] === 'acRead' ||
1313
+ curValue[0] === 'acWrite' ||
1314
+ curValue[0] === 'acFull'))) {
872
1315
  if (curQuery) {
873
1316
  curQuery += typeIsOr ? ' OR ' : ' AND ';
874
1317
  }
875
- const mdate = `param${++count.i}`;
1318
+ const value = `param${++count.i}`;
876
1319
  curQuery +=
877
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1320
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
878
1321
  '(' +
879
1322
  ieTable +
880
- '.`mdate` REGEXP @' +
881
- mdate +
1323
+ '.' +
1324
+ MySQLDriver.escape(curValue[0]) +
1325
+ ' REGEXP @' +
1326
+ value +
882
1327
  ')';
883
- params[mdate] = curValue[1];
884
- break;
1328
+ params[value] = curValue[1];
885
1329
  }
886
1330
  else {
887
1331
  if (curQuery) {
@@ -890,11 +1334,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
890
1334
  const name = `param${++count.i}`;
891
1335
  const value = `param${++count.i}`;
892
1336
  curQuery +=
893
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1337
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1338
+ 'EXISTS (SELECT `guid` FROM ' +
1339
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1340
+ ' WHERE `guid`=' +
894
1341
  ieTable +
895
- '.`guid` IN (SELECT `guid` FROM ' +
896
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
897
- ' WHERE `name`=@' +
1342
+ '.`guid` AND `name`=@' +
898
1343
  name +
899
1344
  ' AND LOWER(`string`) REGEXP LOWER(@' +
900
1345
  value +
@@ -905,35 +1350,31 @@ class MySQLDriver extends nymph_1.NymphDriver {
905
1350
  break;
906
1351
  case 'like':
907
1352
  case '!like':
908
- if (curValue[0] === 'cdate') {
909
- if (curQuery) {
910
- curQuery += typeIsOr ? ' OR ' : ' AND ';
911
- }
912
- const cdate = `param${++count.i}`;
913
- curQuery +=
914
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
915
- '(' +
916
- ieTable +
917
- '.`cdate` LIKE @' +
918
- cdate +
919
- ')';
920
- params[cdate] = curValue[1];
921
- break;
922
- }
923
- else if (curValue[0] === 'mdate') {
1353
+ if (curValue[0] === 'cdate' ||
1354
+ curValue[0] === 'mdate' ||
1355
+ (this.nymph.tilmeld != null &&
1356
+ (curValue[0] === 'user' ||
1357
+ curValue[0] === 'group' ||
1358
+ curValue[0] === 'acUser' ||
1359
+ curValue[0] === 'acGroup' ||
1360
+ curValue[0] === 'acOther' ||
1361
+ curValue[0] === 'acRead' ||
1362
+ curValue[0] === 'acWrite' ||
1363
+ curValue[0] === 'acFull'))) {
924
1364
  if (curQuery) {
925
1365
  curQuery += typeIsOr ? ' OR ' : ' AND ';
926
1366
  }
927
- const mdate = `param${++count.i}`;
1367
+ const value = `param${++count.i}`;
928
1368
  curQuery +=
929
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1369
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
930
1370
  '(' +
931
1371
  ieTable +
932
- '.`mdate` LIKE @' +
933
- mdate +
1372
+ '.' +
1373
+ MySQLDriver.escape(curValue[0]) +
1374
+ ' LIKE @' +
1375
+ value +
934
1376
  ')';
935
- params[mdate] = curValue[1];
936
- break;
1377
+ params[value] = curValue[1];
937
1378
  }
938
1379
  else {
939
1380
  if (curQuery) {
@@ -942,11 +1383,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
942
1383
  const name = `param${++count.i}`;
943
1384
  const value = `param${++count.i}`;
944
1385
  curQuery +=
945
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1386
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1387
+ 'EXISTS (SELECT `guid` FROM ' +
1388
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1389
+ ' WHERE `guid`=' +
946
1390
  ieTable +
947
- '.`guid` IN (SELECT `guid` FROM ' +
948
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
949
- ' WHERE `name`=@' +
1391
+ '.`guid` AND `name`=@' +
950
1392
  name +
951
1393
  ' AND `string` LIKE @' +
952
1394
  value +
@@ -957,35 +1399,31 @@ class MySQLDriver extends nymph_1.NymphDriver {
957
1399
  break;
958
1400
  case 'ilike':
959
1401
  case '!ilike':
960
- if (curValue[0] === 'cdate') {
961
- if (curQuery) {
962
- curQuery += typeIsOr ? ' OR ' : ' AND ';
963
- }
964
- const cdate = `param${++count.i}`;
965
- curQuery +=
966
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
967
- '(' +
968
- ieTable +
969
- '.`cdate` LIKE @' +
970
- cdate +
971
- ')';
972
- params[cdate] = curValue[1];
973
- break;
974
- }
975
- else if (curValue[0] === 'mdate') {
1402
+ if (curValue[0] === 'cdate' ||
1403
+ curValue[0] === 'mdate' ||
1404
+ (this.nymph.tilmeld != null &&
1405
+ (curValue[0] === 'user' ||
1406
+ curValue[0] === 'group' ||
1407
+ curValue[0] === 'acUser' ||
1408
+ curValue[0] === 'acGroup' ||
1409
+ curValue[0] === 'acOther' ||
1410
+ curValue[0] === 'acRead' ||
1411
+ curValue[0] === 'acWrite' ||
1412
+ curValue[0] === 'acFull'))) {
976
1413
  if (curQuery) {
977
1414
  curQuery += typeIsOr ? ' OR ' : ' AND ';
978
1415
  }
979
- const mdate = `param${++count.i}`;
1416
+ const value = `param${++count.i}`;
980
1417
  curQuery +=
981
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1418
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
982
1419
  '(' +
983
1420
  ieTable +
984
- '.`mdate` LIKE @' +
985
- mdate +
1421
+ '.' +
1422
+ MySQLDriver.escape(curValue[0]) +
1423
+ ' LIKE @' +
1424
+ value +
986
1425
  ')';
987
- params[mdate] = curValue[1];
988
- break;
1426
+ params[value] = curValue[1];
989
1427
  }
990
1428
  else {
991
1429
  if (curQuery) {
@@ -994,11 +1432,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
994
1432
  const name = `param${++count.i}`;
995
1433
  const value = `param${++count.i}`;
996
1434
  curQuery +=
997
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1435
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1436
+ 'EXISTS (SELECT `guid` FROM ' +
1437
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1438
+ ' WHERE `guid`=' +
998
1439
  ieTable +
999
- '.`guid` IN (SELECT `guid` FROM ' +
1000
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1001
- ' WHERE `name`=@' +
1440
+ '.`guid` AND `name`=@' +
1002
1441
  name +
1003
1442
  ' AND LOWER(`string`) LIKE LOWER(@' +
1004
1443
  value +
@@ -1009,35 +1448,31 @@ class MySQLDriver extends nymph_1.NymphDriver {
1009
1448
  break;
1010
1449
  case 'gt':
1011
1450
  case '!gt':
1012
- if (curValue[0] === 'cdate') {
1013
- if (curQuery) {
1014
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1015
- }
1016
- const cdate = `param${++count.i}`;
1017
- curQuery +=
1018
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1019
- ieTable +
1020
- '.`cdate`>@' +
1021
- cdate;
1022
- params[cdate] = isNaN(Number(curValue[1]))
1023
- ? null
1024
- : Number(curValue[1]);
1025
- break;
1026
- }
1027
- else if (curValue[0] === 'mdate') {
1451
+ if (curValue[0] === 'cdate' ||
1452
+ curValue[0] === 'mdate' ||
1453
+ (this.nymph.tilmeld != null &&
1454
+ (curValue[0] === 'user' ||
1455
+ curValue[0] === 'group' ||
1456
+ curValue[0] === 'acUser' ||
1457
+ curValue[0] === 'acGroup' ||
1458
+ curValue[0] === 'acOther' ||
1459
+ curValue[0] === 'acRead' ||
1460
+ curValue[0] === 'acWrite' ||
1461
+ curValue[0] === 'acFull'))) {
1028
1462
  if (curQuery) {
1029
1463
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1030
1464
  }
1031
- const mdate = `param${++count.i}`;
1465
+ const value = `param${++count.i}`;
1032
1466
  curQuery +=
1033
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1467
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1034
1468
  ieTable +
1035
- '.`mdate`>@' +
1036
- mdate;
1037
- params[mdate] = isNaN(Number(curValue[1]))
1469
+ '.' +
1470
+ MySQLDriver.escape(curValue[0]) +
1471
+ '>@' +
1472
+ value;
1473
+ params[value] = isNaN(Number(curValue[1]))
1038
1474
  ? null
1039
1475
  : Number(curValue[1]);
1040
- break;
1041
1476
  }
1042
1477
  else {
1043
1478
  if (curQuery) {
@@ -1046,11 +1481,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
1046
1481
  const name = `param${++count.i}`;
1047
1482
  const value = `param${++count.i}`;
1048
1483
  curQuery +=
1049
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1484
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1485
+ 'EXISTS (SELECT `guid` FROM ' +
1486
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1487
+ ' WHERE `guid`=' +
1050
1488
  ieTable +
1051
- '.`guid` IN (SELECT `guid` FROM ' +
1052
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1053
- ' WHERE `name`=@' +
1489
+ '.`guid` AND `name`=@' +
1054
1490
  name +
1055
1491
  ' AND `number`>@' +
1056
1492
  value +
@@ -1063,35 +1499,31 @@ class MySQLDriver extends nymph_1.NymphDriver {
1063
1499
  break;
1064
1500
  case 'gte':
1065
1501
  case '!gte':
1066
- if (curValue[0] === 'cdate') {
1067
- if (curQuery) {
1068
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1069
- }
1070
- const cdate = `param${++count.i}`;
1071
- curQuery +=
1072
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1073
- ieTable +
1074
- '.`cdate`>=@' +
1075
- cdate;
1076
- params[cdate] = isNaN(Number(curValue[1]))
1077
- ? null
1078
- : Number(curValue[1]);
1079
- break;
1080
- }
1081
- else if (curValue[0] === 'mdate') {
1502
+ if (curValue[0] === 'cdate' ||
1503
+ curValue[0] === 'mdate' ||
1504
+ (this.nymph.tilmeld != null &&
1505
+ (curValue[0] === 'user' ||
1506
+ curValue[0] === 'group' ||
1507
+ curValue[0] === 'acUser' ||
1508
+ curValue[0] === 'acGroup' ||
1509
+ curValue[0] === 'acOther' ||
1510
+ curValue[0] === 'acRead' ||
1511
+ curValue[0] === 'acWrite' ||
1512
+ curValue[0] === 'acFull'))) {
1082
1513
  if (curQuery) {
1083
1514
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1084
1515
  }
1085
- const mdate = `param${++count.i}`;
1516
+ const value = `param${++count.i}`;
1086
1517
  curQuery +=
1087
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1518
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1088
1519
  ieTable +
1089
- '.`mdate`>=@' +
1090
- mdate;
1091
- params[mdate] = isNaN(Number(curValue[1]))
1520
+ '.' +
1521
+ MySQLDriver.escape(curValue[0]) +
1522
+ '>=@' +
1523
+ value;
1524
+ params[value] = isNaN(Number(curValue[1]))
1092
1525
  ? null
1093
1526
  : Number(curValue[1]);
1094
- break;
1095
1527
  }
1096
1528
  else {
1097
1529
  if (curQuery) {
@@ -1100,11 +1532,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
1100
1532
  const name = `param${++count.i}`;
1101
1533
  const value = `param${++count.i}`;
1102
1534
  curQuery +=
1103
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1535
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1536
+ 'EXISTS (SELECT `guid` FROM ' +
1537
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1538
+ ' WHERE `guid`=' +
1104
1539
  ieTable +
1105
- '.`guid` IN (SELECT `guid` FROM ' +
1106
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1107
- ' WHERE `name`=@' +
1540
+ '.`guid` AND `name`=@' +
1108
1541
  name +
1109
1542
  ' AND `number`>=@' +
1110
1543
  value +
@@ -1117,35 +1550,31 @@ class MySQLDriver extends nymph_1.NymphDriver {
1117
1550
  break;
1118
1551
  case 'lt':
1119
1552
  case '!lt':
1120
- if (curValue[0] === 'cdate') {
1553
+ if (curValue[0] === 'cdate' ||
1554
+ curValue[0] === 'mdate' ||
1555
+ (this.nymph.tilmeld != null &&
1556
+ (curValue[0] === 'user' ||
1557
+ curValue[0] === 'group' ||
1558
+ curValue[0] === 'acUser' ||
1559
+ curValue[0] === 'acGroup' ||
1560
+ curValue[0] === 'acOther' ||
1561
+ curValue[0] === 'acRead' ||
1562
+ curValue[0] === 'acWrite' ||
1563
+ curValue[0] === 'acFull'))) {
1121
1564
  if (curQuery) {
1122
1565
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1123
1566
  }
1124
- const cdate = `param${++count.i}`;
1125
- curQuery +=
1126
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1127
- ieTable +
1128
- '.`cdate`<@' +
1129
- cdate;
1130
- params[cdate] = isNaN(Number(curValue[1]))
1131
- ? null
1132
- : Number(curValue[1]);
1133
- break;
1134
- }
1135
- else if (curValue[0] === 'mdate') {
1136
- if (curQuery) {
1137
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1138
- }
1139
- const mdate = `param${++count.i}`;
1567
+ const value = `param${++count.i}`;
1140
1568
  curQuery +=
1141
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1569
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1142
1570
  ieTable +
1143
- '.`mdate`<@' +
1144
- mdate;
1145
- params[mdate] = isNaN(Number(curValue[1]))
1571
+ '.' +
1572
+ MySQLDriver.escape(curValue[0]) +
1573
+ '<@' +
1574
+ value;
1575
+ params[value] = isNaN(Number(curValue[1]))
1146
1576
  ? null
1147
1577
  : Number(curValue[1]);
1148
- break;
1149
1578
  }
1150
1579
  else {
1151
1580
  if (curQuery) {
@@ -1154,52 +1583,49 @@ class MySQLDriver extends nymph_1.NymphDriver {
1154
1583
  const name = `param${++count.i}`;
1155
1584
  const value = `param${++count.i}`;
1156
1585
  curQuery +=
1157
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1586
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1587
+ 'EXISTS (SELECT `guid` FROM ' +
1588
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1589
+ ' WHERE `guid`=' +
1158
1590
  ieTable +
1159
- '.`guid` IN (SELECT `guid` FROM ' +
1160
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1161
- ' WHERE `name`=@' +
1591
+ '.`guid` AND `name`=@' +
1162
1592
  name +
1163
1593
  ' AND `number`<@' +
1164
1594
  value +
1165
1595
  ')';
1166
1596
  params[name] = curValue[0];
1167
- params[value] = isNaN(Number(curValue[1]))
1168
- ? null
1169
- : Number(curValue[1]);
1170
- }
1171
- break;
1172
- case 'lte':
1173
- case '!lte':
1174
- if (curValue[0] === 'cdate') {
1175
- if (curQuery) {
1176
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1177
- }
1178
- const cdate = `param${++count.i}`;
1179
- curQuery +=
1180
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1181
- ieTable +
1182
- '.`cdate`<=@' +
1183
- cdate;
1184
- params[cdate] = isNaN(Number(curValue[1]))
1597
+ params[value] = isNaN(Number(curValue[1]))
1185
1598
  ? null
1186
1599
  : Number(curValue[1]);
1187
- break;
1188
1600
  }
1189
- else if (curValue[0] === 'mdate') {
1601
+ break;
1602
+ case 'lte':
1603
+ case '!lte':
1604
+ if (curValue[0] === 'cdate' ||
1605
+ curValue[0] === 'mdate' ||
1606
+ (this.nymph.tilmeld != null &&
1607
+ (curValue[0] === 'user' ||
1608
+ curValue[0] === 'group' ||
1609
+ curValue[0] === 'acUser' ||
1610
+ curValue[0] === 'acGroup' ||
1611
+ curValue[0] === 'acOther' ||
1612
+ curValue[0] === 'acRead' ||
1613
+ curValue[0] === 'acWrite' ||
1614
+ curValue[0] === 'acFull'))) {
1190
1615
  if (curQuery) {
1191
1616
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1192
1617
  }
1193
- const mdate = `param${++count.i}`;
1618
+ const value = `param${++count.i}`;
1194
1619
  curQuery +=
1195
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1620
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1196
1621
  ieTable +
1197
- '.`mdate`<=@' +
1198
- mdate;
1199
- params[mdate] = isNaN(Number(curValue[1]))
1622
+ '.' +
1623
+ MySQLDriver.escape(curValue[0]) +
1624
+ '<=@' +
1625
+ value;
1626
+ params[value] = isNaN(Number(curValue[1]))
1200
1627
  ? null
1201
1628
  : Number(curValue[1]);
1202
- break;
1203
1629
  }
1204
1630
  else {
1205
1631
  if (curQuery) {
@@ -1208,11 +1634,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
1208
1634
  const name = `param${++count.i}`;
1209
1635
  const value = `param${++count.i}`;
1210
1636
  curQuery +=
1211
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1637
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1638
+ 'EXISTS (SELECT `guid` FROM ' +
1639
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1640
+ ' WHERE `guid`=' +
1212
1641
  ieTable +
1213
- '.`guid` IN (SELECT `guid` FROM ' +
1214
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1215
- ' WHERE `name`=@' +
1642
+ '.`guid` AND `name`=@' +
1216
1643
  name +
1217
1644
  ' AND `number`<=@' +
1218
1645
  value +
@@ -1238,71 +1665,190 @@ class MySQLDriver extends nymph_1.NymphDriver {
1238
1665
  if (curQuery) {
1239
1666
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1240
1667
  }
1241
- const name = `param${++count.i}`;
1242
- const guid = `param${++count.i}`;
1243
- curQuery +=
1244
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1245
- ieTable +
1246
- '.`guid` IN (SELECT `guid` FROM ' +
1247
- MySQLDriver.escape(this.prefix + 'references_' + etype) +
1248
- ' WHERE `name`=@' +
1249
- name +
1250
- ' AND `reference`=UNHEX(@' +
1251
- guid +
1252
- '))';
1253
- params[name] = curValue[0];
1254
- params[guid] = curQguid;
1668
+ if (this.nymph.tilmeld != null &&
1669
+ (curValue[0] === 'user' || curValue[0] === 'group')) {
1670
+ const guid = `param${++count.i}`;
1671
+ curQuery +=
1672
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1673
+ ieTable +
1674
+ '.' +
1675
+ MySQLDriver.escape(curValue[0]) +
1676
+ '=UNHEX(@' +
1677
+ guid +
1678
+ ')';
1679
+ params[guid] = curQguid;
1680
+ }
1681
+ else if (this.nymph.tilmeld != null &&
1682
+ (curValue[0] === 'acRead' ||
1683
+ curValue[0] === 'acWrite' ||
1684
+ curValue[0] === 'acFull')) {
1685
+ const queryParam = `param${++count.i}`;
1686
+ curQuery +=
1687
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1688
+ 'MATCH (' +
1689
+ ieTable +
1690
+ '.' +
1691
+ MySQLDriver.escape(curValue[0]) +
1692
+ ') AGAINST (@' +
1693
+ queryParam +
1694
+ ' IN BOOLEAN MODE)';
1695
+ params[queryParam] = '+' + curQguid;
1696
+ }
1697
+ else {
1698
+ const name = `param${++count.i}`;
1699
+ const guid = `param${++count.i}`;
1700
+ curQuery +=
1701
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1702
+ 'EXISTS (SELECT `guid` FROM ' +
1703
+ MySQLDriver.escape(this.prefix + 'references_' + etype) +
1704
+ ' WHERE `guid`=' +
1705
+ ieTable +
1706
+ '.`guid` AND `name`=@' +
1707
+ name +
1708
+ ' AND `reference`=UNHEX(@' +
1709
+ guid +
1710
+ '))';
1711
+ params[name] = curValue[0];
1712
+ params[guid] = curQguid;
1713
+ }
1255
1714
  break;
1256
1715
  case 'selector':
1257
1716
  case '!selector':
1258
- const subquery = this.makeEntityQuery(options, [curValue], etype, count, params, true, tableSuffix, etypes);
1717
+ const innerquery = this.makeEntityQuery({ ...options, sort: null, limit: undefined }, [curValue], etype, count, params, true, tableSuffix, etypes);
1259
1718
  if (curQuery) {
1260
1719
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1261
1720
  }
1262
1721
  curQuery +=
1263
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1722
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1264
1723
  '(' +
1265
- subquery.query +
1724
+ innerquery.query +
1266
1725
  ')';
1267
1726
  break;
1268
1727
  case 'qref':
1269
1728
  case '!qref':
1729
+ const referenceTableSuffix = makeTableSuffix();
1270
1730
  const [qrefOptions, ...qrefSelectors] = curValue[1];
1271
1731
  const QrefEntityClass = qrefOptions.class;
1272
1732
  etypes.push(QrefEntityClass.ETYPE);
1273
- const qrefQuery = this.makeEntityQuery({ ...qrefOptions, return: 'guid', class: QrefEntityClass }, qrefSelectors, QrefEntityClass.ETYPE, count, params, false, (0, guid_1.makeTableSuffix)(), etypes);
1274
1733
  if (curQuery) {
1275
1734
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1276
1735
  }
1277
- const qrefName = `param${++count.i}`;
1278
- curQuery +=
1279
- ((0, nymph_1.xor)(typeIsNot, clauseNot) ? 'NOT ' : '') +
1280
- ieTable +
1281
- '.`guid` IN (SELECT `guid` FROM ' +
1282
- MySQLDriver.escape(this.prefix + 'references_' + etype) +
1283
- ' WHERE `name`=@' +
1284
- qrefName +
1285
- ' AND `reference` IN (' +
1286
- qrefQuery.query +
1287
- '))';
1288
- params[qrefName] = curValue[0];
1736
+ if (this.nymph.tilmeld != null &&
1737
+ (curValue[0] === 'user' || curValue[0] === 'group')) {
1738
+ const qrefQuery = this.makeEntityQuery({
1739
+ ...qrefOptions,
1740
+ sort: qrefOptions.sort ?? null,
1741
+ return: 'guid',
1742
+ class: QrefEntityClass,
1743
+ }, qrefSelectors, QrefEntityClass.ETYPE, count, params, false, makeTableSuffix(), etypes, 'r' +
1744
+ referenceTableSuffix +
1745
+ '.' +
1746
+ MySQLDriver.escape(curValue[0]));
1747
+ curQuery +=
1748
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1749
+ 'EXISTS (SELECT `guid` FROM ' +
1750
+ MySQLDriver.escape(this.prefix + 'entities_' + etype) +
1751
+ ' r' +
1752
+ referenceTableSuffix +
1753
+ ' WHERE r' +
1754
+ referenceTableSuffix +
1755
+ '.`guid`=' +
1756
+ ieTable +
1757
+ '.`guid` AND EXISTS (' +
1758
+ qrefQuery.query +
1759
+ '))';
1760
+ }
1761
+ else if (this.nymph.tilmeld != null &&
1762
+ (curValue[0] === 'acRead' ||
1763
+ curValue[0] === 'acWrite' ||
1764
+ curValue[0] === 'acFull')) {
1765
+ const qrefQuery = this.makeEntityQuery({
1766
+ ...qrefOptions,
1767
+ sort: qrefOptions.sort ?? null,
1768
+ return: 'guid',
1769
+ class: QrefEntityClass,
1770
+ }, qrefSelectors, QrefEntityClass.ETYPE, count, params, false, makeTableSuffix(), etypes, undefined, (guid) => ieTable +
1771
+ '.' +
1772
+ MySQLDriver.escape(curValue[0]) +
1773
+ " LIKE CONCAT('% ', LOWER(HEX(" +
1774
+ guid +
1775
+ ")), ' %')");
1776
+ curQuery +=
1777
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1778
+ 'EXISTS (' +
1779
+ qrefQuery.query +
1780
+ ')';
1781
+ }
1782
+ else {
1783
+ const qrefQuery = this.makeEntityQuery({
1784
+ ...qrefOptions,
1785
+ sort: qrefOptions.sort ?? null,
1786
+ return: 'guid',
1787
+ class: QrefEntityClass,
1788
+ }, qrefSelectors, QrefEntityClass.ETYPE, count, params, false, makeTableSuffix(), etypes, 'r' + referenceTableSuffix + '.`reference`');
1789
+ const qrefName = `param${++count.i}`;
1790
+ curQuery +=
1791
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1792
+ 'EXISTS (SELECT `guid` FROM ' +
1793
+ MySQLDriver.escape(this.prefix + 'references_' + etype) +
1794
+ ' r' +
1795
+ referenceTableSuffix +
1796
+ ' WHERE r' +
1797
+ referenceTableSuffix +
1798
+ '.`guid`=' +
1799
+ ieTable +
1800
+ '.`guid` AND r' +
1801
+ referenceTableSuffix +
1802
+ '.`name`=@' +
1803
+ qrefName +
1804
+ ' AND EXISTS (' +
1805
+ qrefQuery.query +
1806
+ '))';
1807
+ params[qrefName] = curValue[0];
1808
+ }
1289
1809
  break;
1290
1810
  }
1291
1811
  }
1292
1812
  return curQuery;
1293
1813
  });
1294
1814
  let sortBy;
1295
- switch (sort) {
1296
- case 'mdate':
1297
- sortBy = '`mdate`';
1298
- break;
1299
- case 'cdate':
1300
- default:
1301
- sortBy = '`cdate`';
1302
- break;
1303
- }
1304
- if (options.reverse) {
1305
- sortBy += ' DESC';
1815
+ let sortByInner;
1816
+ let sortJoin = '';
1817
+ let sortJoinInner = '';
1818
+ const order = options.reverse ? ' DESC' : '';
1819
+ if (sort == null) {
1820
+ sortBy = '';
1821
+ sortByInner = '';
1822
+ }
1823
+ else {
1824
+ switch (sort) {
1825
+ case 'mdate':
1826
+ sortBy = `ORDER BY ${eTable}.\`mdate\`${order}`;
1827
+ sortByInner = `ORDER BY ${ieTable}.\`mdate\`${order}`;
1828
+ break;
1829
+ case 'cdate':
1830
+ sortBy = `ORDER BY ${eTable}.\`cdate\`${order}`;
1831
+ sortByInner = `ORDER BY ${ieTable}.\`cdate\`${order}`;
1832
+ break;
1833
+ default:
1834
+ const name = `param${++count.i}`;
1835
+ sortJoin = `LEFT JOIN (
1836
+ SELECT \`guid\`, \`string\`, \`number\`
1837
+ FROM ${MySQLDriver.escape(this.prefix + 'data_' + etype)}
1838
+ WHERE \`name\`=@${name}
1839
+ ORDER BY \`number\`${order}, \`string\`${order}
1840
+ ) ${sTable} ON ${eTable}.\`guid\`=${sTable}.\`guid\``;
1841
+ sortJoinInner = `LEFT JOIN (
1842
+ SELECT \`guid\`, \`string\`, \`number\`
1843
+ FROM ${MySQLDriver.escape(this.prefix + 'data_' + etype)}
1844
+ WHERE \`name\`=@${name}
1845
+ ORDER BY \`number\`${order}, \`string\`${order}
1846
+ ) ${sTable} ON ${ieTable}.\`guid\`=${sTable}.\`guid\``;
1847
+ sortBy = `ORDER BY ${sTable}.\`number\`${order}, ${sTable}.\`string\`${order}`;
1848
+ sortByInner = sortBy;
1849
+ params[name] = sort;
1850
+ break;
1851
+ }
1306
1852
  }
1307
1853
  let query;
1308
1854
  if (queryParts.length) {
@@ -1319,18 +1865,23 @@ class MySQLDriver extends nymph_1.NymphDriver {
1319
1865
  offset = ` OFFSET ${Math.floor(isNaN(Number(options.offset)) ? 0 : Number(options.offset))}`;
1320
1866
  }
1321
1867
  const whereClause = queryParts.join(') AND (');
1868
+ const guidClause = guidExplicitSelector
1869
+ ? `${guidExplicitSelector(`${ieTable}.\`guid\``)} AND `
1870
+ : guidSelector
1871
+ ? `${ieTable}.\`guid\`=${guidSelector} AND `
1872
+ : '';
1322
1873
  if (options.return === 'count') {
1323
1874
  if (limit || offset) {
1324
1875
  query = `SELECT COUNT(${countTable}.\`guid\`) AS \`count\` FROM (
1325
1876
  SELECT ${ieTable}.\`guid\` AS \`guid\`
1326
1877
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}
1327
- WHERE (${whereClause})${limit}${offset}
1878
+ WHERE ${guidClause}(${whereClause})${limit}${offset}
1328
1879
  ) ${countTable}`;
1329
1880
  }
1330
1881
  else {
1331
1882
  query = `SELECT COUNT(${ieTable}.\`guid\`) AS \`count\`
1332
1883
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}
1333
- WHERE (${whereClause})`;
1884
+ WHERE ${guidClause}(${whereClause})`;
1334
1885
  }
1335
1886
  }
1336
1887
  else if (options.return === 'guid') {
@@ -1339,8 +1890,9 @@ class MySQLDriver extends nymph_1.NymphDriver {
1339
1890
  : `${ieTable}.\`guid\``;
1340
1891
  query = `SELECT ${guidColumn} AS \`guid\`
1341
1892
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}
1342
- WHERE (${whereClause})
1343
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}`;
1893
+ ${sortJoinInner}
1894
+ WHERE ${guidClause}(${whereClause})
1895
+ ${sortByInner ? sortByInner + ', ' : 'ORDER BY '}${ieTable}.\`guid\`${limit}${offset}`;
1344
1896
  }
1345
1897
  else {
1346
1898
  query = `SELECT
@@ -1348,20 +1900,30 @@ class MySQLDriver extends nymph_1.NymphDriver {
1348
1900
  ${eTable}.\`tags\`,
1349
1901
  ${eTable}.\`cdate\`,
1350
1902
  ${eTable}.\`mdate\`,
1903
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
1904
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
1905
+ ${eTable}.\`acUser\`,
1906
+ ${eTable}.\`acGroup\`,
1907
+ ${eTable}.\`acOther\`,
1908
+ ${eTable}.\`acRead\`,
1909
+ ${eTable}.\`acWrite\`,
1910
+ ${eTable}.\`acFull\`,
1351
1911
  ${dTable}.\`name\`,
1352
1912
  ${dTable}.\`value\`,
1353
- ${cTable}.\`string\`,
1354
- ${cTable}.\`number\`
1913
+ ${dTable}.\`json\`,
1914
+ ${dTable}.\`string\`,
1915
+ ${dTable}.\`number\`
1355
1916
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${eTable}
1356
1917
  LEFT JOIN ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1357
- INNER JOIN ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1918
+ ${sortJoin}
1358
1919
  INNER JOIN (
1359
1920
  SELECT ${ieTable}.\`guid\`
1360
1921
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}
1361
- WHERE (${whereClause})
1362
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}
1922
+ ${sortJoinInner}
1923
+ WHERE ${guidClause}(${whereClause})
1924
+ ${sortByInner}${limit}${offset}
1363
1925
  ) ${fTable} ON ${eTable}.\`guid\`=${fTable}.\`guid\`
1364
- ORDER BY ${eTable}.${sortBy}`;
1926
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1365
1927
  }
1366
1928
  }
1367
1929
  }
@@ -1378,16 +1940,21 @@ class MySQLDriver extends nymph_1.NymphDriver {
1378
1940
  if ('offset' in options) {
1379
1941
  offset = ` OFFSET ${Math.floor(isNaN(Number(options.offset)) ? 0 : Number(options.offset))}`;
1380
1942
  }
1943
+ const guidClause = guidExplicitSelector
1944
+ ? ` WHERE ${guidExplicitSelector(`${ieTable}.\`guid\``)}`
1945
+ : guidSelector
1946
+ ? ` WHERE ${ieTable}.\`guid\`=${guidSelector}`
1947
+ : '';
1381
1948
  if (options.return === 'count') {
1382
1949
  if (limit || offset) {
1383
1950
  query = `SELECT COUNT(${countTable}.\`guid\`) AS \`count\` FROM (
1384
1951
  SELECT ${ieTable}.\`guid\` AS \`guid\`
1385
- FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}${limit}${offset}
1952
+ FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}${guidClause}${limit}${offset}
1386
1953
  ) ${countTable}`;
1387
1954
  }
1388
1955
  else {
1389
1956
  query = `SELECT COUNT(${ieTable}.\`guid\`) AS \`count\`
1390
- FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}`;
1957
+ FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}${guidClause}`;
1391
1958
  }
1392
1959
  }
1393
1960
  else if (options.return === 'guid') {
@@ -1396,7 +1963,9 @@ class MySQLDriver extends nymph_1.NymphDriver {
1396
1963
  : `${ieTable}.\`guid\``;
1397
1964
  query = `SELECT ${guidColumn} AS \`guid\`
1398
1965
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}
1399
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}`;
1966
+ ${sortJoinInner}
1967
+ ${guidClause}
1968
+ ${sortByInner ? sortByInner + ', ' : 'ORDER BY '}${ieTable}.\`guid\`${limit}${offset}`;
1400
1969
  }
1401
1970
  else {
1402
1971
  if (limit || offset) {
@@ -1405,19 +1974,30 @@ class MySQLDriver extends nymph_1.NymphDriver {
1405
1974
  ${eTable}.\`tags\`,
1406
1975
  ${eTable}.\`cdate\`,
1407
1976
  ${eTable}.\`mdate\`,
1977
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
1978
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
1979
+ ${eTable}.\`acUser\`,
1980
+ ${eTable}.\`acGroup\`,
1981
+ ${eTable}.\`acOther\`,
1982
+ ${eTable}.\`acRead\`,
1983
+ ${eTable}.\`acWrite\`,
1984
+ ${eTable}.\`acFull\`,
1408
1985
  ${dTable}.\`name\`,
1409
1986
  ${dTable}.\`value\`,
1410
- ${cTable}.\`string\`,
1411
- ${cTable}.\`number\`
1987
+ ${dTable}.\`json\`,
1988
+ ${dTable}.\`string\`,
1989
+ ${dTable}.\`number\`
1412
1990
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${eTable}
1413
1991
  LEFT JOIN ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1414
- INNER JOIN ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1992
+ ${sortJoin}
1415
1993
  INNER JOIN (
1416
1994
  SELECT ${ieTable}.\`guid\`
1417
1995
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${ieTable}
1418
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}
1996
+ ${sortJoinInner}
1997
+ ${guidClause}
1998
+ ${sortByInner}${limit}${offset}
1419
1999
  ) ${fTable} ON ${eTable}.\`guid\`=${fTable}.\`guid\`
1420
- ORDER BY ${eTable}.${sortBy}`;
2000
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1421
2001
  }
1422
2002
  else {
1423
2003
  query = `SELECT
@@ -1425,14 +2005,24 @@ class MySQLDriver extends nymph_1.NymphDriver {
1425
2005
  ${eTable}.\`tags\`,
1426
2006
  ${eTable}.\`cdate\`,
1427
2007
  ${eTable}.\`mdate\`,
2008
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2009
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2010
+ ${eTable}.\`acUser\`,
2011
+ ${eTable}.\`acGroup\`,
2012
+ ${eTable}.\`acOther\`,
2013
+ ${eTable}.\`acRead\`,
2014
+ ${eTable}.\`acWrite\`,
2015
+ ${eTable}.\`acFull\`,
1428
2016
  ${dTable}.\`name\`,
1429
2017
  ${dTable}.\`value\`,
1430
- ${cTable}.\`string\`,
1431
- ${cTable}.\`number\`
2018
+ ${dTable}.\`json\`,
2019
+ ${dTable}.\`string\`,
2020
+ ${dTable}.\`number\`
1432
2021
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} ${eTable}
1433
2022
  LEFT JOIN ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1434
- INNER JOIN ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1435
- ORDER BY ${eTable}.${sortBy}`;
2023
+ ${sortJoin}
2024
+ ${guidExplicitSelector ? `WHERE ${guidExplicitSelector(`${eTable}.\`guid\``)}` : guidSelector ? `WHERE ${eTable}.\`guid\`=${guidSelector}` : ''}
2025
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1436
2026
  }
1437
2027
  }
1438
2028
  }
@@ -1448,33 +2038,43 @@ class MySQLDriver extends nymph_1.NymphDriver {
1448
2038
  }
1449
2039
  performQuery(options, formattedSelectors, etype) {
1450
2040
  const { query, params, etypes } = this.makeEntityQuery(options, formattedSelectors, etype);
1451
- const result = this.queryIter(query, { etypes, params }).then((val) => val[Symbol.iterator]());
1452
- return {
1453
- result,
1454
- };
1455
- }
1456
- performQuerySync(options, formattedSelectors, etype) {
1457
- const { query, params, etypes } = this.makeEntityQuery(options, formattedSelectors, etype);
1458
- const result = (this.queryIterSync(query, { etypes, params }) || [])[Symbol.iterator]();
2041
+ const result = this.queryArray(query, { etypes, params }).then((val) => val[Symbol.iterator]());
1459
2042
  return {
1460
2043
  result,
1461
2044
  };
1462
2045
  }
1463
2046
  async getEntities(options = {}, ...selectors) {
1464
- const { result: resultPromise, process } = this.getEntitesRowLike(options, selectors, (options, formattedSelectors, etype) => this.performQuery(options, formattedSelectors, etype), () => {
2047
+ const { result: resultPromise, process } = this.getEntitiesRowLike(
2048
+ // @ts-ignore: options is correct here.
2049
+ options, selectors, ({ options, selectors, etype }) => this.performQuery(options, selectors, etype), () => {
1465
2050
  const next = result.next();
1466
2051
  return next.done ? null : next.value;
1467
2052
  }, () => undefined, (row) => Number(row.count), (row) => row.guid, (row) => ({
1468
- tags: row.tags.length > 2 ? row.tags.slice(1, -1).split(' ') : [],
1469
- cdate: isNaN(Number(row.cdate)) ? null : Number(row.cdate),
1470
- mdate: isNaN(Number(row.mdate)) ? null : Number(row.mdate),
2053
+ tags: row.tags.length > 2
2054
+ ? MySQLDriver.unescapeTags(row.tags
2055
+ .slice(1, -1)
2056
+ .split(' ')
2057
+ .filter((tag) => tag))
2058
+ : [],
2059
+ cdate: isNaN(Number(row.cdate)) ? Date.now() : Number(row.cdate),
2060
+ mdate: isNaN(Number(row.mdate)) ? Date.now() : Number(row.mdate),
2061
+ user: row.user,
2062
+ group: row.group,
2063
+ acUser: row.acUser,
2064
+ acGroup: row.acGroup,
2065
+ acOther: row.acOther,
2066
+ acRead: row.acRead?.slice(1, -1).split(' ') ?? [],
2067
+ acWrite: row.acWrite?.slice(1, -1).split(' ') ?? [],
2068
+ acFull: row.acFull?.slice(1, -1).split(' ') ?? [],
1471
2069
  }), (row) => ({
1472
2070
  name: row.name,
1473
2071
  svalue: row.value === 'N'
1474
2072
  ? JSON.stringify(row.number)
1475
2073
  : row.value === 'S'
1476
2074
  ? JSON.stringify(row.string)
1477
- : row.value,
2075
+ : row.value === 'J'
2076
+ ? JSON.stringify(row.json)
2077
+ : row.value,
1478
2078
  }));
1479
2079
  const result = await resultPromise;
1480
2080
  const value = process();
@@ -1483,31 +2083,12 @@ class MySQLDriver extends nymph_1.NymphDriver {
1483
2083
  }
1484
2084
  return value;
1485
2085
  }
1486
- getEntitiesSync(options = {}, ...selectors) {
1487
- const { result, process } = this.getEntitesRowLike(options, selectors, (options, formattedSelectors, etype) => this.performQuerySync(options, formattedSelectors, etype), () => {
1488
- const next = result.next();
1489
- return next.done ? null : next.value;
1490
- }, () => undefined, (row) => Number(row.count), (row) => row.guid, (row) => ({
1491
- tags: row.tags.length > 2 ? row.tags.slice(1, -1).split(',') : [],
1492
- cdate: isNaN(Number(row.cdate)) ? null : Number(row.cdate),
1493
- mdate: isNaN(Number(row.mdate)) ? null : Number(row.mdate),
1494
- }), (row) => ({
1495
- name: row.name,
1496
- svalue: row.value === 'N'
1497
- ? JSON.stringify(row.number)
1498
- : row.value === 'S'
1499
- ? JSON.stringify(row.string)
1500
- : row.value,
1501
- }));
1502
- const value = process();
1503
- if (value instanceof Error) {
1504
- throw value;
1505
- }
1506
- return value;
1507
- }
1508
2086
  async getUID(name) {
1509
2087
  if (name == null) {
1510
- throw new nymph_1.InvalidParametersError('Name not given for UID.');
2088
+ throw new InvalidParametersError('Name not given for UID.');
2089
+ }
2090
+ if (name.length > 128) {
2091
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
1511
2092
  }
1512
2093
  const result = await this.queryGet(`SELECT \`cur_uid\` FROM ${MySQLDriver.escape(`${this.prefix}uids`)} WHERE \`name\`=@name;`, {
1513
2094
  params: {
@@ -1516,45 +2097,81 @@ class MySQLDriver extends nymph_1.NymphDriver {
1516
2097
  });
1517
2098
  return result?.cur_uid ?? null;
1518
2099
  }
1519
- async import(filename) {
2100
+ async importEntity(entity) {
2101
+ return await this.importEntityInternal(entity);
2102
+ }
2103
+ async importEntityTokens(entity) {
2104
+ return await this.importEntityInternal(entity, { only: 'tokens' });
2105
+ }
2106
+ async importEntityTilmeldAC(entity) {
2107
+ return await this.importEntityInternal(entity, { only: 'tilmeldAC' });
2108
+ }
2109
+ async importEntityInternal({ guid, cdate, mdate, tags, sdata, etype, }, { only = undefined } = {}) {
1520
2110
  try {
1521
- const result = await this.importFromFile(filename, async (guid, tags, sdata, etype) => {
1522
- await this.queryRun(`REPLACE INTO ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`) VALUES (UNHEX(@guid), @tags, @cdate, @mdate);`, {
2111
+ let promises = [];
2112
+ if (only == null) {
2113
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
1523
2114
  etypes: [etype],
1524
2115
  params: {
1525
2116
  guid,
1526
- tags: ' ' + tags.join(' ') + ' ',
1527
- cdate: isNaN(Number(JSON.parse(sdata.cdate)))
1528
- ? null
1529
- : Number(JSON.parse(sdata.cdate)),
1530
- mdate: isNaN(Number(JSON.parse(sdata.mdate)))
1531
- ? null
1532
- : Number(JSON.parse(sdata.mdate)),
1533
2117
  },
1534
- });
1535
- const promises = [];
2118
+ }));
1536
2119
  promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
1537
2120
  etypes: [etype],
1538
2121
  params: {
1539
2122
  guid,
1540
2123
  },
1541
2124
  }));
1542
- promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
2125
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
1543
2126
  etypes: [etype],
1544
2127
  params: {
1545
2128
  guid,
1546
2129
  },
1547
2130
  }));
1548
- promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
2131
+ }
2132
+ if (only == null || only === 'tokens') {
2133
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
1549
2134
  etypes: [etype],
1550
2135
  params: {
1551
2136
  guid,
1552
2137
  },
1553
2138
  }));
1554
- await Promise.all(promises);
1555
- delete sdata.cdate;
1556
- delete sdata.mdate;
2139
+ }
2140
+ if (only == null) {
2141
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
2142
+ etypes: [etype],
2143
+ params: {
2144
+ guid,
2145
+ },
2146
+ }));
2147
+ }
2148
+ await Promise.all(promises);
2149
+ promises = [];
2150
+ if (only == null) {
2151
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull } = this.removeAndReturnACValues(etype, {}, sdata);
2152
+ await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`, \`user\`, \`group\`, \`acUser\`, \`acGroup\`, \`acOther\`, \`acRead\`, \`acWrite\`, \`acFull\`) VALUES (UNHEX(@guid), @tags, @cdate, @mdate, ${user == null ? '@user' : 'UNHEX(@user)'}, ${group == null ? '@group' : 'UNHEX(@group)'}, @acUser, @acGroup, @acOther, @acRead, @acWrite, @acFull);`, {
2153
+ etypes: [etype],
2154
+ params: {
2155
+ guid,
2156
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2157
+ cdate: isNaN(cdate) ? null : cdate,
2158
+ mdate: isNaN(mdate) ? null : mdate,
2159
+ user,
2160
+ group,
2161
+ acUser,
2162
+ acGroup,
2163
+ acOther,
2164
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2165
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2166
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2167
+ },
2168
+ });
1557
2169
  for (const name in sdata) {
2170
+ if (typeof name !== 'string' ||
2171
+ !name.length ||
2172
+ name.match(/^\s|=|\s$/)) {
2173
+ throw new EntityInvalidDataError('Property names must be non-empty strings without leading or trailing spaces or equals signs.');
2174
+ }
1558
2175
  const value = sdata[name];
1559
2176
  const uvalue = JSON.parse(value);
1560
2177
  if (value === undefined) {
@@ -1564,24 +2181,18 @@ class MySQLDriver extends nymph_1.NymphDriver {
1564
2181
  ? 'N'
1565
2182
  : typeof uvalue === 'string'
1566
2183
  ? 'S'
1567
- : value;
1568
- const promises = [];
1569
- promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (\`guid\`, \`name\`, \`value\`) VALUES (UNHEX(@guid), @name, @storageValue);`, {
2184
+ : 'J';
2185
+ const jsonValue = storageValue === 'J' ? value : null;
2186
+ promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (\`guid\`, \`name\`, \`value\`, \`json\`, \`string\`, \`number\`, \`truthy\`) VALUES (UNHEX(@guid), @name, @storageValue, @jsonValue, @string, @number, @truthy);`, {
1570
2187
  etypes: [etype],
1571
2188
  params: {
1572
2189
  guid,
1573
2190
  name,
1574
2191
  storageValue,
1575
- },
1576
- }));
1577
- promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} (\`guid\`, \`name\`, \`truthy\`, \`string\`, \`number\`) VALUES (UNHEX(@guid), @name, @truthy, @string, @number);`, {
1578
- etypes: [etype],
1579
- params: {
1580
- guid,
1581
- name,
1582
- truthy: !!uvalue,
1583
- string: `${uvalue}`,
2192
+ jsonValue,
2193
+ string: storageValue === 'J' ? null : `${uvalue}`,
1584
2194
  number: isNaN(Number(uvalue)) ? null : Number(uvalue),
2195
+ truthy: !!uvalue,
1585
2196
  },
1586
2197
  }));
1587
2198
  const references = this.findReferences(value);
@@ -1596,37 +2207,129 @@ class MySQLDriver extends nymph_1.NymphDriver {
1596
2207
  }));
1597
2208
  }
1598
2209
  }
1599
- await Promise.all(promises);
1600
- }, async (name, curUid) => {
1601
- await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}uids`)} (\`name\`, \`cur_uid\`) VALUES (@name, @curUid) ON DUPLICATE KEY UPDATE \`cur_uid\`=@curUid;`, {
2210
+ }
2211
+ if (only === 'tilmeldAC') {
2212
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull } = this.removeAndReturnACValues(etype, {}, sdata);
2213
+ promises.push(this.queryRun(`UPDATE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} SET \`user\`=${user == null ? '@user' : 'UNHEX(@user)'}, \`group\`=${group == null ? '@group' : 'UNHEX(@group)'}, \`acUser\`=@acUser, \`acGroup\`=@acGroup, \`acOther\`=@acOther, \`acRead\`=@acRead, \`acWrite\`=@acWrite, \`acFull\`=@acFull WHERE \`guid\`=UNHEX(@guid);`, {
2214
+ etypes: [etype],
1602
2215
  params: {
1603
- name,
1604
- curUid,
2216
+ user,
2217
+ group,
2218
+ acUser,
2219
+ acGroup,
2220
+ acOther,
2221
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2222
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2223
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2224
+ guid,
1605
2225
  },
2226
+ }));
2227
+ }
2228
+ const EntityClass = this.nymph.getEntityClassByEtype(etype);
2229
+ if (only == null || only === 'tokens') {
2230
+ for (let name in sdata) {
2231
+ let tokenString = null;
2232
+ try {
2233
+ tokenString = EntityClass.getFTSText(name, JSON.parse(sdata[name]));
2234
+ }
2235
+ catch (e) {
2236
+ // Ignore error.
2237
+ }
2238
+ if (tokenString != null) {
2239
+ const tokens = this.tokenizer.tokenize(tokenString);
2240
+ while (tokens.length) {
2241
+ const currentTokens = tokens.splice(0, 100);
2242
+ const params = {
2243
+ guid,
2244
+ name,
2245
+ };
2246
+ const values = [];
2247
+ for (let i = 0; i < currentTokens.length; i++) {
2248
+ const token = currentTokens[i];
2249
+ params['token' + i] = token.token;
2250
+ params['position' + i] = token.position;
2251
+ params['stem' + i] = token.stem;
2252
+ values.push('(UNHEX(@guid), @name, @token' +
2253
+ i +
2254
+ ', @position' +
2255
+ i +
2256
+ ', @stem' +
2257
+ i +
2258
+ ')');
2259
+ }
2260
+ promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} (\`guid\`, \`name\`, \`token\`, \`position\`, \`stem\`) VALUES ${values.join(', ')};`, {
2261
+ etypes: [etype],
2262
+ params,
2263
+ }));
2264
+ }
2265
+ }
2266
+ }
2267
+ }
2268
+ if (only == null) {
2269
+ const uniques = await EntityClass.getUniques({
2270
+ guid,
2271
+ cdate,
2272
+ mdate,
2273
+ tags,
2274
+ data: {},
2275
+ sdata,
1606
2276
  });
1607
- }, async () => {
1608
- await this.internalTransaction('nymph-import');
1609
- }, async () => {
1610
- await this.commit('nymph-import');
2277
+ for (const unique of uniques) {
2278
+ promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} (\`guid\`, \`unique\`) VALUES (UNHEX(@guid), @unique);`, {
2279
+ etypes: [etype],
2280
+ params: {
2281
+ guid,
2282
+ unique,
2283
+ },
2284
+ }).catch((e) => {
2285
+ if (e instanceof EntityUniqueConstraintError) {
2286
+ this.nymph.config.debugError('mysql', `Import entity unique constraint violation for GUID "${guid}" on etype "${etype}": "${unique}"`);
2287
+ }
2288
+ return e;
2289
+ }));
2290
+ }
2291
+ }
2292
+ await Promise.all(promises);
2293
+ }
2294
+ catch (e) {
2295
+ this.nymph.config.debugError('mysql', `Import entity error: "${e}"`);
2296
+ throw e;
2297
+ }
2298
+ }
2299
+ async importUID({ name, value }) {
2300
+ if (name.length > 128) {
2301
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
2302
+ }
2303
+ try {
2304
+ await this.internalTransaction(`nymph-import-uid-${name}`);
2305
+ await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}uids`)} (\`name\`, \`cur_uid\`) VALUES (@name, @value) ON DUPLICATE KEY UPDATE \`cur_uid\`=@value;`, {
2306
+ params: {
2307
+ name,
2308
+ value,
2309
+ },
1611
2310
  });
1612
- return result;
2311
+ await this.commit(`nymph-import-uid-${name}`);
1613
2312
  }
1614
2313
  catch (e) {
1615
- await this.rollback('nymph-import');
1616
- return false;
2314
+ this.nymph.config.debugError('mysql', `Import UID error: "${e}"`);
2315
+ await this.rollback(`nymph-import-uid-${name}`);
2316
+ throw e;
1617
2317
  }
1618
2318
  }
1619
2319
  async newUID(name) {
1620
2320
  if (name == null) {
1621
- throw new nymph_1.InvalidParametersError('Name not given for UID.');
2321
+ throw new InvalidParametersError('Name not given for UID.');
2322
+ }
2323
+ if (name.length > 128) {
2324
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
1622
2325
  }
1623
2326
  await this.internalTransaction('nymph-newuid');
2327
+ let curUid = null;
1624
2328
  try {
1625
2329
  const lock = await this.queryGet(`SELECT GET_LOCK(${MySQLDriver.escapeValue(`${this.prefix}uids_${name}`)}, 10) AS \`lock\`;`);
1626
2330
  if (lock.lock !== 1) {
1627
- throw new nymph_1.QueryFailedError("Couldn't get lock for UID: " + name);
2331
+ throw new QueryFailedError("Couldn't get lock for UID: " + name);
1628
2332
  }
1629
- let curUid = null;
1630
2333
  await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}uids`)} (\`name\`, \`cur_uid\`) VALUES (@name, 1) ON DUPLICATE KEY UPDATE \`cur_uid\`=\`cur_uid\`+1;`, {
1631
2334
  params: {
1632
2335
  name,
@@ -1638,21 +2341,25 @@ class MySQLDriver extends nymph_1.NymphDriver {
1638
2341
  },
1639
2342
  });
1640
2343
  await this.queryRun(`SELECT RELEASE_LOCK(${MySQLDriver.escapeValue(`${this.prefix}uids_${name}`)});`);
1641
- await this.commit('nymph-newuid');
1642
2344
  curUid = result.cur_uid ?? null;
1643
- return curUid;
1644
2345
  }
1645
2346
  catch (e) {
2347
+ this.nymph.config.debugError('mysql', `New UID error: "${e}"`);
1646
2348
  if (e?.message !== "Couldn't get lock for UID: " + name) {
1647
2349
  await this.queryRun(`SELECT RELEASE_LOCK(${MySQLDriver.escapeValue(`${this.prefix}uids_${name}`)});`);
1648
2350
  }
1649
2351
  await this.rollback('nymph-newuid');
1650
2352
  throw e;
1651
2353
  }
2354
+ await this.commit('nymph-newuid');
2355
+ return curUid;
1652
2356
  }
1653
2357
  async renameUID(oldName, newName) {
1654
2358
  if (oldName == null || newName == null) {
1655
- throw new nymph_1.InvalidParametersError('Name not given for UID.');
2359
+ throw new InvalidParametersError('Name not given for UID.');
2360
+ }
2361
+ if (oldName.length > 128 || newName.length > 128) {
2362
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
1656
2363
  }
1657
2364
  await this.queryRun(`UPDATE ${MySQLDriver.escape(`${this.prefix}uids`)} SET \`name\`=@newName WHERE \`name\`=@oldName;`, {
1658
2365
  params: {
@@ -1664,7 +2371,7 @@ class MySQLDriver extends nymph_1.NymphDriver {
1664
2371
  }
1665
2372
  async rollback(name) {
1666
2373
  if (name == null || typeof name !== 'string' || name.length === 0) {
1667
- throw new nymph_1.InvalidParametersError('Transaction rollback attempted without a name.');
2374
+ throw new InvalidParametersError('Transaction rollback attempted without a name.');
1668
2375
  }
1669
2376
  if (!this.transaction || this.transaction.count === 0) {
1670
2377
  this.transaction = null;
@@ -1683,8 +2390,14 @@ class MySQLDriver extends nymph_1.NymphDriver {
1683
2390
  return true;
1684
2391
  }
1685
2392
  async saveEntity(entity) {
1686
- const insertData = async (guid, data, sdata, etype) => {
2393
+ const insertData = async (guid, data, sdata, uniques, etype) => {
2394
+ const EntityClass = this.nymph.getEntityClassByEtype(etype);
1687
2395
  const runInsertQuery = async (name, value, svalue) => {
2396
+ if (typeof name !== 'string' ||
2397
+ !name.length ||
2398
+ name.match(/^\s|=|\s$/)) {
2399
+ throw new EntityInvalidDataError('Property names must be non-empty strings without leading or trailing spaces or equals signs.');
2400
+ }
1688
2401
  if (value === undefined) {
1689
2402
  return;
1690
2403
  }
@@ -1692,24 +2405,19 @@ class MySQLDriver extends nymph_1.NymphDriver {
1692
2405
  ? 'N'
1693
2406
  : typeof value === 'string'
1694
2407
  ? 'S'
1695
- : svalue;
2408
+ : 'J';
2409
+ const jsonValue = storageValue === 'J' ? svalue : null;
1696
2410
  const promises = [];
1697
- promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (\`guid\`, \`name\`, \`value\`) VALUES (UNHEX(@guid), @name, @storageValue);`, {
2411
+ promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} (\`guid\`, \`name\`, \`value\`, \`json\`, \`string\`, \`number\`, \`truthy\`) VALUES (UNHEX(@guid), @name, @storageValue, @jsonValue, @string, @number, @truthy);`, {
1698
2412
  etypes: [etype],
1699
2413
  params: {
1700
2414
  guid,
1701
2415
  name,
1702
2416
  storageValue,
1703
- },
1704
- }));
1705
- promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} (\`guid\`, \`name\`, \`truthy\`, \`string\`, \`number\`) VALUES (UNHEX(@guid), @name, @truthy, @string, @number);`, {
1706
- etypes: [etype],
1707
- params: {
1708
- guid,
1709
- name,
1710
- truthy: !!value,
1711
- string: `${value}`,
2417
+ jsonValue,
2418
+ string: storageValue === 'J' ? null : `${value}`,
1712
2419
  number: isNaN(Number(value)) ? null : Number(value),
2420
+ truthy: !!value,
1713
2421
  },
1714
2422
  }));
1715
2423
  const references = this.findReferences(svalue);
@@ -1723,8 +2431,60 @@ class MySQLDriver extends nymph_1.NymphDriver {
1723
2431
  },
1724
2432
  }));
1725
2433
  }
2434
+ let tokenString = null;
2435
+ try {
2436
+ tokenString = EntityClass.getFTSText(name, value);
2437
+ }
2438
+ catch (e) {
2439
+ // Ignore error.
2440
+ }
2441
+ if (tokenString != null) {
2442
+ const tokens = this.tokenizer.tokenize(tokenString);
2443
+ while (tokens.length) {
2444
+ const currentTokens = tokens.splice(0, 100);
2445
+ const params = {
2446
+ guid,
2447
+ name,
2448
+ };
2449
+ const values = [];
2450
+ for (let i = 0; i < currentTokens.length; i++) {
2451
+ const token = currentTokens[i];
2452
+ params['token' + i] = token.token;
2453
+ params['position' + i] = token.position;
2454
+ params['stem' + i] = token.stem;
2455
+ values.push('(UNHEX(@guid), @name, @token' +
2456
+ i +
2457
+ ', @position' +
2458
+ i +
2459
+ ', @stem' +
2460
+ i +
2461
+ ')');
2462
+ }
2463
+ promises.push(this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} (\`guid\`, \`name\`, \`token\`, \`position\`, \`stem\`) VALUES ${values.join(', ')};`, {
2464
+ etypes: [etype],
2465
+ params,
2466
+ }));
2467
+ }
2468
+ }
1726
2469
  await Promise.all(promises);
1727
2470
  };
2471
+ for (const unique of uniques) {
2472
+ try {
2473
+ await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} (\`guid\`, \`unique\`) VALUES (UNHEX(@guid), @unique);`, {
2474
+ etypes: [etype],
2475
+ params: {
2476
+ guid,
2477
+ unique,
2478
+ },
2479
+ });
2480
+ }
2481
+ catch (e) {
2482
+ if (e instanceof EntityUniqueConstraintError) {
2483
+ this.nymph.config.debugError('mysql', `Save entity unique constraint violation for GUID "${guid}" on etype "${etype}": "${unique}"`);
2484
+ }
2485
+ throw e;
2486
+ }
2487
+ }
1728
2488
  for (const name in data) {
1729
2489
  await runInsertQuery(name, data[name], JSON.stringify(data[name]));
1730
2490
  }
@@ -1732,19 +2492,56 @@ class MySQLDriver extends nymph_1.NymphDriver {
1732
2492
  await runInsertQuery(name, JSON.parse(sdata[name]), sdata[name]);
1733
2493
  }
1734
2494
  };
2495
+ let inTransaction = false;
1735
2496
  try {
1736
- const result = await this.saveEntityRowLike(entity, async (_entity, guid, tags, data, sdata, cdate, etype) => {
1737
- await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`) VALUES (UNHEX(@guid), @tags, @cdate, @cdate);`, {
2497
+ const result = await this.saveEntityRowLike(entity, async ({ guid, tags, data, sdata, uniques, cdate, etype }) => {
2498
+ if (Object.keys(data).length === 0 &&
2499
+ Object.keys(sdata).length === 0) {
2500
+ throw new EntityInvalidDataError('Entity contains no data.');
2501
+ }
2502
+ for (let tag of tags) {
2503
+ if (typeof tag !== 'string' ||
2504
+ !tag.length ||
2505
+ tag.match(/[\x00-\x1F\x7F\[\],]/)) {
2506
+ throw new EntityInvalidDataError('Tags must be non-empty strings without square brackets, control characters, or commas.');
2507
+ }
2508
+ }
2509
+ let processedData = this.removeAndReturnACValues(etype, { ...data }, { ...sdata });
2510
+ ({ data, sdata } = processedData);
2511
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull, } = processedData;
2512
+ await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`, \`user\`, \`group\`, \`acUser\`, \`acGroup\`, \`acOther\`, \`acRead\`, \`acWrite\`, \`acFull\`) VALUES (UNHEX(@guid), @tags, @cdate, @cdate, ${user == null ? '@user' : 'UNHEX(@user)'}, ${group == null ? '@group' : 'UNHEX(@group)'}, @acUser, @acGroup, @acOther, @acRead, @acWrite, @acFull);`, {
1738
2513
  etypes: [etype],
1739
2514
  params: {
1740
2515
  guid,
1741
- tags: ' ' + tags.join(' ') + ' ',
2516
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
1742
2517
  cdate,
2518
+ user,
2519
+ group,
2520
+ acUser,
2521
+ acGroup,
2522
+ acOther,
2523
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2524
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2525
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
1743
2526
  },
1744
2527
  });
1745
- await insertData(guid, data, sdata, etype);
2528
+ await insertData(guid, data, sdata, uniques, etype);
1746
2529
  return true;
1747
- }, async (entity, guid, tags, data, sdata, mdate, etype) => {
2530
+ }, async ({ entity, guid, tags, data, sdata, uniques, mdate, etype }) => {
2531
+ if (Object.keys(data).length === 0 &&
2532
+ Object.keys(sdata).length === 0) {
2533
+ throw new EntityInvalidDataError('Entity contains no data.');
2534
+ }
2535
+ for (let tag of tags) {
2536
+ if (typeof tag !== 'string' ||
2537
+ !tag.length ||
2538
+ tag.match(/[\x00-\x1F\x7F\[\],]/)) {
2539
+ throw new EntityInvalidDataError('Tags must be non-empty strings without square brackets, control characters, or commas.');
2540
+ }
2541
+ }
2542
+ let processedData = this.removeAndReturnACValues(etype, { ...data }, { ...sdata });
2543
+ ({ data, sdata } = processedData);
2544
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull, } = processedData;
1748
2545
  if (this.config.rowLocking) {
1749
2546
  const promises = [];
1750
2547
  promises.push(this.queryRun(`SELECT 1 FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`, {
@@ -1759,13 +2556,19 @@ class MySQLDriver extends nymph_1.NymphDriver {
1759
2556
  guid,
1760
2557
  },
1761
2558
  }));
1762
- promises.push(this.queryRun(`SELECT 1 FROM ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`, {
2559
+ promises.push(this.queryRun(`SELECT 1 FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`, {
1763
2560
  etypes: [etype],
1764
2561
  params: {
1765
2562
  guid,
1766
2563
  },
1767
2564
  }));
1768
- promises.push(this.queryRun(`SELECT 1 FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`, {
2565
+ promises.push(this.queryRun(`SELECT 1 FROM ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`, {
2566
+ etypes: [etype],
2567
+ params: {
2568
+ guid,
2569
+ },
2570
+ }));
2571
+ promises.push(this.queryRun(`SELECT 1 FROM ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`, {
1769
2572
  etypes: [etype],
1770
2573
  params: {
1771
2574
  guid,
@@ -1774,13 +2577,21 @@ class MySQLDriver extends nymph_1.NymphDriver {
1774
2577
  await Promise.all(promises);
1775
2578
  }
1776
2579
  if (this.config.tableLocking) {
1777
- await this.queryRun(`LOCK TABLES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WRITE;`);
2580
+ await this.queryRun(`LOCK TABLES ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} WRITE, ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} WRITE;`);
1778
2581
  }
1779
- const info = await this.queryRun(`UPDATE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} SET \`tags\`=@tags, \`mdate\`=@mdate WHERE \`guid\`=UNHEX(@guid) AND \`mdate\` <= @emdate;`, {
2582
+ const info = await this.queryRun(`UPDATE ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} SET \`tags\`=@tags, \`mdate\`=@mdate, \`user\`=${user == null ? '@user' : 'UNHEX(@user)'}, \`group\`=${group == null ? '@group' : 'UNHEX(@group)'}, \`acUser\`=@acUser, \`acGroup\`=@acGroup, \`acOther\`=@acOther, \`acRead\`=@acRead, \`acWrite\`=@acWrite, \`acFull\`=@acFull WHERE \`guid\`=UNHEX(@guid) AND \`mdate\` <= @emdate;`, {
1780
2583
  etypes: [etype],
1781
2584
  params: {
1782
- tags: ' ' + tags.join(' ') + ' ',
2585
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
1783
2586
  mdate,
2587
+ user,
2588
+ group,
2589
+ acUser,
2590
+ acGroup,
2591
+ acOther,
2592
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2593
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2594
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
1784
2595
  guid,
1785
2596
  emdate: isNaN(Number(entity.mdate)) ? 0 : Number(entity.mdate),
1786
2597
  },
@@ -1794,47 +2605,66 @@ class MySQLDriver extends nymph_1.NymphDriver {
1794
2605
  guid,
1795
2606
  },
1796
2607
  }));
1797
- promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}comparisons_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
2608
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
1798
2609
  etypes: [etype],
1799
2610
  params: {
1800
2611
  guid,
1801
2612
  },
1802
2613
  }));
1803
- promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
2614
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
2615
+ etypes: [etype],
2616
+ params: {
2617
+ guid,
2618
+ },
2619
+ }));
2620
+ promises.push(this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}uniques_${etype}`)} WHERE \`guid\`=UNHEX(@guid);`, {
1804
2621
  etypes: [etype],
1805
2622
  params: {
1806
2623
  guid,
1807
2624
  },
1808
2625
  }));
1809
2626
  await Promise.all(promises);
1810
- await insertData(guid, data, sdata, etype);
2627
+ await insertData(guid, data, sdata, uniques, etype);
1811
2628
  success = true;
1812
2629
  }
1813
2630
  if (this.config.tableLocking) {
1814
2631
  await this.queryRun('UNLOCK TABLES;');
1815
2632
  }
2633
+ if (!success && info.changes === 0) {
2634
+ throw new EntityConflictError("Entity either doesn't exist or is newer in the DB.");
2635
+ }
1816
2636
  return success;
1817
2637
  }, async () => {
1818
2638
  await this.internalTransaction('nymph-save');
2639
+ inTransaction = true;
1819
2640
  }, async (success) => {
1820
- if (success) {
1821
- await this.commit('nymph-save');
1822
- }
1823
- else {
1824
- await this.rollback('nymph-save');
2641
+ if (inTransaction) {
2642
+ inTransaction = false;
2643
+ if (success) {
2644
+ success = await this.commit('nymph-save');
2645
+ }
2646
+ else {
2647
+ await this.rollback('nymph-save');
2648
+ }
1825
2649
  }
1826
2650
  return success;
1827
2651
  });
1828
2652
  return result;
1829
2653
  }
1830
2654
  catch (e) {
1831
- await this.rollback('nymph-save');
2655
+ this.nymph.config.debugError('mysql', `Save entity error: "${e}"`);
2656
+ if (inTransaction) {
2657
+ await this.rollback('nymph-save');
2658
+ }
1832
2659
  throw e;
1833
2660
  }
1834
2661
  }
1835
2662
  async setUID(name, curUid) {
1836
2663
  if (name == null) {
1837
- throw new nymph_1.InvalidParametersError('Name not given for UID.');
2664
+ throw new InvalidParametersError('Name not given for UID.');
2665
+ }
2666
+ if (name.length > 128) {
2667
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
1838
2668
  }
1839
2669
  await this.queryRun(`INSERT INTO ${MySQLDriver.escape(`${this.prefix}uids`)} (\`name\`, \`cur_uid\`) VALUES (@name, @curUid) ON DUPLICATE KEY UPDATE \`cur_uid\`=@curUid;`, {
1840
2670
  params: {
@@ -1844,35 +2674,146 @@ class MySQLDriver extends nymph_1.NymphDriver {
1844
2674
  });
1845
2675
  return true;
1846
2676
  }
1847
- async internalTransaction(name) {
2677
+ async internalTransaction(name, setOnSelf = true) {
1848
2678
  if (name == null || typeof name !== 'string' || name.length === 0) {
1849
- throw new nymph_1.InvalidParametersError('Transaction start attempted without a name.');
2679
+ throw new InvalidParametersError('Transaction start attempted without a name.');
1850
2680
  }
1851
- if (!this.transaction || this.transaction.count === 0) {
1852
- this.transaction = {
2681
+ let transaction = this.transaction;
2682
+ if (!transaction) {
2683
+ // Lock to one connection.
2684
+ transaction = {
1853
2685
  count: 0,
1854
2686
  connection: await this.getConnection(),
2687
+ latestPromise: Promise.resolve(),
1855
2688
  };
1856
- if (this.config.transactions) {
1857
- await this.queryRun('START TRANSACTION;');
2689
+ if (setOnSelf) {
2690
+ this.transaction = transaction;
1858
2691
  }
1859
2692
  }
2693
+ if (this.config.transactions && transaction.count === 0) {
2694
+ // We're not in a transaction yet, so start one.
2695
+ await this.queryRun('START TRANSACTION;', { transaction });
2696
+ }
2697
+ transaction.count++;
1860
2698
  if (this.config.transactions) {
1861
- await this.queryRun(`SAVEPOINT ${MySQLDriver.escape(name)};`);
2699
+ await this.queryRun(`SAVEPOINT ${MySQLDriver.escape(name)};`, {
2700
+ transaction,
2701
+ });
1862
2702
  }
1863
- this.transaction.count++;
1864
- return this.transaction;
2703
+ return transaction;
1865
2704
  }
1866
2705
  async startTransaction(name) {
1867
- const inTransaction = this.inTransaction();
1868
- const transaction = await this.internalTransaction(name);
1869
- if (!inTransaction) {
1870
- this.transaction = null;
1871
- }
2706
+ const transaction = await this.internalTransaction(name, false);
1872
2707
  const nymph = this.nymph.clone();
1873
2708
  nymph.driver.transaction = transaction;
1874
2709
  return nymph;
1875
2710
  }
2711
+ async removeTilmeldOldRows(etype) {
2712
+ await this.internalTransaction('nymph-remove-tilmeld-rows');
2713
+ try {
2714
+ for (let name of [
2715
+ 'user',
2716
+ 'group',
2717
+ 'acUser',
2718
+ 'acGroup',
2719
+ 'acOther',
2720
+ 'acRead',
2721
+ 'acWrite',
2722
+ 'acFull',
2723
+ ]) {
2724
+ await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}data_${etype}`)} WHERE \`name\`=@name;`, {
2725
+ etypes: [etype],
2726
+ params: {
2727
+ name,
2728
+ },
2729
+ });
2730
+ await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}references_${etype}`)} WHERE \`name\`=@name;`, {
2731
+ etypes: [etype],
2732
+ params: {
2733
+ name,
2734
+ },
2735
+ });
2736
+ await this.queryRun(`DELETE FROM ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)} WHERE \`name\`=@name;`, {
2737
+ etypes: [etype],
2738
+ params: {
2739
+ name,
2740
+ },
2741
+ });
2742
+ }
2743
+ }
2744
+ catch (e) {
2745
+ this.nymph.config.debugError('mysql', `Remove tilmeld rows error: "${e}"`);
2746
+ await this.rollback('nymph-remove-tilmeld-rows');
2747
+ throw e;
2748
+ }
2749
+ await this.commit('nymph-remove-tilmeld-rows');
2750
+ return true;
2751
+ }
2752
+ async needsMigration() {
2753
+ const table = await this.queryGet('SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix LIMIT 1;', {
2754
+ params: {
2755
+ db: this.config.database,
2756
+ prefix: this.prefix + 'data_' + '%',
2757
+ },
2758
+ });
2759
+ if (table?.table_name) {
2760
+ const result = await this.queryGet("SELECT 1 AS `exists` FROM `information_schema`.`columns` WHERE `table_schema`=@db AND `table_name`=@table AND `column_name`='json';", {
2761
+ params: {
2762
+ db: this.config.database,
2763
+ table: table.table_name,
2764
+ },
2765
+ });
2766
+ if (!result?.exists) {
2767
+ return 'json';
2768
+ }
2769
+ }
2770
+ const table2 = await this.queryGet('SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @tokenTable LIMIT 1;', {
2771
+ params: {
2772
+ db: this.config.database,
2773
+ tokenTable: this.prefix + 'tokens_' + '%',
2774
+ },
2775
+ });
2776
+ if (!table2 || !table2.table_name) {
2777
+ return 'tokens';
2778
+ }
2779
+ const table3 = await this.queryGet('SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix LIMIT 1;', {
2780
+ params: {
2781
+ db: this.config.database,
2782
+ prefix: this.prefix + 'entities_' + '%',
2783
+ },
2784
+ });
2785
+ if (table3?.table_name) {
2786
+ const result = await this.queryGet("SELECT 1 AS `exists` FROM `information_schema`.`columns` WHERE `table_schema`=@db AND `table_name`=@table AND `column_name`='user';", {
2787
+ params: {
2788
+ db: this.config.database,
2789
+ table: table3.table_name,
2790
+ },
2791
+ });
2792
+ if (!result?.exists) {
2793
+ return 'tilmeldColumns';
2794
+ }
2795
+ }
2796
+ return false;
2797
+ }
2798
+ async liveMigration(migrationType) {
2799
+ if (migrationType === 'tokenTables') {
2800
+ const etypes = await this.getEtypes();
2801
+ for (let etype of etypes) {
2802
+ await this.createTokensTable(etype);
2803
+ }
2804
+ }
2805
+ else if (migrationType === 'tilmeldColumns') {
2806
+ const etypes = await this.getEtypes();
2807
+ for (let etype of etypes) {
2808
+ await this.addTilmeldColumnsAndIndexes(etype);
2809
+ }
2810
+ }
2811
+ else if (migrationType === 'tilmeldRemoveOldRows') {
2812
+ const etypes = await this.getEtypes();
2813
+ for (let etype of etypes) {
2814
+ await this.removeTilmeldOldRows(etype);
2815
+ }
2816
+ }
2817
+ }
1876
2818
  }
1877
- exports.default = MySQLDriver;
1878
2819
  //# sourceMappingURL=MySQLDriver.js.map