@nymphjs/driver-mysql 1.0.0-beta.15 → 1.0.0-beta.150

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,21 +1,30 @@
1
- import cp from 'child_process';
2
- // @ts-ignore: types are wonky with @vlasky/mysql.
3
- import { default as MySQLType } from '@types/mysql';
4
- // @ts-ignore: replace with mysql once https://github.com/mysqljs/mysql/pull/2233 is merged.
5
- import vlaskyMysql from '@vlasky/mysql';
1
+ import { Pool, PoolOptions, PoolConnection } from 'mysql2';
2
+ import mysql from 'mysql2';
3
+ import SqlString from 'sqlstring';
4
+ import type {
5
+ SearchTerm,
6
+ SearchOrTerm,
7
+ SearchNotTerm,
8
+ SearchSeriesTerm,
9
+ } from '@sciactive/tokenizer';
6
10
  import {
7
11
  NymphDriver,
8
- EntityConstructor,
9
- EntityData,
10
- EntityInterface,
11
- SerializedEntityData,
12
+ type EntityConstructor,
13
+ type EntityData,
14
+ type EntityObjectType,
15
+ type EntityInterface,
16
+ type EntityInstanceType,
17
+ type SerializedEntityData,
18
+ type FormattedSelector,
19
+ type Options,
20
+ type Selector,
21
+ EntityConflictError,
22
+ EntityInvalidDataError,
23
+ EntityUniqueConstraintError,
12
24
  InvalidParametersError,
13
25
  NotConfiguredError,
14
26
  QueryFailedError,
15
27
  UnableToConnectError,
16
- FormattedSelector,
17
- Options,
18
- Selector,
19
28
  xor,
20
29
  } from '@nymphjs/nymph';
21
30
  import { makeTableSuffix } from '@nymphjs/guid';
@@ -23,39 +32,59 @@ import { makeTableSuffix } from '@nymphjs/guid';
23
32
  import {
24
33
  MySQLDriverConfig,
25
34
  MySQLDriverConfigDefaults as defaults,
26
- } from './conf';
35
+ } from './conf/index.js';
27
36
 
28
37
  type MySQLDriverTransaction = {
29
- connection: MySQLType.PoolConnection | null;
38
+ connection: PoolConnection | null;
30
39
  count: number;
40
+ latestPromise: Promise<any>;
31
41
  };
32
42
 
33
- const mysql = vlaskyMysql as typeof MySQLType;
34
-
35
43
  /**
36
44
  * The MySQL Nymph database driver.
37
45
  */
38
46
  export default class MySQLDriver extends NymphDriver {
39
47
  public config: MySQLDriverConfig;
40
- private mysqlConfig: MySQLType.PoolConfig;
48
+ private mysqlConfig: PoolOptions;
41
49
  protected prefix: string;
42
50
  protected connected: boolean = false;
43
51
  // @ts-ignore: this is assigned in connect(), which is called by the constructor.
44
- protected link: MySQLType.Pool;
52
+ protected link: Pool;
45
53
  protected transaction: MySQLDriverTransaction | null = null;
46
54
 
47
55
  static escape(input: string) {
48
- return mysql.escapeId(input);
56
+ return SqlString.escapeId(input, true);
49
57
  }
50
58
 
51
59
  static escapeValue(input: string) {
52
60
  return mysql.escape(input);
53
61
  }
54
62
 
63
+ static escapeTags(tags: string[]) {
64
+ return tags.map(MySQLDriver.escapeTag);
65
+ }
66
+
67
+ static escapeTag(tag: string) {
68
+ return tag
69
+ .replace(/\\/g, () => '\\\\')
70
+ .replace(/_/g, () => '\\_')
71
+ .replace(/ /g, () => '_');
72
+ }
73
+
74
+ static unescapeTags(tags: string[]) {
75
+ return tags.map(MySQLDriver.unescapeTag);
76
+ }
77
+
78
+ static unescapeTag(tag: string) {
79
+ return tag.replace(/\\([\\_])|_/g, (_, char) =>
80
+ char != null ? char : ' ',
81
+ );
82
+ }
83
+
55
84
  constructor(
56
85
  config: Partial<MySQLDriverConfig>,
57
- link?: MySQLType.Pool,
58
- transaction?: MySQLDriverTransaction
86
+ link?: Pool,
87
+ transaction?: MySQLDriverTransaction,
59
88
  ) {
60
89
  super();
61
90
  this.config = { ...defaults, ...config };
@@ -90,16 +119,16 @@ export default class MySQLDriver extends NymphDriver {
90
119
  return new MySQLDriver(
91
120
  this.config,
92
121
  this.link,
93
- this.transaction ?? undefined
122
+ this.transaction ?? undefined,
94
123
  );
95
124
  }
96
125
 
97
- private getConnection(): Promise<MySQLType.PoolConnection> {
126
+ private getConnection(): Promise<PoolConnection> {
98
127
  if (this.transaction != null && this.transaction.connection != null) {
99
128
  return Promise.resolve(this.transaction.connection);
100
129
  }
101
130
  return new Promise((resolve, reject) =>
102
- this.link.getConnection((err, con) => (err ? reject(err) : resolve(con)))
131
+ this.link.getConnection((err, con) => (err ? reject(err) : resolve(con))),
103
132
  );
104
133
  }
105
134
 
@@ -112,16 +141,11 @@ export default class MySQLDriver extends NymphDriver {
112
141
  // If we think we're connected, try pinging the server.
113
142
  try {
114
143
  if (this.connected) {
115
- const connection: MySQLType.PoolConnection = await new Promise(
144
+ const connection: PoolConnection = await new Promise(
116
145
  (resolve, reject) =>
117
146
  this.link.getConnection((err, con) =>
118
- err ? reject(err) : resolve(con)
119
- )
120
- );
121
- await new Promise((resolve) =>
122
- connection.ping(() => {
123
- resolve(0);
124
- })
147
+ err ? reject(err) : resolve(con),
148
+ ),
125
149
  );
126
150
  connection.release();
127
151
  }
@@ -132,7 +156,10 @@ export default class MySQLDriver extends NymphDriver {
132
156
  // Connecting, selecting database
133
157
  if (!this.connected) {
134
158
  try {
135
- this.link = mysql.createPool(this.mysqlConfig);
159
+ this.link = mysql.createPool({
160
+ ...this.mysqlConfig,
161
+ charset: 'utf8mb4_bin',
162
+ });
136
163
  this.connected = true;
137
164
  } catch (e: any) {
138
165
  if (
@@ -142,7 +169,7 @@ export default class MySQLDriver extends NymphDriver {
142
169
  this.mysqlConfig.database === 'nymph'
143
170
  ) {
144
171
  throw new NotConfiguredError(
145
- "It seems the config hasn't been set up correctly."
172
+ "It seems the config hasn't been set up correctly.",
146
173
  );
147
174
  } else {
148
175
  throw new UnableToConnectError('Could not connect: ' + e?.message);
@@ -166,6 +193,9 @@ export default class MySQLDriver extends NymphDriver {
166
193
  }
167
194
 
168
195
  public async inTransaction() {
196
+ if (this.transaction && this.transaction.count === 0) {
197
+ this.transaction = null;
198
+ }
169
199
  return !!this.transaction;
170
200
  }
171
201
 
@@ -178,106 +208,271 @@ export default class MySQLDriver extends NymphDriver {
178
208
  return this.connected;
179
209
  }
180
210
 
181
- /**
182
- * Create entity tables in the database.
183
- *
184
- * @param etype The entity type to create a table for. If this is blank, the default tables are created.
185
- * @returns True on success, false on failure.
186
- */
187
- private createTables(etype: string | null = null) {
188
- this.queryRunSync('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
189
- let foreignKeyDataTableGuid = '';
190
- let foreignKeyDataComparisonsTableGuid = '';
191
- let foreignKeyReferencesTableGuid = '';
192
- if (this.config.foreignKeys) {
193
- foreignKeyDataTableGuid = ` REFERENCES ${MySQLDriver.escape(
194
- `${this.prefix}entities_${etype}`
195
- )}(\`guid\`) ON DELETE CASCADE`;
196
- foreignKeyDataComparisonsTableGuid = ` REFERENCES ${MySQLDriver.escape(
197
- `${this.prefix}entities_${etype}`
198
- )}(\`guid\`) ON DELETE CASCADE`;
199
- foreignKeyReferencesTableGuid = ` REFERENCES ${MySQLDriver.escape(
200
- `${this.prefix}entities_${etype}`
201
- )}(\`guid\`) ON DELETE CASCADE`;
202
- }
203
- if (etype != null) {
204
- // Create the entity table.
205
- this.queryRunSync(
206
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
207
- `${this.prefix}entities_${etype}`
208
- )} (
211
+ private async createEntitiesTable(etype: string) {
212
+ // Create the entity table.
213
+ await this.queryRun(
214
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
215
+ `${this.prefix}entities_${etype}`,
216
+ )} (
209
217
  \`guid\` BINARY(12) NOT NULL,
210
218
  \`tags\` LONGTEXT,
211
219
  \`cdate\` DOUBLE PRECISION NOT NULL,
212
220
  \`mdate\` DOUBLE PRECISION NOT NULL,
221
+ \`user\` BINARY(12),
222
+ \`group\` BINARY(12),
223
+ \`acUser\` TINYINT UNSIGNED,
224
+ \`acGroup\` TINYINT UNSIGNED,
225
+ \`acOther\` TINYINT UNSIGNED,
226
+ \`acRead\` LONGTEXT,
227
+ \`acWrite\` LONGTEXT,
228
+ \`acFull\` LONGTEXT,
213
229
  PRIMARY KEY (\`guid\`),
230
+ INDEX \`id_guid\` USING HASH (\`guid\`),
214
231
  INDEX \`id_cdate\` USING BTREE (\`cdate\`),
215
232
  INDEX \`id_mdate\` USING BTREE (\`mdate\`),
216
- FULLTEXT \`id_tags\` (\`tags\`)
217
- ) ENGINE ${this.config.engine}
218
- CHARACTER SET utf8 COLLATE utf8_bin;`
219
- );
220
- // Create the data table.
221
- this.queryRunSync(
222
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
223
- `${this.prefix}data_${etype}`
224
- )} (
225
- \`guid\` BINARY(12) NOT NULL${foreignKeyDataTableGuid},
226
- \`name\` TEXT NOT NULL,
227
- \`value\` LONGTEXT NOT NULL,
228
- PRIMARY KEY (\`guid\`,\`name\`(255)),
229
- INDEX \`id_name\` USING HASH (\`name\`(255)),
230
- INDEX \`id_name_value\` USING BTREE (\`name\`(255), \`value\`(512))
233
+ FULLTEXT \`id_tags\` (\`tags\`),
234
+ INDEX \`id_user_acUser\` USING BTREE (\`user\`, \`acUser\`),
235
+ INDEX \`id_group_acGroup\` USING BTREE (\`group\`, \`acGroup\`),
236
+ INDEX \`id_acUser\` USING BTREE (\`acUser\`),
237
+ INDEX \`id_acGroup\` USING BTREE (\`acGroup\`),
238
+ INDEX \`id_acOther\` USING BTREE (\`acOther\`),
239
+ FULLTEXT \`id_acRead\` (\`acRead\`),
240
+ FULLTEXT \`id_acWrite\` (\`acWrite\`),
241
+ FULLTEXT \`id_acFull\` (\`acFull\`)
231
242
  ) ENGINE ${this.config.engine}
232
- CHARACTER SET utf8 COLLATE utf8_bin;`
233
- );
234
- // Create the data comparisons table.
235
- this.queryRunSync(
236
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
237
- `${this.prefix}comparisons_${etype}`
238
- )} (
239
- \`guid\` BINARY(12) NOT NULL${foreignKeyDataComparisonsTableGuid},
243
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
244
+ );
245
+ }
246
+
247
+ private async addTilmeldColumnsAndIndexes(etype: string) {
248
+ await this.queryRun(
249
+ `ALTER TABLE ${MySQLDriver.escape(
250
+ `${this.prefix}entities_${etype}`,
251
+ )} ADD COLUMN \`user\` BINARY(12);`,
252
+ );
253
+ await this.queryRun(
254
+ `ALTER TABLE ${MySQLDriver.escape(
255
+ `${this.prefix}entities_${etype}`,
256
+ )} ADD COLUMN \`group\` BINARY(12);`,
257
+ );
258
+ await this.queryRun(
259
+ `ALTER TABLE ${MySQLDriver.escape(
260
+ `${this.prefix}entities_${etype}`,
261
+ )} ADD COLUMN \`acUser\` TINYINT UNSIGNED;`,
262
+ );
263
+ await this.queryRun(
264
+ `ALTER TABLE ${MySQLDriver.escape(
265
+ `${this.prefix}entities_${etype}`,
266
+ )} ADD COLUMN \`acGroup\` TINYINT UNSIGNED;`,
267
+ );
268
+ await this.queryRun(
269
+ `ALTER TABLE ${MySQLDriver.escape(
270
+ `${this.prefix}entities_${etype}`,
271
+ )} ADD COLUMN \`acOther\` TINYINT UNSIGNED;`,
272
+ );
273
+ await this.queryRun(
274
+ `ALTER TABLE ${MySQLDriver.escape(
275
+ `${this.prefix}entities_${etype}`,
276
+ )} ADD COLUMN \`acRead\` LONGTEXT;`,
277
+ );
278
+ await this.queryRun(
279
+ `ALTER TABLE ${MySQLDriver.escape(
280
+ `${this.prefix}entities_${etype}`,
281
+ )} ADD COLUMN \`acWrite\` LONGTEXT;`,
282
+ );
283
+ await this.queryRun(
284
+ `ALTER TABLE ${MySQLDriver.escape(
285
+ `${this.prefix}entities_${etype}`,
286
+ )} ADD COLUMN \`acFull\` LONGTEXT;`,
287
+ );
288
+ await this.createEntitiesTilmeldIndexes(etype);
289
+ }
290
+
291
+ private async createEntitiesTilmeldIndexes(etype: string) {
292
+ await this.queryRun(
293
+ `CREATE INDEX \`id_user_acUser\` ON ${MySQLDriver.escape(
294
+ `${this.prefix}entities_${etype}`,
295
+ )} (\`user\`, \`acUser\`) USING BTREE;`,
296
+ );
297
+ await this.queryRun(
298
+ `CREATE INDEX \`id_group_acGroup\` ON ${MySQLDriver.escape(
299
+ `${this.prefix}entities_${etype}`,
300
+ )} (\`group\`, \`acGroup\`) USING BTREE;`,
301
+ );
302
+ await this.queryRun(
303
+ `CREATE INDEX \`id_acUser\` ON ${MySQLDriver.escape(
304
+ `${this.prefix}entities_${etype}`,
305
+ )} (\`acUser\`) USING BTREE;`,
306
+ );
307
+ await this.queryRun(
308
+ `CREATE INDEX \`id_acGroup\` ON ${MySQLDriver.escape(
309
+ `${this.prefix}entities_${etype}`,
310
+ )} (\`acGroup\`) USING BTREE;`,
311
+ );
312
+ await this.queryRun(
313
+ `CREATE INDEX \`id_acOther\` ON ${MySQLDriver.escape(
314
+ `${this.prefix}entities_${etype}`,
315
+ )} (\`acOther\`) USING BTREE;`,
316
+ );
317
+ await this.queryRun(
318
+ `CREATE FULLTEXT INDEX \`id_acRead\` ON ${MySQLDriver.escape(
319
+ `${this.prefix}entities_${etype}`,
320
+ )} (\`acRead\`);`,
321
+ );
322
+ await this.queryRun(
323
+ `CREATE FULLTEXT INDEX \`id_acWrite\` ON ${MySQLDriver.escape(
324
+ `${this.prefix}entities_${etype}`,
325
+ )} (\`acWrite\`);`,
326
+ );
327
+ await this.queryRun(
328
+ `CREATE FULLTEXT INDEX \`id_acFull\` ON ${MySQLDriver.escape(
329
+ `${this.prefix}entities_${etype}`,
330
+ )} (\`acFull\`);`,
331
+ );
332
+ }
333
+
334
+ private async createDataTable(etype: string) {
335
+ let foreignKey = '';
336
+ if (this.config.foreignKeys) {
337
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
338
+ `${this.prefix}entities_${etype}`,
339
+ )}(\`guid\`) ON DELETE CASCADE`;
340
+ }
341
+ // Create the data table.
342
+ await this.queryRun(
343
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
344
+ `${this.prefix}data_${etype}`,
345
+ )} (
346
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
240
347
  \`name\` TEXT NOT NULL,
241
- \`truthy\` BOOLEAN,
348
+ \`value\` CHAR(1) NOT NULL,
349
+ \`json\` JSON,
242
350
  \`string\` LONGTEXT,
243
351
  \`number\` DOUBLE,
352
+ \`truthy\` BOOLEAN,
244
353
  PRIMARY KEY (\`guid\`, \`name\`(255)),
245
- INDEX \`id_name\` USING HASH (\`name\`(255))
354
+ INDEX \`id_name_guid\` USING BTREE (\`name\`(255), \`guid\`),
355
+ INDEX \`id_name_string_guid\` USING BTREE (\`name\`(255), \`string\`(500), \`guid\`),
356
+ INDEX \`id_name_number_guid\` USING BTREE (\`name\`(255), \`number\`, \`guid\`),
357
+ INDEX \`id_name_truthy_guid\` USING BTREE (\`name\`(255), \`truthy\`, \`guid\`),
358
+ INDEX \`id_name_json_guid\` USING BTREE (\`name\`(255), (CAST(\`json\` AS CHAR(500)) COLLATE utf8mb4_bin), \`guid\`)
246
359
  ) ENGINE ${this.config.engine}
247
- CHARACTER SET utf8 COLLATE utf8_bin;`
248
- );
249
- // Create the references table.
250
- this.queryRunSync(
251
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
252
- `${this.prefix}references_${etype}`
253
- )} (
254
- \`guid\` BINARY(12) NOT NULL${foreignKeyReferencesTableGuid},
360
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
361
+ );
362
+ }
363
+
364
+ private async createReferencesTable(etype: string) {
365
+ let foreignKey = '';
366
+ if (this.config.foreignKeys) {
367
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
368
+ `${this.prefix}entities_${etype}`,
369
+ )}(\`guid\`) ON DELETE CASCADE`;
370
+ }
371
+ // Create the references table.
372
+ await this.queryRun(
373
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
374
+ `${this.prefix}references_${etype}`,
375
+ )} (
376
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
255
377
  \`name\` TEXT NOT NULL,
256
378
  \`reference\` BINARY(12) NOT NULL,
257
379
  PRIMARY KEY (\`guid\`, \`name\`(255), \`reference\`),
258
- INDEX \`id_name_reference\` USING BTREE (\`name\`(255), \`reference\`)
380
+ INDEX \`id_name_reference_guid\` USING HASH (\`name\`(255), \`reference\`, \`guid\`)
259
381
  ) ENGINE ${this.config.engine}
260
- CHARACTER SET utf8 COLLATE utf8_bin;`
261
- );
382
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
383
+ );
384
+ }
385
+
386
+ private async createTokensTable(etype: string) {
387
+ let foreignKey = '';
388
+ if (this.config.foreignKeys) {
389
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
390
+ `${this.prefix}entities_${etype}`,
391
+ )}(\`guid\`) ON DELETE CASCADE`;
392
+ }
393
+ // Create the tokens table.
394
+ await this.queryRun(
395
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
396
+ `${this.prefix}tokens_${etype}`,
397
+ )} (
398
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
399
+ \`name\` TEXT NOT NULL,
400
+ \`token\` INT NOT NULL,
401
+ \`position\` INT UNSIGNED NOT NULL,
402
+ \`stem\` BOOLEAN NOT NULL,
403
+ PRIMARY KEY (\`guid\`, \`name\`(255), \`token\`, \`position\`),
404
+ INDEX \`id_name_token_guid\` USING btree (\`name\`(255), \`token\`, \`guid\`)
405
+ ) ENGINE ${this.config.engine}
406
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
407
+ );
408
+ }
409
+
410
+ private async createUniquesTable(etype: string) {
411
+ let foreignKey = '';
412
+ if (this.config.foreignKeys) {
413
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
414
+ `${this.prefix}entities_${etype}`,
415
+ )}(\`guid\`) ON DELETE CASCADE`;
416
+ }
417
+ // Create the unique strings table.
418
+ // 255 key is max length for charset UTF8.
419
+ await this.queryRun(
420
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
421
+ `${this.prefix}uniques_${etype}`,
422
+ )} (
423
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
424
+ \`unique\` TEXT NOT NULL,
425
+ PRIMARY KEY (\`guid\`, \`unique\`(255)),
426
+ INDEX \`id_guid\` USING HASH (\`guid\`),
427
+ CONSTRAINT \`uc_unique\` UNIQUE (\`unique\`(255))
428
+ ) ENGINE ${this.config.engine}
429
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
430
+ );
431
+ }
432
+
433
+ /**
434
+ * Create entity tables in the database.
435
+ *
436
+ * @param etype The entity type to create a table for. If this is blank, the default tables are created.
437
+ * @returns True on success, false on failure.
438
+ */
439
+ private async createTables(etype: string | null = null) {
440
+ await this.queryRun('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
441
+ if (etype != null) {
442
+ await this.createEntitiesTable(etype);
443
+ await this.createDataTable(etype);
444
+ await this.createReferencesTable(etype);
445
+ await this.createTokensTable(etype);
446
+ await this.createUniquesTable(etype);
262
447
  } else {
263
448
  // Create the UID table.
264
- this.queryRunSync(
449
+ await this.queryRun(
265
450
  `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
266
- `${this.prefix}uids`
451
+ `${this.prefix}uids`,
267
452
  )} (
268
453
  \`name\` TEXT NOT NULL,
269
454
  \`cur_uid\` BIGINT(20) UNSIGNED NOT NULL,
270
- PRIMARY KEY (\`name\`(100))
455
+ PRIMARY KEY (\`name\`(128))
271
456
  ) ENGINE ${this.config.engine}
272
- CHARACTER SET utf8 COLLATE utf8_bin;`
457
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
273
458
  );
274
459
  }
460
+ if (
461
+ this.transaction &&
462
+ this.transaction.count > 0 &&
463
+ this.config.transactions
464
+ ) {
465
+ this.transaction.count = 0;
466
+ this.transaction.connection?.release();
467
+ this.transaction.connection = null;
468
+ this.transaction = null;
469
+ }
275
470
  return true;
276
471
  }
277
472
 
278
473
  private translateQuery(
279
474
  origQuery: string,
280
- origParams: { [k: string]: any }
475
+ origParams: { [k: string]: any },
281
476
  ): { query: string; params: any[] } {
282
477
  const params: any[] = [];
283
478
  let query = origQuery;
@@ -296,32 +491,37 @@ export default class MySQLDriver extends NymphDriver {
296
491
  private async query<T extends () => any>(
297
492
  runQuery: T,
298
493
  query: string,
299
- etypes: string[] = []
494
+ etypes: string[] = [],
300
495
  // @ts-ignore: The return type of T is a promise.
301
496
  ): ReturnType<T> {
302
497
  try {
498
+ this.nymph.config.debugInfo('mysql:query', query);
303
499
  return await runQuery();
304
500
  } catch (e: any) {
305
501
  const errorCode = e?.errno;
306
- if (errorCode === 1146 && this.createTables()) {
502
+ if (errorCode === 1146 && (await this.createTables())) {
307
503
  // If the tables don't exist yet, create them.
308
504
  for (let etype of etypes) {
309
- this.createTables(etype);
505
+ await this.createTables(etype);
310
506
  }
311
507
  try {
312
508
  return await runQuery();
313
509
  } catch (e2: any) {
314
510
  throw new QueryFailedError(
315
511
  'Query failed: ' + e2?.errno + ' - ' + e2?.message,
316
- query
512
+ query,
513
+ e2?.errno,
317
514
  );
318
515
  }
516
+ } else if (errorCode === 1062) {
517
+ throw new EntityUniqueConstraintError(`Unique constraint violation.`);
319
518
  } else if (errorCode === 2006) {
320
519
  // If the MySQL server disconnected, reconnect to it.
321
- if (!this.connect()) {
520
+ if (!(await this.connect())) {
322
521
  throw new QueryFailedError(
323
522
  'Query failed: ' + e?.errno + ' - ' + e?.message,
324
- query
523
+ query,
524
+ e?.errno,
325
525
  );
326
526
  }
327
527
  try {
@@ -329,60 +529,21 @@ export default class MySQLDriver extends NymphDriver {
329
529
  } catch (e2: any) {
330
530
  throw new QueryFailedError(
331
531
  'Query failed: ' + e2?.errno + ' - ' + e2?.message,
332
- query
333
- );
334
- }
335
- } else {
336
- throw e;
337
- }
338
- }
339
- }
340
-
341
- private querySync<T extends () => any>(
342
- runQuery: T,
343
- query: string,
344
- etypes: string[] = []
345
- ): ReturnType<T> {
346
- try {
347
- return runQuery();
348
- } catch (e: any) {
349
- const errorCode = e?.errno;
350
- if (errorCode === 1146 && this.createTables()) {
351
- // If the tables don't exist yet, create them.
352
- for (let etype of etypes) {
353
- this.createTables(etype);
354
- }
355
- try {
356
- return runQuery();
357
- } catch (e2: any) {
358
- throw new QueryFailedError(
359
- 'Query failed: ' + e2?.errno + ' - ' + e2?.message,
360
- query
361
- );
362
- }
363
- } else if (errorCode === 2006) {
364
- // If the MySQL server disconnected, reconnect to it.
365
- if (!this.connect()) {
366
- throw new QueryFailedError(
367
- 'Query failed: ' + e?.errno + ' - ' + e?.message,
368
- query
369
- );
370
- }
371
- try {
372
- return runQuery();
373
- } catch (e2: any) {
374
- throw new QueryFailedError(
375
- 'Query failed: ' + e2?.errno + ' - ' + e2?.message,
376
- query
532
+ query,
533
+ e2?.errno,
377
534
  );
378
535
  }
379
536
  } else {
380
- throw e;
537
+ throw new QueryFailedError(
538
+ 'Query failed: ' + e?.errno + ' - ' + e?.message,
539
+ query,
540
+ e?.errno,
541
+ );
381
542
  }
382
543
  }
383
544
  }
384
545
 
385
- private queryIter(
546
+ private queryArray(
386
547
  query: string,
387
548
  {
388
549
  etypes = [],
@@ -390,82 +551,42 @@ export default class MySQLDriver extends NymphDriver {
390
551
  }: {
391
552
  etypes?: string[];
392
553
  params?: { [k: string]: any };
393
- } = {}
554
+ } = {},
394
555
  ) {
395
556
  const { query: newQuery, params: newParams } = this.translateQuery(
396
557
  query,
397
- params
558
+ params,
398
559
  );
399
560
  return this.query(
400
561
  async () => {
401
- const results: any = await new Promise((resolve, reject) => {
402
- try {
403
- (this.transaction?.connection ?? this.link).query(
404
- newQuery,
405
- newParams,
406
- (error, results) => {
407
- if (error) {
408
- reject(error);
409
- }
562
+ const results: any = await new Promise(async (resolve, reject) => {
563
+ // Only do one query at a time in transations.
564
+ let myResolve: (value: void | PromiseLike<void>) => void = () => {};
565
+ const myPromise = new Promise<void>((resolve) => {
566
+ myResolve = resolve;
567
+ });
568
+ if (this.transaction) {
569
+ const latestPromise = this.transaction.latestPromise;
570
+ this.transaction.latestPromise = myPromise;
571
+ await latestPromise;
572
+ }
573
+ (this.transaction?.connection ?? this.link).query(
574
+ newQuery,
575
+ newParams,
576
+ (error, results) => {
577
+ if (error) {
578
+ reject(error);
579
+ } else {
410
580
  resolve(results);
411
581
  }
412
- );
413
- } catch (e) {
414
- reject(e);
415
- }
582
+ myResolve();
583
+ },
584
+ );
416
585
  });
417
586
  return results;
418
587
  },
419
588
  `${query} -- ${JSON.stringify(params)}`,
420
- etypes
421
- );
422
- }
423
-
424
- private queryIterSync(
425
- query: string,
426
- {
427
- etypes = [],
428
- params = {},
429
- }: { etypes?: string[]; params?: { [k: string]: any } } = {}
430
- ) {
431
- const { query: newQuery, params: newParams } = this.translateQuery(
432
- query,
433
- params
434
- );
435
- return this.querySync(
436
- () => {
437
- const output = cp.spawnSync(
438
- process.argv0,
439
- [__dirname + '/runMysqlSync.js'],
440
- {
441
- input: JSON.stringify({
442
- mysqlConfig: this.mysqlConfig,
443
- query: newQuery,
444
- params: newParams,
445
- }),
446
- timeout: 30000,
447
- maxBuffer: 100 * 1024 * 1024,
448
- encoding: 'utf8',
449
- windowsHide: true,
450
- }
451
- );
452
- try {
453
- const { results } = JSON.parse(output.stdout);
454
- return results;
455
- } catch (e) {
456
- // Do nothing.
457
- }
458
- if (output.status === 0) {
459
- throw new Error('Unknown parse error.');
460
- }
461
- const err = JSON.parse(output.stderr);
462
- const e = new Error(err.name);
463
- for (const name in err) {
464
- (e as any)[name] = err[name];
465
- }
466
- },
467
- `${query} -- ${JSON.stringify(params)}`,
468
- etypes
589
+ etypes,
469
590
  );
470
591
  }
471
592
 
@@ -477,34 +598,42 @@ export default class MySQLDriver extends NymphDriver {
477
598
  }: {
478
599
  etypes?: string[];
479
600
  params?: { [k: string]: any };
480
- } = {}
601
+ } = {},
481
602
  ) {
482
603
  const { query: newQuery, params: newParams } = this.translateQuery(
483
604
  query,
484
- params
605
+ params,
485
606
  );
486
607
  return this.query(
487
608
  async () => {
488
- const results: any = await new Promise((resolve, reject) => {
489
- try {
490
- (this.transaction?.connection ?? this.link).query(
491
- newQuery,
492
- newParams,
493
- (error, results) => {
494
- if (error) {
495
- reject(error);
496
- }
609
+ const results: any = await new Promise(async (resolve, reject) => {
610
+ // Only do one query at a time in transations.
611
+ let myResolve: (value: void | PromiseLike<void>) => void = () => {};
612
+ const myPromise = new Promise<void>((resolve) => {
613
+ myResolve = resolve;
614
+ });
615
+ if (this.transaction) {
616
+ const latestPromise = this.transaction.latestPromise;
617
+ this.transaction.latestPromise = myPromise;
618
+ await latestPromise;
619
+ }
620
+ (this.transaction?.connection ?? this.link).query(
621
+ newQuery,
622
+ newParams,
623
+ (error, results) => {
624
+ if (error) {
625
+ reject(error);
626
+ } else {
497
627
  resolve(results);
498
628
  }
499
- );
500
- } catch (e) {
501
- reject(e);
502
- }
629
+ myResolve();
630
+ },
631
+ );
503
632
  });
504
633
  return results[0];
505
634
  },
506
635
  `${query} -- ${JSON.stringify(params)}`,
507
- etypes
636
+ etypes,
508
637
  );
509
638
  }
510
639
 
@@ -513,92 +642,55 @@ export default class MySQLDriver extends NymphDriver {
513
642
  {
514
643
  etypes = [],
515
644
  params = {},
645
+ transaction,
516
646
  }: {
517
647
  etypes?: string[];
518
648
  params?: { [k: string]: any };
519
- } = {}
649
+ transaction?: MySQLDriverTransaction;
650
+ } = {},
520
651
  ) {
521
652
  const { query: newQuery, params: newParams } = this.translateQuery(
522
653
  query,
523
- params
654
+ params,
524
655
  );
525
656
  return this.query(
526
657
  async () => {
527
- const results: any = await new Promise((resolve, reject) => {
528
- try {
529
- (this.transaction?.connection ?? this.link).query(
530
- newQuery,
531
- newParams,
532
- (error, results) => {
533
- if (error) {
534
- reject(error);
535
- }
658
+ const results: any = await new Promise(async (resolve, reject) => {
659
+ // Only do one query at a time in transations.
660
+ let myResolve: (value: void | PromiseLike<void>) => void = () => {};
661
+ const myPromise = new Promise<void>((resolve) => {
662
+ myResolve = resolve;
663
+ });
664
+ const trans = transaction ?? this.transaction;
665
+ if (trans) {
666
+ const latestPromise = trans.latestPromise;
667
+ trans.latestPromise = myPromise;
668
+ await latestPromise;
669
+ }
670
+ (trans?.connection ?? this.link).query(
671
+ newQuery,
672
+ newParams,
673
+ (error, results) => {
674
+ if (error) {
675
+ reject(error);
676
+ } else {
536
677
  resolve(results);
537
678
  }
538
- );
539
- } catch (e) {
540
- reject(e);
541
- }
679
+ myResolve();
680
+ },
681
+ );
542
682
  });
543
683
  return { changes: results.changedRows ?? 0 };
544
684
  },
545
685
  `${query} -- ${JSON.stringify(params)}`,
546
- etypes
547
- );
548
- }
549
-
550
- private queryRunSync(
551
- query: string,
552
- {
553
- etypes = [],
554
- params = {},
555
- }: { etypes?: string[]; params?: { [k: string]: any } } = {}
556
- ) {
557
- const { query: newQuery, params: newParams } = this.translateQuery(
558
- query,
559
- params
560
- );
561
- return this.querySync(
562
- () => {
563
- const output = cp.spawnSync(
564
- process.argv0,
565
- [__dirname + '/runMysqlSync.js'],
566
- {
567
- input: JSON.stringify({
568
- mysqlConfig: this.mysqlConfig,
569
- query: newQuery,
570
- params: newParams,
571
- }),
572
- timeout: 30000,
573
- maxBuffer: 100 * 1024 * 1024,
574
- encoding: 'utf8',
575
- windowsHide: true,
576
- }
577
- );
578
- try {
579
- const { results } = JSON.parse(output.stdout);
580
- return { changes: results.changedRows ?? 0 };
581
- } catch (e) {
582
- // Do nothing.
583
- }
584
- if (output.status === 0) {
585
- throw new Error('Unknown parse error.');
586
- }
587
- const err = JSON.parse(output.stderr);
588
- const e = new Error(err.name);
589
- for (const name in err) {
590
- (e as any)[name] = err[name];
591
- }
592
- },
593
- `${query} -- ${JSON.stringify(params)}`,
594
- etypes
686
+ etypes,
595
687
  );
596
688
  }
597
689
 
598
690
  public async commit(name: string) {
599
691
  if (name == null || typeof name !== 'string' || name.length === 0) {
600
692
  throw new InvalidParametersError(
601
- 'Transaction commit attempted without a name.'
693
+ 'Transaction commit attempted without a name.',
602
694
  );
603
695
  }
604
696
  if (!this.transaction || this.transaction.count === 0) {
@@ -620,7 +712,7 @@ export default class MySQLDriver extends NymphDriver {
620
712
 
621
713
  public async deleteEntityByID(
622
714
  guid: string,
623
- className?: EntityConstructor | string | null
715
+ className?: EntityConstructor | string | null,
624
716
  ) {
625
717
  let EntityClass: EntityConstructor;
626
718
  if (typeof className === 'string' || className == null) {
@@ -634,161 +726,440 @@ export default class MySQLDriver extends NymphDriver {
634
726
  try {
635
727
  await this.queryRun(
636
728
  `DELETE FROM ${MySQLDriver.escape(
637
- `${this.prefix}entities_${etype}`
729
+ `${this.prefix}entities_${etype}`,
638
730
  )} WHERE \`guid\`=UNHEX(@guid);`,
639
731
  {
640
732
  etypes: [etype],
641
733
  params: {
642
734
  guid,
643
735
  },
644
- }
736
+ },
645
737
  );
646
738
  await this.queryRun(
647
739
  `DELETE FROM ${MySQLDriver.escape(
648
- `${this.prefix}data_${etype}`
740
+ `${this.prefix}data_${etype}`,
649
741
  )} WHERE \`guid\`=UNHEX(@guid);`,
650
742
  {
651
743
  etypes: [etype],
652
744
  params: {
653
745
  guid,
654
746
  },
655
- }
747
+ },
656
748
  );
657
749
  await this.queryRun(
658
750
  `DELETE FROM ${MySQLDriver.escape(
659
- `${this.prefix}comparisons_${etype}`
751
+ `${this.prefix}references_${etype}`,
660
752
  )} WHERE \`guid\`=UNHEX(@guid);`,
661
753
  {
662
754
  etypes: [etype],
663
755
  params: {
664
756
  guid,
665
757
  },
666
- }
758
+ },
667
759
  );
668
760
  await this.queryRun(
669
761
  `DELETE FROM ${MySQLDriver.escape(
670
- `${this.prefix}references_${etype}`
762
+ `${this.prefix}tokens_${etype}`,
671
763
  )} WHERE \`guid\`=UNHEX(@guid);`,
672
764
  {
673
765
  etypes: [etype],
674
766
  params: {
675
767
  guid,
676
768
  },
677
- }
769
+ },
770
+ );
771
+ await this.queryRun(
772
+ `DELETE FROM ${MySQLDriver.escape(
773
+ `${this.prefix}uniques_${etype}`,
774
+ )} WHERE \`guid\`=UNHEX(@guid);`,
775
+ {
776
+ etypes: [etype],
777
+ params: {
778
+ guid,
779
+ },
780
+ },
678
781
  );
679
- await this.commit('nymph-delete');
680
- // Remove any cached versions of this entity.
681
- if (this.nymph.config.cache) {
682
- this.cleanCache(guid);
683
- }
684
- return true;
685
782
  } catch (e: any) {
783
+ this.nymph.config.debugError('mysql', `Delete entity error: "${e}"`);
686
784
  await this.rollback('nymph-delete');
687
785
  throw e;
688
786
  }
787
+
788
+ await this.commit('nymph-delete');
789
+ return true;
689
790
  }
690
791
 
691
792
  public async deleteUID(name: string) {
692
793
  if (!name) {
693
794
  throw new InvalidParametersError('Name not given for UID');
694
795
  }
796
+ if (name.length > 128) {
797
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
798
+ }
695
799
  await this.queryRun(
696
800
  `DELETE FROM ${MySQLDriver.escape(
697
- `${this.prefix}uids`
801
+ `${this.prefix}uids`,
698
802
  )} WHERE \`name\`=@name;`,
699
803
  {
700
804
  params: {
701
805
  name,
702
806
  },
703
- }
807
+ },
704
808
  );
705
809
  return true;
706
810
  }
707
811
 
708
- protected async exportEntities(writeLine: (line: string) => void) {
709
- writeLine('#nex2');
710
- writeLine('# Nymph Entity Exchange v2');
711
- writeLine('# http://nymph.io');
712
- writeLine('#');
713
- writeLine('# Generation Time: ' + new Date().toLocaleString());
714
- writeLine('');
812
+ public async getIndexes(etype: string) {
813
+ const indexes: {
814
+ scope: 'data' | 'references' | 'tokens';
815
+ name: string;
816
+ property: string;
817
+ }[] = [];
715
818
 
716
- writeLine('#');
717
- writeLine('# UIDs');
718
- writeLine('#');
719
- writeLine('');
819
+ for (let [scope, suffix] of [
820
+ ['data', '_string_guid'],
821
+ ['references', '_reference_guid'],
822
+ ['tokens', '_token_guid'],
823
+ ] as (
824
+ | ['data', '_string_guid']
825
+ | ['references', '_reference_guid']
826
+ | ['tokens', '_token_guid']
827
+ )[]) {
828
+ const indexDefinitions = await this.queryArray(
829
+ `SHOW INDEXES FROM ${MySQLDriver.escape(
830
+ `${this.prefix}${scope}_${etype}`,
831
+ )} WHERE \`Key_name\` LIKE @pattern AND \`Seq_in_index\`=1;`,
832
+ {
833
+ params: {
834
+ pattern: `${this.prefix}${scope}_${etype}_id_custom_%${suffix}`,
835
+ },
836
+ },
837
+ );
838
+ for (const indexDefinition of indexDefinitions) {
839
+ indexes.push({
840
+ scope,
841
+ name: (indexDefinition.Key_name as string).substring(
842
+ `${this.prefix}${scope}_${etype}_id_custom_`.length,
843
+ indexDefinition.Key_name.length - suffix.length,
844
+ ),
845
+ property:
846
+ ((indexDefinition.Expression as string).match(
847
+ /\s*\(?\s*`?name`?\s*=\s*(?:\w*)\\*'(.*?)\\*'/,
848
+ ) ?? [])[1] ?? '',
849
+ });
850
+ }
851
+ }
852
+
853
+ return indexes;
854
+ }
855
+
856
+ public async addIndex(
857
+ etype: string,
858
+ definition: {
859
+ scope: 'data' | 'references' | 'tokens';
860
+ name: string;
861
+ property: string;
862
+ },
863
+ ) {
864
+ this.checkIndexName(definition.name);
865
+ await this.deleteIndex(etype, definition.scope, definition.name);
866
+ if (definition.scope === 'data') {
867
+ await this.queryRun(
868
+ `CREATE INDEX ${MySQLDriver.escape(
869
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_string_guid`,
870
+ )} USING btree ON ${MySQLDriver.escape(
871
+ `${this.prefix}data_${etype}`,
872
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`string\`(500), \`guid\`);`,
873
+ );
874
+ await this.queryRun(
875
+ `CREATE INDEX ${MySQLDriver.escape(
876
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_number_guid`,
877
+ )} USING btree ON ${MySQLDriver.escape(
878
+ `${this.prefix}data_${etype}`,
879
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`number\`, \`guid\`);`,
880
+ );
881
+ await this.queryRun(
882
+ `CREATE INDEX ${MySQLDriver.escape(
883
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_truthy_guid`,
884
+ )} USING btree ON ${MySQLDriver.escape(
885
+ `${this.prefix}data_${etype}`,
886
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`truthy\`, \`guid\`);`,
887
+ );
888
+ await this.queryRun(
889
+ `CREATE INDEX ${MySQLDriver.escape(
890
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_json_guid`,
891
+ )} USING btree ON ${MySQLDriver.escape(
892
+ `${this.prefix}data_${etype}`,
893
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), (CAST(\`json\` AS CHAR(500)) COLLATE utf8mb4_bin), \`guid\`);`,
894
+ );
895
+ } else if (definition.scope === 'references') {
896
+ await this.queryRun(
897
+ `CREATE INDEX ${MySQLDriver.escape(
898
+ `${this.prefix}references_${etype}_id_custom_${definition.name}_reference_guid`,
899
+ )} USING btree ON ${MySQLDriver.escape(
900
+ `${this.prefix}references_${etype}`,
901
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`reference\`, \`guid\`);`,
902
+ );
903
+ } else if (definition.scope === 'tokens') {
904
+ await this.queryRun(
905
+ `CREATE INDEX ${MySQLDriver.escape(
906
+ `${this.prefix}tokens_${etype}_id_custom_${definition.name}_token_guid`,
907
+ )} USING btree ON ${MySQLDriver.escape(
908
+ `${this.prefix}tokens_${etype}`,
909
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`token\`, \`guid\`);`,
910
+ );
911
+ }
912
+ return true;
913
+ }
914
+
915
+ public async deleteIndex(
916
+ etype: string,
917
+ scope: 'data' | 'references' | 'tokens',
918
+ name: string,
919
+ ) {
920
+ this.checkIndexName(name);
921
+ try {
922
+ if (scope === 'data') {
923
+ await this.queryRun(
924
+ `DROP INDEX ${MySQLDriver.escape(
925
+ `${this.prefix}data_${etype}_id_custom_${name}_string_guid`,
926
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
927
+ );
928
+ await this.queryRun(
929
+ `DROP INDEX ${MySQLDriver.escape(
930
+ `${this.prefix}data_${etype}_id_custom_${name}_number_guid`,
931
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
932
+ );
933
+ await this.queryRun(
934
+ `DROP INDEX ${MySQLDriver.escape(
935
+ `${this.prefix}data_${etype}_id_custom_${name}_truthy_guid`,
936
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
937
+ );
938
+ await this.queryRun(
939
+ `DROP INDEX ${MySQLDriver.escape(
940
+ `${this.prefix}data_${etype}_id_custom_${name}_json_guid`,
941
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
942
+ );
943
+ } else if (scope === 'references') {
944
+ await this.queryRun(
945
+ `DROP INDEX ${MySQLDriver.escape(
946
+ `${this.prefix}references_${etype}_id_custom_${name}_reference_guid`,
947
+ )} ON ${MySQLDriver.escape(`${this.prefix}references_${etype}`)};`,
948
+ );
949
+ } else if (scope === 'tokens') {
950
+ await this.queryRun(
951
+ `DROP INDEX ${MySQLDriver.escape(
952
+ `${this.prefix}tokens_${etype}_id_custom_${name}_token_guid`,
953
+ )} ON ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)};`,
954
+ );
955
+ }
956
+ } catch (e: any) {
957
+ if (e?.errorCode !== 1091) {
958
+ throw e;
959
+ }
960
+ }
961
+ return true;
962
+ }
963
+
964
+ public async getEtypes() {
965
+ const tables = await this.queryArray(
966
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix;',
967
+ {
968
+ params: {
969
+ db: this.config.database,
970
+ prefix: this.prefix + 'entities_' + '%',
971
+ },
972
+ },
973
+ );
974
+ const etypes: string[] = [];
975
+ for (const table of tables) {
976
+ etypes.push(table.table_name.substr((this.prefix + 'entities_').length));
977
+ }
978
+
979
+ return etypes;
980
+ }
981
+
982
+ public async *exportDataIterator(): AsyncGenerator<
983
+ { type: 'comment' | 'uid' | 'entity'; content: string },
984
+ void,
985
+ false | undefined
986
+ > {
987
+ if (
988
+ yield {
989
+ type: 'comment',
990
+ content: `#nex2
991
+ # Nymph Entity Exchange v2
992
+ # http://nymph.io
993
+ #
994
+ # Generation Time: ${new Date().toLocaleString()}
995
+ `,
996
+ }
997
+ ) {
998
+ return;
999
+ }
1000
+
1001
+ if (
1002
+ yield {
1003
+ type: 'comment',
1004
+ content: `
1005
+
1006
+ #
1007
+ # UIDs
1008
+ #
1009
+
1010
+ `,
1011
+ }
1012
+ ) {
1013
+ return;
1014
+ }
720
1015
 
721
1016
  // Export UIDs.
722
- let uids = await this.queryIter(
1017
+ let uids = await this.queryArray(
723
1018
  `SELECT * FROM ${MySQLDriver.escape(
724
- `${this.prefix}uids`
725
- )} ORDER BY \`name\`;`
1019
+ `${this.prefix}uids`,
1020
+ )} ORDER BY \`name\`;`,
726
1021
  );
727
1022
  for (const uid of uids) {
728
- writeLine(`<${uid.name}>[${uid.cur_uid}]`);
1023
+ if (yield { type: 'uid', content: `<${uid.name}>[${uid.cur_uid}]\n` }) {
1024
+ return;
1025
+ }
729
1026
  }
730
1027
 
731
- writeLine('');
732
- writeLine('#');
733
- writeLine('# Entities');
734
- writeLine('#');
735
- writeLine('');
1028
+ if (
1029
+ yield {
1030
+ type: 'comment',
1031
+ content: `
736
1032
 
737
- // Get the etypes.
738
- const tables = await this.queryIter('SHOW TABLES;');
739
- const etypes = [];
740
- for (const tableRow of tables) {
741
- const table = tableRow[Object.keys(tableRow)[0]];
742
- if (table.startsWith(this.prefix + 'entities_')) {
743
- etypes.push(table.substr((this.prefix + 'entities_').length));
1033
+ #
1034
+ # Entities
1035
+ #
1036
+
1037
+ `,
744
1038
  }
1039
+ ) {
1040
+ return;
745
1041
  }
746
1042
 
1043
+ // Get the etypes.
1044
+ const etypes = await this.getEtypes();
1045
+
747
1046
  for (const etype of etypes) {
748
1047
  // Export entities.
749
- const dataIterator = (
750
- await this.queryIter(
751
- `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\`
1048
+ const entityIterator = this.exportEntityInternal(etype);
1049
+ for await (let content of entityIterator) {
1050
+ yield { type: 'entity', content };
1051
+ }
1052
+ }
1053
+ }
1054
+
1055
+ public async exportEntity(etype: string, guid: string): Promise<string> {
1056
+ const entityIterator = this.exportEntityInternal(etype, guid);
1057
+ let exportContent = '';
1058
+ for await (let content of entityIterator) {
1059
+ exportContent += content;
1060
+ }
1061
+
1062
+ return exportContent;
1063
+ }
1064
+
1065
+ private async *exportEntityInternal(
1066
+ etype: string,
1067
+ guid?: string,
1068
+ ): AsyncGenerator<string, void, false | undefined> {
1069
+ // Export entities.
1070
+ const dataIterator = (
1071
+ await this.queryArray(
1072
+ `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\`
752
1073
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} e
753
1074
  LEFT JOIN ${MySQLDriver.escape(
754
- `${this.prefix}data_${etype}`
755
- )} d ON e.\`guid\`=d.\`guid\`
756
- INNER JOIN ${MySQLDriver.escape(
757
- `${this.prefix}comparisons_${etype}`
758
- )} c ON d.\`guid\`=c.\`guid\` AND d.\`name\`=c.\`name\`
759
- ORDER BY e.\`guid\`;`
760
- )
761
- )[Symbol.iterator]();
762
- let datum = dataIterator.next();
763
- while (!datum.done) {
764
- const guid = datum.value.guid;
765
- const tags = datum.value.tags.slice(1, -1).split(' ').join(',');
766
- const cdate = datum.value.cdate;
767
- const mdate = datum.value.mdate;
768
- writeLine(`{${guid}}<${etype}>[${tags}]`);
769
- writeLine(`\tcdate=${JSON.stringify(cdate)}`);
770
- writeLine(`\tmdate=${JSON.stringify(mdate)}`);
771
- if (datum.value.dname != null) {
772
- // This do will keep going and adding the data until the
773
- // next entity is reached. $row will end on the next entity.
774
- do {
775
- const value =
776
- datum.value.dvalue === 'N'
777
- ? JSON.stringify(datum.value.number)
778
- : datum.value.dvalue === 'S'
1075
+ `${this.prefix}data_${etype}`,
1076
+ )} d ON e.\`guid\`=d.\`guid\`${guid == null ? '' : ` WHERE e.\`guid\`=UNHEX(@guid)`}
1077
+ ORDER BY e.\`guid\`, d.\`name\`;`,
1078
+ guid == null ? undefined : { params: { guid } },
1079
+ )
1080
+ )[Symbol.iterator]();
1081
+ let datum = dataIterator.next();
1082
+ while (!datum.done) {
1083
+ const guid = datum.value.guid;
1084
+ const tags = MySQLDriver.unescapeTags(
1085
+ datum.value.tags
1086
+ .slice(1, -1)
1087
+ .split(' ')
1088
+ .filter((tag: string) => tag),
1089
+ ).join(',');
1090
+ const cdate = datum.value.cdate;
1091
+ const mdate = datum.value.mdate;
1092
+ const user = datum.value.user;
1093
+ const group = datum.value.group;
1094
+ const acUser = datum.value.acUser;
1095
+ const acGroup = datum.value.acGroup;
1096
+ const acOther = datum.value.acOther;
1097
+ const acRead = datum.value.acRead?.slice(1, -1).split(' ');
1098
+ const acWrite = datum.value.acWrite?.slice(1, -1).split(' ');
1099
+ const acFull = datum.value.acFull?.slice(1, -1).split(' ');
1100
+ let currentEntityExport: string[] = [];
1101
+ currentEntityExport.push(
1102
+ `{${guid}}<${etype}>[${tags.replace(/\n/g, () => '\\n')}]`,
1103
+ );
1104
+ currentEntityExport.push(`\tcdate=${JSON.stringify(cdate)}`);
1105
+ currentEntityExport.push(`\tmdate=${JSON.stringify(mdate)}`);
1106
+ if (this.nymph.tilmeld != null) {
1107
+ if (user != null) {
1108
+ currentEntityExport.push(
1109
+ `\tuser=${JSON.stringify(['nymph_entity_reference', user, 'User'])}`,
1110
+ );
1111
+ }
1112
+ if (group != null) {
1113
+ currentEntityExport.push(
1114
+ `\tgroup=${JSON.stringify(['nymph_entity_reference', group, 'Group'])}`,
1115
+ );
1116
+ }
1117
+ if (acUser != null) {
1118
+ currentEntityExport.push(`\tacUser=${JSON.stringify(acUser)}`);
1119
+ }
1120
+ if (acGroup != null) {
1121
+ currentEntityExport.push(`\tacGroup=${JSON.stringify(acGroup)}`);
1122
+ }
1123
+ if (acOther != null) {
1124
+ currentEntityExport.push(`\tacOther=${JSON.stringify(acOther)}`);
1125
+ }
1126
+ if (acRead != null) {
1127
+ currentEntityExport.push(`\tacRead=${JSON.stringify(acRead)}`);
1128
+ }
1129
+ if (acWrite != null) {
1130
+ currentEntityExport.push(`\tacWrite=${JSON.stringify(acWrite)}`);
1131
+ }
1132
+ if (acFull != null) {
1133
+ currentEntityExport.push(`\tacFull=${JSON.stringify(acFull)}`);
1134
+ }
1135
+ }
1136
+ if (datum.value.name != null) {
1137
+ // This do will keep going and adding the data until the
1138
+ // next entity is reached. $row will end on the next entity.
1139
+ do {
1140
+ const value =
1141
+ datum.value.value === 'N'
1142
+ ? JSON.stringify(datum.value.number)
1143
+ : datum.value.value === 'S'
779
1144
  ? JSON.stringify(datum.value.string)
780
- : datum.value.dvalue;
781
- writeLine(`\t${datum.value.dname}=${value}`);
782
- datum = dataIterator.next();
783
- } while (!datum.done && datum.value.guid === guid);
784
- } else {
785
- // Make sure that datum is incremented :)
1145
+ : datum.value.value === 'J'
1146
+ ? JSON.stringify(datum.value.json)
1147
+ : datum.value.value;
1148
+ currentEntityExport.push(
1149
+ `\t${datum.value.name.replace(/\n/g, () => '\\n')}=${value}`,
1150
+ );
786
1151
  datum = dataIterator.next();
787
- }
1152
+ } while (!datum.done && datum.value.guid === guid);
1153
+ } else {
1154
+ // Make sure that datum is incremented :)
1155
+ datum = dataIterator.next();
788
1156
  }
789
- }
1157
+ currentEntityExport.push('');
790
1158
 
791
- return;
1159
+ if (yield currentEntityExport.join('\n')) {
1160
+ return;
1161
+ }
1162
+ }
792
1163
  }
793
1164
 
794
1165
  /**
@@ -809,22 +1180,23 @@ export default class MySQLDriver extends NymphDriver {
809
1180
  params: { [k: string]: any } = {},
810
1181
  subquery = false,
811
1182
  tableSuffix = '',
812
- etypes: string[] = []
1183
+ etypes: string[] = [],
1184
+ guidSelector: string | undefined = undefined,
1185
+ guidExplicitSelector: ((guid: string) => string) | undefined = undefined,
813
1186
  ) {
814
1187
  if (typeof options.class?.alterOptions === 'function') {
815
1188
  options = options.class.alterOptions(options);
816
1189
  }
817
1190
  const eTable = `e${tableSuffix}`;
818
1191
  const dTable = `d${tableSuffix}`;
819
- const cTable = `c${tableSuffix}`;
820
1192
  const fTable = `f${tableSuffix}`;
821
1193
  const ieTable = `ie${tableSuffix}`;
822
1194
  const countTable = `count${tableSuffix}`;
823
1195
  const sTable = `s${tableSuffix}`;
824
- const sort = options.sort ?? 'cdate';
1196
+ const sort = options.sort == null ? 'cdate' : `${options.sort}`;
825
1197
  const queryParts = this.iterateSelectorsForQuery(
826
1198
  formattedSelectors,
827
- (key, value, typeIsOr, typeIsNot) => {
1199
+ ({ key, value, typeIsOr, typeIsNot }) => {
828
1200
  const clauseNot = key.startsWith('!');
829
1201
  let curQuery = '';
830
1202
  for (const curValue of value) {
@@ -855,12 +1227,13 @@ export default class MySQLDriver extends NymphDriver {
855
1227
  }
856
1228
  const tag = `param${++count.i}`;
857
1229
  curQuery += ieTable + '.`tags` NOT REGEXP @' + tag;
858
- params[tag] = ' ' + curTag + ' ';
1230
+ params[tag] = ' ' + MySQLDriver.escapeTag(curTag) + ' ';
859
1231
  }
860
1232
  } else {
861
1233
  const tag = `param${++count.i}`;
862
1234
  curQuery += ieTable + '.`tags` NOT REGEXP @' + tag;
863
- params[tag] = ' (' + curValue.join('|') + ') ';
1235
+ params[tag] =
1236
+ ' (' + MySQLDriver.escapeTags(curValue).join('|') + ') ';
864
1237
  }
865
1238
  } else {
866
1239
  if (curQuery) {
@@ -869,7 +1242,8 @@ export default class MySQLDriver extends NymphDriver {
869
1242
  const groupQueryParam = `param${++count.i}`;
870
1243
  let groupQuery = '';
871
1244
  for (const curTag of curValue) {
872
- groupQuery += (typeIsOr ? ' ' : ' +') + curTag;
1245
+ groupQuery +=
1246
+ (typeIsOr ? ' ' : ' +') + MySQLDriver.escapeTag(curTag);
873
1247
  }
874
1248
  curQuery +=
875
1249
  'MATCH (' +
@@ -886,17 +1260,39 @@ export default class MySQLDriver extends NymphDriver {
886
1260
  if (curQuery) {
887
1261
  curQuery += typeIsOr ? ' OR ' : ' AND ';
888
1262
  }
889
- const name = `param${++count.i}`;
890
- curQuery +=
891
- ieTable +
892
- '.`guid` ' +
893
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
894
- 'IN (SELECT `guid` FROM ' +
895
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
896
- ' WHERE `name`=@' +
897
- name +
898
- ')';
899
- params[name] = curVar;
1263
+ if (
1264
+ curVar === 'cdate' ||
1265
+ curVar === 'mdate' ||
1266
+ (this.nymph.tilmeld != null &&
1267
+ (curVar === 'user' ||
1268
+ curVar === 'group' ||
1269
+ curVar === 'acUser' ||
1270
+ curVar === 'acGroup' ||
1271
+ curVar === 'acOther' ||
1272
+ curVar === 'acRead' ||
1273
+ curVar === 'acWrite' ||
1274
+ curVar === 'acFull'))
1275
+ ) {
1276
+ curQuery +=
1277
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1278
+ '(' +
1279
+ ieTable +
1280
+ '.' +
1281
+ MySQLDriver.escape(curVar) +
1282
+ ' IS NOT NULL)';
1283
+ } else {
1284
+ const name = `param${++count.i}`;
1285
+ curQuery +=
1286
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1287
+ 'EXISTS (SELECT `guid` FROM ' +
1288
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1289
+ ' WHERE `guid`=' +
1290
+ ieTable +
1291
+ '.`guid` AND `name`=@' +
1292
+ name +
1293
+ ')';
1294
+ params[name] = curVar;
1295
+ }
900
1296
  }
901
1297
  break;
902
1298
  case 'truthy':
@@ -905,28 +1301,35 @@ export default class MySQLDriver extends NymphDriver {
905
1301
  if (curQuery) {
906
1302
  curQuery += typeIsOr ? ' OR ' : ' AND ';
907
1303
  }
908
- if (curVar === 'cdate') {
909
- curQuery +=
910
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
911
- '(' +
912
- ieTable +
913
- '.`cdate` NOT NULL)';
914
- break;
915
- } else if (curVar === 'mdate') {
1304
+ if (
1305
+ curVar === 'cdate' ||
1306
+ curVar === 'mdate' ||
1307
+ (this.nymph.tilmeld != null &&
1308
+ (curVar === 'user' ||
1309
+ curVar === 'group' ||
1310
+ curVar === 'acUser' ||
1311
+ curVar === 'acGroup' ||
1312
+ curVar === 'acOther' ||
1313
+ curVar === 'acRead' ||
1314
+ curVar === 'acWrite' ||
1315
+ curVar === 'acFull'))
1316
+ ) {
916
1317
  curQuery +=
917
1318
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
918
1319
  '(' +
919
1320
  ieTable +
920
- '.`mdate` NOT NULL)';
921
- break;
1321
+ '.' +
1322
+ MySQLDriver.escape(curVar) +
1323
+ ' IS NOT NULL)';
922
1324
  } else {
923
1325
  const name = `param${++count.i}`;
924
1326
  curQuery +=
925
1327
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1328
+ 'EXISTS (SELECT `guid` FROM ' +
1329
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1330
+ ' WHERE `guid`=' +
926
1331
  ieTable +
927
- '.`guid` IN (SELECT `guid` FROM ' +
928
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
929
- ' WHERE `name`=@' +
1332
+ '.`guid` AND `name`=@' +
930
1333
  name +
931
1334
  ' AND `truthy`=TRUE)';
932
1335
  params[name] = curVar;
@@ -935,34 +1338,65 @@ export default class MySQLDriver extends NymphDriver {
935
1338
  break;
936
1339
  case 'equal':
937
1340
  case '!equal':
938
- if (curValue[0] === 'cdate') {
1341
+ if (
1342
+ curValue[0] === 'cdate' ||
1343
+ curValue[0] === 'mdate' ||
1344
+ (this.nymph.tilmeld != null &&
1345
+ (curValue[0] === 'acUser' ||
1346
+ curValue[0] === 'acGroup' ||
1347
+ curValue[0] === 'acOther'))
1348
+ ) {
939
1349
  if (curQuery) {
940
1350
  curQuery += typeIsOr ? ' OR ' : ' AND ';
941
1351
  }
942
- const cdate = `param${++count.i}`;
1352
+ const value = `param${++count.i}`;
943
1353
  curQuery +=
944
1354
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
945
1355
  ieTable +
946
- '.`cdate`=@' +
947
- cdate;
948
- params[cdate] = isNaN(Number(curValue[1]))
1356
+ '.' +
1357
+ MySQLDriver.escape(curValue[0]) +
1358
+ '=@' +
1359
+ value;
1360
+ params[value] = isNaN(Number(curValue[1]))
949
1361
  ? null
950
1362
  : Number(curValue[1]);
951
- break;
952
- } else if (curValue[0] === 'mdate') {
1363
+ } else if (
1364
+ this.nymph.tilmeld != null &&
1365
+ (curValue[0] === 'user' || curValue[0] === 'group')
1366
+ ) {
953
1367
  if (curQuery) {
954
1368
  curQuery += typeIsOr ? ' OR ' : ' AND ';
955
1369
  }
956
- const mdate = `param${++count.i}`;
1370
+ const value = `param${++count.i}`;
957
1371
  curQuery +=
958
1372
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
959
1373
  ieTable +
960
- '.`mdate`=@' +
961
- mdate;
962
- params[mdate] = isNaN(Number(curValue[1]))
963
- ? null
964
- : Number(curValue[1]);
965
- break;
1374
+ '.' +
1375
+ MySQLDriver.escape(curValue[0]) +
1376
+ '=UNHEX(@' +
1377
+ value +
1378
+ ')';
1379
+ params[value] = `${curValue[1]}`;
1380
+ } else if (
1381
+ this.nymph.tilmeld != null &&
1382
+ (curValue[0] === 'acRead' ||
1383
+ curValue[0] === 'acWrite' ||
1384
+ curValue[0] === 'acFull')
1385
+ ) {
1386
+ if (curQuery) {
1387
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1388
+ }
1389
+ const value = `param${++count.i}`;
1390
+ curQuery +=
1391
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1392
+ ieTable +
1393
+ '.' +
1394
+ MySQLDriver.escape(curValue[0]) +
1395
+ '=@' +
1396
+ value;
1397
+ params[value] = Array.isArray(curValue[1])
1398
+ ? ' ' + MySQLDriver.escapeTags(curValue[1]).join(' ') + ' '
1399
+ : '';
966
1400
  } else if (typeof curValue[1] === 'number') {
967
1401
  if (curQuery) {
968
1402
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -971,10 +1405,11 @@ export default class MySQLDriver extends NymphDriver {
971
1405
  const value = `param${++count.i}`;
972
1406
  curQuery +=
973
1407
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1408
+ 'EXISTS (SELECT `guid` FROM ' +
1409
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1410
+ ' WHERE `guid`=' +
974
1411
  ieTable +
975
- '.`guid` IN (SELECT `guid` FROM ' +
976
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
977
- ' WHERE `name`=@' +
1412
+ '.`guid` AND `name`=@' +
978
1413
  name +
979
1414
  ' AND `number`=@' +
980
1415
  value +
@@ -989,10 +1424,11 @@ export default class MySQLDriver extends NymphDriver {
989
1424
  const value = `param${++count.i}`;
990
1425
  curQuery +=
991
1426
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1427
+ 'EXISTS (SELECT `guid` FROM ' +
1428
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1429
+ ' WHERE `guid`=' +
992
1430
  ieTable +
993
- '.`guid` IN (SELECT `guid` FROM ' +
994
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
995
- ' WHERE `name`=@' +
1431
+ '.`guid` AND `name`=@' +
996
1432
  name +
997
1433
  ' AND `string`=@' +
998
1434
  value +
@@ -1014,136 +1450,313 @@ export default class MySQLDriver extends NymphDriver {
1014
1450
  }
1015
1451
  const name = `param${++count.i}`;
1016
1452
  const value = `param${++count.i}`;
1017
- curQuery +=
1018
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1019
- ieTable +
1020
- '.`guid` IN (SELECT `guid` FROM ' +
1021
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
1022
- ' WHERE `name`=@' +
1023
- name +
1024
- ' AND `value`=@' +
1025
- value +
1026
- ')';
1453
+ if (svalue.length < 500) {
1454
+ curQuery +=
1455
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1456
+ 'EXISTS (SELECT `guid` FROM ' +
1457
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1458
+ ' WHERE `guid`=' +
1459
+ ieTable +
1460
+ '.`guid` AND `name`=@' +
1461
+ name +
1462
+ ' AND (CAST(`json` AS CHAR(500)) COLLATE utf8mb4_bin)=CAST(CAST(@' +
1463
+ value +
1464
+ ' AS JSON) AS CHAR(500)))';
1465
+ } else {
1466
+ curQuery +=
1467
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1468
+ 'EXISTS (SELECT `guid` FROM ' +
1469
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1470
+ ' WHERE `guid`=' +
1471
+ ieTable +
1472
+ '.`guid` AND `name`=@' +
1473
+ name +
1474
+ ' AND `json`=CAST(@' +
1475
+ value +
1476
+ ' AS JSON))';
1477
+ }
1027
1478
  params[name] = curValue[0];
1028
1479
  params[value] = svalue;
1029
1480
  }
1030
1481
  break;
1031
1482
  case 'contain':
1032
1483
  case '!contain':
1033
- if (curValue[0] === 'cdate') {
1484
+ if (
1485
+ curValue[0] === 'cdate' ||
1486
+ curValue[0] === 'mdate' ||
1487
+ (this.nymph.tilmeld != null &&
1488
+ (curValue[0] === 'acUser' ||
1489
+ curValue[0] === 'acGroup' ||
1490
+ curValue[0] === 'acOther'))
1491
+ ) {
1034
1492
  if (curQuery) {
1035
1493
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1036
1494
  }
1037
- const cdate = `param${++count.i}`;
1495
+ const value = `param${++count.i}`;
1038
1496
  curQuery +=
1039
1497
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1040
1498
  ieTable +
1041
- '.`cdate`=' +
1042
- cdate;
1043
- params[cdate] = isNaN(Number(curValue[1]))
1499
+ '.' +
1500
+ MySQLDriver.escape(curValue[0]) +
1501
+ '=@' +
1502
+ value;
1503
+ params[value] = isNaN(Number(curValue[1]))
1044
1504
  ? null
1045
1505
  : Number(curValue[1]);
1046
- break;
1047
- } else if (curValue[0] === 'mdate') {
1506
+ } else if (
1507
+ this.nymph.tilmeld != null &&
1508
+ (curValue[0] === 'user' || curValue[0] === 'group')
1509
+ ) {
1048
1510
  if (curQuery) {
1049
1511
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1050
1512
  }
1051
- const mdate = `param${++count.i}`;
1513
+ const value = `param${++count.i}`;
1052
1514
  curQuery +=
1053
1515
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1054
1516
  ieTable +
1055
- '.`mdate`=' +
1056
- mdate;
1057
- params[mdate] = isNaN(Number(curValue[1]))
1058
- ? null
1059
- : Number(curValue[1]);
1060
- break;
1517
+ '.' +
1518
+ MySQLDriver.escape(curValue[0]) +
1519
+ '=UNHEX(@' +
1520
+ value +
1521
+ ')';
1522
+ params[value] = `${curValue[1]}`;
1523
+ } else if (
1524
+ this.nymph.tilmeld != null &&
1525
+ (curValue[0] === 'acRead' ||
1526
+ curValue[0] === 'acWrite' ||
1527
+ curValue[0] === 'acFull')
1528
+ ) {
1529
+ if (curQuery) {
1530
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1531
+ }
1532
+ const queryParam = `param${++count.i}`;
1533
+ curQuery +=
1534
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1535
+ 'MATCH (' +
1536
+ ieTable +
1537
+ '.' +
1538
+ MySQLDriver.escape(curValue[0]) +
1539
+ ') AGAINST (@' +
1540
+ queryParam +
1541
+ ' IN BOOLEAN MODE)';
1542
+ params[queryParam] = '+' + curValue[1];
1061
1543
  } else {
1062
1544
  if (curQuery) {
1063
1545
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1064
1546
  }
1065
1547
  let svalue: string;
1066
- let stringValue: string;
1067
1548
  if (
1068
1549
  curValue[1] instanceof Object &&
1069
1550
  typeof curValue[1].toReference === 'function'
1070
1551
  ) {
1071
1552
  svalue = JSON.stringify(curValue[1].toReference());
1072
- stringValue = `${curValue[1].toReference()}`;
1073
1553
  } else {
1074
1554
  svalue = JSON.stringify(curValue[1]);
1075
- stringValue = `${curValue[1]}`;
1076
1555
  }
1077
1556
  const name = `param${++count.i}`;
1078
1557
  const value = `param${++count.i}`;
1079
- if (typeof curValue[1] === 'string') {
1080
- const stringParam = `param${++count.i}`;
1558
+ curQuery +=
1559
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1560
+ 'EXISTS (SELECT `guid` FROM ' +
1561
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1562
+ ' WHERE `guid`=' +
1563
+ ieTable +
1564
+ '.`guid` AND `name`=@' +
1565
+ name +
1566
+ ' AND JSON_CONTAINS(`json`, @' +
1567
+ value +
1568
+ '))';
1569
+ params[name] = curValue[0];
1570
+ params[value] = svalue;
1571
+ }
1572
+ break;
1573
+ case 'search':
1574
+ case '!search':
1575
+ if (
1576
+ curValue[0] === 'cdate' ||
1577
+ curValue[0] === 'mdate' ||
1578
+ (this.nymph.tilmeld != null &&
1579
+ (curValue[0] === 'user' ||
1580
+ curValue[0] === 'group' ||
1581
+ curValue[0] === 'acUser' ||
1582
+ curValue[0] === 'acGroup' ||
1583
+ curValue[0] === 'acOther' ||
1584
+ curValue[0] === 'acRead' ||
1585
+ curValue[0] === 'acWrite' ||
1586
+ curValue[0] === 'acFull'))
1587
+ ) {
1588
+ if (curQuery) {
1589
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1590
+ }
1591
+ curQuery +=
1592
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') + '(FALSE)';
1593
+ } else {
1594
+ if (curQuery) {
1595
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1596
+ }
1597
+
1598
+ const parsedFTSQuery = this.tokenizer.parseSearchQuery(
1599
+ curValue[1],
1600
+ );
1601
+
1602
+ if (!parsedFTSQuery.length) {
1081
1603
  curQuery +=
1082
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1083
- '(' +
1084
- ieTable +
1085
- '.`guid` IN (SELECT `guid` FROM ' +
1086
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
1087
- ' WHERE `name`=@' +
1088
- name +
1089
- ' AND INSTR(`value`, @' +
1090
- value +
1091
- ')) OR ' +
1092
- ieTable +
1093
- '.`guid` IN (SELECT `guid` FROM ' +
1094
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1095
- ' WHERE `name`=@' +
1096
- name +
1097
- ' AND `string`=@' +
1098
- stringParam +
1099
- '))';
1100
- params[stringParam] = stringValue;
1604
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') + '(FALSE)';
1101
1605
  } else {
1606
+ const name = `param${++count.i}`;
1607
+
1608
+ const queryPartToken = (term: SearchTerm) => {
1609
+ const value = `param${++count.i}`;
1610
+ params[value] = term.token;
1611
+ return (
1612
+ 'EXISTS (SELECT `guid` FROM ' +
1613
+ MySQLDriver.escape(this.prefix + 'tokens_' + etype) +
1614
+ ' WHERE `guid`=' +
1615
+ ieTable +
1616
+ '.`guid` AND `name`=@' +
1617
+ name +
1618
+ ' AND `token`=@' +
1619
+ value +
1620
+ (term.nostemmed ? ' AND `stem`=FALSE' : '') +
1621
+ ')'
1622
+ );
1623
+ };
1624
+
1625
+ const queryPartSeries = (series: SearchSeriesTerm) => {
1626
+ const tokenTableSuffix = makeTableSuffix();
1627
+ const tokenParts = series.tokens.map((token, i) => {
1628
+ const value = `param${++count.i}`;
1629
+ params[value] = token.token;
1630
+ return {
1631
+ fromClause:
1632
+ i === 0
1633
+ ? 'FROM ' +
1634
+ MySQLDriver.escape(
1635
+ this.prefix + 'tokens_' + etype,
1636
+ ) +
1637
+ ' t' +
1638
+ tokenTableSuffix +
1639
+ '0'
1640
+ : 'JOIN ' +
1641
+ MySQLDriver.escape(
1642
+ this.prefix + 'tokens_' + etype,
1643
+ ) +
1644
+ ' t' +
1645
+ tokenTableSuffix +
1646
+ i +
1647
+ ' ON t' +
1648
+ tokenTableSuffix +
1649
+ i +
1650
+ '.`guid` = t' +
1651
+ tokenTableSuffix +
1652
+ '0.`guid` AND t' +
1653
+ tokenTableSuffix +
1654
+ i +
1655
+ '.`name` = t' +
1656
+ tokenTableSuffix +
1657
+ '0.`name` AND t' +
1658
+ tokenTableSuffix +
1659
+ i +
1660
+ '.`position` = t' +
1661
+ tokenTableSuffix +
1662
+ '0.`position` + ' +
1663
+ i,
1664
+ whereClause:
1665
+ 't' +
1666
+ tokenTableSuffix +
1667
+ i +
1668
+ '.`token`=@' +
1669
+ value +
1670
+ (token.nostemmed
1671
+ ? ' AND t' + tokenTableSuffix + i + '.`stem`=FALSE'
1672
+ : ''),
1673
+ };
1674
+ });
1675
+ return (
1676
+ 'EXISTS (SELECT t' +
1677
+ tokenTableSuffix +
1678
+ '0.`guid` ' +
1679
+ tokenParts.map((part) => part.fromClause).join(' ') +
1680
+ ' WHERE t' +
1681
+ tokenTableSuffix +
1682
+ '0.`guid`=' +
1683
+ ieTable +
1684
+ '.`guid` AND t' +
1685
+ tokenTableSuffix +
1686
+ '0.`name`=@' +
1687
+ name +
1688
+ ' AND ' +
1689
+ tokenParts.map((part) => part.whereClause).join(' AND ') +
1690
+ ')'
1691
+ );
1692
+ };
1693
+
1694
+ const queryPartTerm = (
1695
+ term:
1696
+ | SearchTerm
1697
+ | SearchOrTerm
1698
+ | SearchNotTerm
1699
+ | SearchSeriesTerm,
1700
+ ): string => {
1701
+ if (term.type === 'series') {
1702
+ return queryPartSeries(term);
1703
+ } else if (term.type === 'not') {
1704
+ return 'NOT ' + queryPartTerm(term.operand);
1705
+ } else if (term.type === 'or') {
1706
+ let queryParts: string[] = [];
1707
+ for (let operand of term.operands) {
1708
+ queryParts.push(queryPartTerm(operand));
1709
+ }
1710
+ return '(' + queryParts.join(' OR ') + ')';
1711
+ }
1712
+ return queryPartToken(term);
1713
+ };
1714
+
1715
+ // Run through the query and add terms.
1716
+ let termStrings: string[] = [];
1717
+ for (let term of parsedFTSQuery) {
1718
+ termStrings.push(queryPartTerm(term));
1719
+ }
1720
+
1102
1721
  curQuery +=
1103
1722
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1104
- ieTable +
1105
- '.`guid` IN (SELECT `guid` FROM ' +
1106
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
1107
- ' WHERE `name`=@' +
1108
- name +
1109
- ' AND INSTR(`value`, @' +
1110
- value +
1111
- '))';
1723
+ '(' +
1724
+ termStrings.join(' AND ') +
1725
+ ')';
1726
+
1727
+ params[name] = curValue[0];
1112
1728
  }
1113
- params[name] = curValue[0];
1114
- params[value] = svalue;
1115
1729
  }
1116
1730
  break;
1117
1731
  case 'match':
1118
1732
  case '!match':
1119
- if (curValue[0] === 'cdate') {
1120
- if (curQuery) {
1121
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1122
- }
1123
- const cdate = `param${++count.i}`;
1124
- curQuery +=
1125
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1126
- '(' +
1127
- ieTable +
1128
- '.`cdate` REGEXP @' +
1129
- cdate +
1130
- ')';
1131
- params[cdate] = curValue[1];
1132
- break;
1133
- } else if (curValue[0] === 'mdate') {
1733
+ if (
1734
+ curValue[0] === 'cdate' ||
1735
+ curValue[0] === 'mdate' ||
1736
+ (this.nymph.tilmeld != null &&
1737
+ (curValue[0] === 'user' ||
1738
+ curValue[0] === 'group' ||
1739
+ curValue[0] === 'acUser' ||
1740
+ curValue[0] === 'acGroup' ||
1741
+ curValue[0] === 'acOther' ||
1742
+ curValue[0] === 'acRead' ||
1743
+ curValue[0] === 'acWrite' ||
1744
+ curValue[0] === 'acFull'))
1745
+ ) {
1134
1746
  if (curQuery) {
1135
1747
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1136
1748
  }
1137
- const mdate = `param${++count.i}`;
1749
+ const value = `param${++count.i}`;
1138
1750
  curQuery +=
1139
1751
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1140
1752
  '(' +
1141
1753
  ieTable +
1142
- '.`mdate` REGEXP @' +
1143
- mdate +
1754
+ '.' +
1755
+ MySQLDriver.escape(curValue[0]) +
1756
+ ' REGEXP @' +
1757
+ value +
1144
1758
  ')';
1145
- params[mdate] = curValue[1];
1146
- break;
1759
+ params[value] = curValue[1];
1147
1760
  } else {
1148
1761
  if (curQuery) {
1149
1762
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1152,10 +1765,11 @@ export default class MySQLDriver extends NymphDriver {
1152
1765
  const value = `param${++count.i}`;
1153
1766
  curQuery +=
1154
1767
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1768
+ 'EXISTS (SELECT `guid` FROM ' +
1769
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1770
+ ' WHERE `guid`=' +
1155
1771
  ieTable +
1156
- '.`guid` IN (SELECT `guid` FROM ' +
1157
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1158
- ' WHERE `name`=@' +
1772
+ '.`guid` AND `name`=@' +
1159
1773
  name +
1160
1774
  ' AND `string` REGEXP @' +
1161
1775
  value +
@@ -1166,34 +1780,33 @@ export default class MySQLDriver extends NymphDriver {
1166
1780
  break;
1167
1781
  case 'imatch':
1168
1782
  case '!imatch':
1169
- if (curValue[0] === 'cdate') {
1170
- if (curQuery) {
1171
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1172
- }
1173
- const cdate = `param${++count.i}`;
1174
- curQuery +=
1175
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1176
- '(' +
1177
- ieTable +
1178
- '.`cdate` REGEXP @' +
1179
- cdate +
1180
- ')';
1181
- params[cdate] = curValue[1];
1182
- break;
1183
- } else if (curValue[0] === 'mdate') {
1783
+ if (
1784
+ curValue[0] === 'cdate' ||
1785
+ curValue[0] === 'mdate' ||
1786
+ (this.nymph.tilmeld != null &&
1787
+ (curValue[0] === 'user' ||
1788
+ curValue[0] === 'group' ||
1789
+ curValue[0] === 'acUser' ||
1790
+ curValue[0] === 'acGroup' ||
1791
+ curValue[0] === 'acOther' ||
1792
+ curValue[0] === 'acRead' ||
1793
+ curValue[0] === 'acWrite' ||
1794
+ curValue[0] === 'acFull'))
1795
+ ) {
1184
1796
  if (curQuery) {
1185
1797
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1186
1798
  }
1187
- const mdate = `param${++count.i}`;
1799
+ const value = `param${++count.i}`;
1188
1800
  curQuery +=
1189
1801
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1190
1802
  '(' +
1191
1803
  ieTable +
1192
- '.`mdate` REGEXP @' +
1193
- mdate +
1804
+ '.' +
1805
+ MySQLDriver.escape(curValue[0]) +
1806
+ ' REGEXP @' +
1807
+ value +
1194
1808
  ')';
1195
- params[mdate] = curValue[1];
1196
- break;
1809
+ params[value] = curValue[1];
1197
1810
  } else {
1198
1811
  if (curQuery) {
1199
1812
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1202,10 +1815,11 @@ export default class MySQLDriver extends NymphDriver {
1202
1815
  const value = `param${++count.i}`;
1203
1816
  curQuery +=
1204
1817
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1818
+ 'EXISTS (SELECT `guid` FROM ' +
1819
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1820
+ ' WHERE `guid`=' +
1205
1821
  ieTable +
1206
- '.`guid` IN (SELECT `guid` FROM ' +
1207
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1208
- ' WHERE `name`=@' +
1822
+ '.`guid` AND `name`=@' +
1209
1823
  name +
1210
1824
  ' AND LOWER(`string`) REGEXP LOWER(@' +
1211
1825
  value +
@@ -1216,34 +1830,33 @@ export default class MySQLDriver extends NymphDriver {
1216
1830
  break;
1217
1831
  case 'like':
1218
1832
  case '!like':
1219
- if (curValue[0] === 'cdate') {
1833
+ if (
1834
+ curValue[0] === 'cdate' ||
1835
+ curValue[0] === 'mdate' ||
1836
+ (this.nymph.tilmeld != null &&
1837
+ (curValue[0] === 'user' ||
1838
+ curValue[0] === 'group' ||
1839
+ curValue[0] === 'acUser' ||
1840
+ curValue[0] === 'acGroup' ||
1841
+ curValue[0] === 'acOther' ||
1842
+ curValue[0] === 'acRead' ||
1843
+ curValue[0] === 'acWrite' ||
1844
+ curValue[0] === 'acFull'))
1845
+ ) {
1220
1846
  if (curQuery) {
1221
1847
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1222
1848
  }
1223
- const cdate = `param${++count.i}`;
1224
- curQuery +=
1225
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1226
- '(' +
1227
- ieTable +
1228
- '.`cdate` LIKE @' +
1229
- cdate +
1230
- ')';
1231
- params[cdate] = curValue[1];
1232
- break;
1233
- } else if (curValue[0] === 'mdate') {
1234
- if (curQuery) {
1235
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1236
- }
1237
- const mdate = `param${++count.i}`;
1849
+ const value = `param${++count.i}`;
1238
1850
  curQuery +=
1239
1851
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1240
1852
  '(' +
1241
1853
  ieTable +
1242
- '.`mdate` LIKE @' +
1243
- mdate +
1854
+ '.' +
1855
+ MySQLDriver.escape(curValue[0]) +
1856
+ ' LIKE @' +
1857
+ value +
1244
1858
  ')';
1245
- params[mdate] = curValue[1];
1246
- break;
1859
+ params[value] = curValue[1];
1247
1860
  } else {
1248
1861
  if (curQuery) {
1249
1862
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1252,10 +1865,11 @@ export default class MySQLDriver extends NymphDriver {
1252
1865
  const value = `param${++count.i}`;
1253
1866
  curQuery +=
1254
1867
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1868
+ 'EXISTS (SELECT `guid` FROM ' +
1869
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1870
+ ' WHERE `guid`=' +
1255
1871
  ieTable +
1256
- '.`guid` IN (SELECT `guid` FROM ' +
1257
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1258
- ' WHERE `name`=@' +
1872
+ '.`guid` AND `name`=@' +
1259
1873
  name +
1260
1874
  ' AND `string` LIKE @' +
1261
1875
  value +
@@ -1266,34 +1880,33 @@ export default class MySQLDriver extends NymphDriver {
1266
1880
  break;
1267
1881
  case 'ilike':
1268
1882
  case '!ilike':
1269
- if (curValue[0] === 'cdate') {
1883
+ if (
1884
+ curValue[0] === 'cdate' ||
1885
+ curValue[0] === 'mdate' ||
1886
+ (this.nymph.tilmeld != null &&
1887
+ (curValue[0] === 'user' ||
1888
+ curValue[0] === 'group' ||
1889
+ curValue[0] === 'acUser' ||
1890
+ curValue[0] === 'acGroup' ||
1891
+ curValue[0] === 'acOther' ||
1892
+ curValue[0] === 'acRead' ||
1893
+ curValue[0] === 'acWrite' ||
1894
+ curValue[0] === 'acFull'))
1895
+ ) {
1270
1896
  if (curQuery) {
1271
1897
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1272
1898
  }
1273
- const cdate = `param${++count.i}`;
1274
- curQuery +=
1275
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1276
- '(' +
1277
- ieTable +
1278
- '.`cdate` LIKE @' +
1279
- cdate +
1280
- ')';
1281
- params[cdate] = curValue[1];
1282
- break;
1283
- } else if (curValue[0] === 'mdate') {
1284
- if (curQuery) {
1285
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1286
- }
1287
- const mdate = `param${++count.i}`;
1899
+ const value = `param${++count.i}`;
1288
1900
  curQuery +=
1289
1901
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1290
1902
  '(' +
1291
1903
  ieTable +
1292
- '.`mdate` LIKE @' +
1293
- mdate +
1904
+ '.' +
1905
+ MySQLDriver.escape(curValue[0]) +
1906
+ ' LIKE @' +
1907
+ value +
1294
1908
  ')';
1295
- params[mdate] = curValue[1];
1296
- break;
1909
+ params[value] = curValue[1];
1297
1910
  } else {
1298
1911
  if (curQuery) {
1299
1912
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1302,10 +1915,11 @@ export default class MySQLDriver extends NymphDriver {
1302
1915
  const value = `param${++count.i}`;
1303
1916
  curQuery +=
1304
1917
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1918
+ 'EXISTS (SELECT `guid` FROM ' +
1919
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1920
+ ' WHERE `guid`=' +
1305
1921
  ieTable +
1306
- '.`guid` IN (SELECT `guid` FROM ' +
1307
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1308
- ' WHERE `name`=@' +
1922
+ '.`guid` AND `name`=@' +
1309
1923
  name +
1310
1924
  ' AND LOWER(`string`) LIKE LOWER(@' +
1311
1925
  value +
@@ -1316,34 +1930,33 @@ export default class MySQLDriver extends NymphDriver {
1316
1930
  break;
1317
1931
  case 'gt':
1318
1932
  case '!gt':
1319
- if (curValue[0] === 'cdate') {
1933
+ if (
1934
+ curValue[0] === 'cdate' ||
1935
+ curValue[0] === 'mdate' ||
1936
+ (this.nymph.tilmeld != null &&
1937
+ (curValue[0] === 'user' ||
1938
+ curValue[0] === 'group' ||
1939
+ curValue[0] === 'acUser' ||
1940
+ curValue[0] === 'acGroup' ||
1941
+ curValue[0] === 'acOther' ||
1942
+ curValue[0] === 'acRead' ||
1943
+ curValue[0] === 'acWrite' ||
1944
+ curValue[0] === 'acFull'))
1945
+ ) {
1320
1946
  if (curQuery) {
1321
1947
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1322
1948
  }
1323
- const cdate = `param${++count.i}`;
1324
- curQuery +=
1325
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1326
- ieTable +
1327
- '.`cdate`>@' +
1328
- cdate;
1329
- params[cdate] = isNaN(Number(curValue[1]))
1330
- ? null
1331
- : Number(curValue[1]);
1332
- break;
1333
- } else if (curValue[0] === 'mdate') {
1334
- if (curQuery) {
1335
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1336
- }
1337
- const mdate = `param${++count.i}`;
1949
+ const value = `param${++count.i}`;
1338
1950
  curQuery +=
1339
1951
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1340
1952
  ieTable +
1341
- '.`mdate`>@' +
1342
- mdate;
1343
- params[mdate] = isNaN(Number(curValue[1]))
1953
+ '.' +
1954
+ MySQLDriver.escape(curValue[0]) +
1955
+ '>@' +
1956
+ value;
1957
+ params[value] = isNaN(Number(curValue[1]))
1344
1958
  ? null
1345
1959
  : Number(curValue[1]);
1346
- break;
1347
1960
  } else {
1348
1961
  if (curQuery) {
1349
1962
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1352,10 +1965,11 @@ export default class MySQLDriver extends NymphDriver {
1352
1965
  const value = `param${++count.i}`;
1353
1966
  curQuery +=
1354
1967
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1968
+ 'EXISTS (SELECT `guid` FROM ' +
1969
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1970
+ ' WHERE `guid`=' +
1355
1971
  ieTable +
1356
- '.`guid` IN (SELECT `guid` FROM ' +
1357
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1358
- ' WHERE `name`=@' +
1972
+ '.`guid` AND `name`=@' +
1359
1973
  name +
1360
1974
  ' AND `number`>@' +
1361
1975
  value +
@@ -1368,34 +1982,33 @@ export default class MySQLDriver extends NymphDriver {
1368
1982
  break;
1369
1983
  case 'gte':
1370
1984
  case '!gte':
1371
- if (curValue[0] === 'cdate') {
1372
- if (curQuery) {
1373
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1374
- }
1375
- const cdate = `param${++count.i}`;
1376
- curQuery +=
1377
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1378
- ieTable +
1379
- '.`cdate`>=@' +
1380
- cdate;
1381
- params[cdate] = isNaN(Number(curValue[1]))
1382
- ? null
1383
- : Number(curValue[1]);
1384
- break;
1385
- } else if (curValue[0] === 'mdate') {
1985
+ if (
1986
+ curValue[0] === 'cdate' ||
1987
+ curValue[0] === 'mdate' ||
1988
+ (this.nymph.tilmeld != null &&
1989
+ (curValue[0] === 'user' ||
1990
+ curValue[0] === 'group' ||
1991
+ curValue[0] === 'acUser' ||
1992
+ curValue[0] === 'acGroup' ||
1993
+ curValue[0] === 'acOther' ||
1994
+ curValue[0] === 'acRead' ||
1995
+ curValue[0] === 'acWrite' ||
1996
+ curValue[0] === 'acFull'))
1997
+ ) {
1386
1998
  if (curQuery) {
1387
1999
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1388
2000
  }
1389
- const mdate = `param${++count.i}`;
2001
+ const value = `param${++count.i}`;
1390
2002
  curQuery +=
1391
2003
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1392
2004
  ieTable +
1393
- '.`mdate`>=@' +
1394
- mdate;
1395
- params[mdate] = isNaN(Number(curValue[1]))
2005
+ '.' +
2006
+ MySQLDriver.escape(curValue[0]) +
2007
+ '>=@' +
2008
+ value;
2009
+ params[value] = isNaN(Number(curValue[1]))
1396
2010
  ? null
1397
2011
  : Number(curValue[1]);
1398
- break;
1399
2012
  } else {
1400
2013
  if (curQuery) {
1401
2014
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1404,10 +2017,11 @@ export default class MySQLDriver extends NymphDriver {
1404
2017
  const value = `param${++count.i}`;
1405
2018
  curQuery +=
1406
2019
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2020
+ 'EXISTS (SELECT `guid` FROM ' +
2021
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
2022
+ ' WHERE `guid`=' +
1407
2023
  ieTable +
1408
- '.`guid` IN (SELECT `guid` FROM ' +
1409
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1410
- ' WHERE `name`=@' +
2024
+ '.`guid` AND `name`=@' +
1411
2025
  name +
1412
2026
  ' AND `number`>=@' +
1413
2027
  value +
@@ -1417,37 +2031,36 @@ export default class MySQLDriver extends NymphDriver {
1417
2031
  ? null
1418
2032
  : Number(curValue[1]);
1419
2033
  }
1420
- break;
1421
- case 'lt':
1422
- case '!lt':
1423
- if (curValue[0] === 'cdate') {
1424
- if (curQuery) {
1425
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1426
- }
1427
- const cdate = `param${++count.i}`;
1428
- curQuery +=
1429
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1430
- ieTable +
1431
- '.`cdate`<@' +
1432
- cdate;
1433
- params[cdate] = isNaN(Number(curValue[1]))
1434
- ? null
1435
- : Number(curValue[1]);
1436
- break;
1437
- } else if (curValue[0] === 'mdate') {
2034
+ break;
2035
+ case 'lt':
2036
+ case '!lt':
2037
+ if (
2038
+ curValue[0] === 'cdate' ||
2039
+ curValue[0] === 'mdate' ||
2040
+ (this.nymph.tilmeld != null &&
2041
+ (curValue[0] === 'user' ||
2042
+ curValue[0] === 'group' ||
2043
+ curValue[0] === 'acUser' ||
2044
+ curValue[0] === 'acGroup' ||
2045
+ curValue[0] === 'acOther' ||
2046
+ curValue[0] === 'acRead' ||
2047
+ curValue[0] === 'acWrite' ||
2048
+ curValue[0] === 'acFull'))
2049
+ ) {
1438
2050
  if (curQuery) {
1439
2051
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1440
2052
  }
1441
- const mdate = `param${++count.i}`;
2053
+ const value = `param${++count.i}`;
1442
2054
  curQuery +=
1443
2055
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1444
2056
  ieTable +
1445
- '.`mdate`<@' +
1446
- mdate;
1447
- params[mdate] = isNaN(Number(curValue[1]))
2057
+ '.' +
2058
+ MySQLDriver.escape(curValue[0]) +
2059
+ '<@' +
2060
+ value;
2061
+ params[value] = isNaN(Number(curValue[1]))
1448
2062
  ? null
1449
2063
  : Number(curValue[1]);
1450
- break;
1451
2064
  } else {
1452
2065
  if (curQuery) {
1453
2066
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1456,10 +2069,11 @@ export default class MySQLDriver extends NymphDriver {
1456
2069
  const value = `param${++count.i}`;
1457
2070
  curQuery +=
1458
2071
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2072
+ 'EXISTS (SELECT `guid` FROM ' +
2073
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
2074
+ ' WHERE `guid`=' +
1459
2075
  ieTable +
1460
- '.`guid` IN (SELECT `guid` FROM ' +
1461
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1462
- ' WHERE `name`=@' +
2076
+ '.`guid` AND `name`=@' +
1463
2077
  name +
1464
2078
  ' AND `number`<@' +
1465
2079
  value +
@@ -1472,34 +2086,33 @@ export default class MySQLDriver extends NymphDriver {
1472
2086
  break;
1473
2087
  case 'lte':
1474
2088
  case '!lte':
1475
- if (curValue[0] === 'cdate') {
1476
- if (curQuery) {
1477
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1478
- }
1479
- const cdate = `param${++count.i}`;
1480
- curQuery +=
1481
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1482
- ieTable +
1483
- '.`cdate`<=@' +
1484
- cdate;
1485
- params[cdate] = isNaN(Number(curValue[1]))
1486
- ? null
1487
- : Number(curValue[1]);
1488
- break;
1489
- } else if (curValue[0] === 'mdate') {
2089
+ if (
2090
+ curValue[0] === 'cdate' ||
2091
+ curValue[0] === 'mdate' ||
2092
+ (this.nymph.tilmeld != null &&
2093
+ (curValue[0] === 'user' ||
2094
+ curValue[0] === 'group' ||
2095
+ curValue[0] === 'acUser' ||
2096
+ curValue[0] === 'acGroup' ||
2097
+ curValue[0] === 'acOther' ||
2098
+ curValue[0] === 'acRead' ||
2099
+ curValue[0] === 'acWrite' ||
2100
+ curValue[0] === 'acFull'))
2101
+ ) {
1490
2102
  if (curQuery) {
1491
2103
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1492
2104
  }
1493
- const mdate = `param${++count.i}`;
2105
+ const value = `param${++count.i}`;
1494
2106
  curQuery +=
1495
2107
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1496
2108
  ieTable +
1497
- '.`mdate`<=@' +
1498
- mdate;
1499
- params[mdate] = isNaN(Number(curValue[1]))
2109
+ '.' +
2110
+ MySQLDriver.escape(curValue[0]) +
2111
+ '<=@' +
2112
+ value;
2113
+ params[value] = isNaN(Number(curValue[1]))
1500
2114
  ? null
1501
2115
  : Number(curValue[1]);
1502
- break;
1503
2116
  } else {
1504
2117
  if (curQuery) {
1505
2118
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1508,10 +2121,11 @@ export default class MySQLDriver extends NymphDriver {
1508
2121
  const value = `param${++count.i}`;
1509
2122
  curQuery +=
1510
2123
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2124
+ 'EXISTS (SELECT `guid` FROM ' +
2125
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
2126
+ ' WHERE `guid`=' +
1511
2127
  ieTable +
1512
- '.`guid` IN (SELECT `guid` FROM ' +
1513
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1514
- ' WHERE `name`=@' +
2128
+ '.`guid` AND `name`=@' +
1515
2129
  name +
1516
2130
  ' AND `number`<=@' +
1517
2131
  value +
@@ -1535,32 +2149,66 @@ export default class MySQLDriver extends NymphDriver {
1535
2149
  if (curQuery) {
1536
2150
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1537
2151
  }
1538
- const name = `param${++count.i}`;
1539
- const guid = `param${++count.i}`;
1540
- curQuery +=
1541
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1542
- ieTable +
1543
- '.`guid` IN (SELECT `guid` FROM ' +
1544
- MySQLDriver.escape(this.prefix + 'references_' + etype) +
1545
- ' WHERE `name`=@' +
1546
- name +
1547
- ' AND `reference`=UNHEX(@' +
1548
- guid +
1549
- '))';
1550
- params[name] = curValue[0];
1551
- params[guid] = curQguid;
2152
+ if (
2153
+ this.nymph.tilmeld != null &&
2154
+ (curValue[0] === 'user' || curValue[0] === 'group')
2155
+ ) {
2156
+ const guid = `param${++count.i}`;
2157
+ curQuery +=
2158
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2159
+ ieTable +
2160
+ '.' +
2161
+ MySQLDriver.escape(curValue[0]) +
2162
+ '=UNHEX(@' +
2163
+ guid +
2164
+ ')';
2165
+ params[guid] = curQguid;
2166
+ } else if (
2167
+ this.nymph.tilmeld != null &&
2168
+ (curValue[0] === 'acRead' ||
2169
+ curValue[0] === 'acWrite' ||
2170
+ curValue[0] === 'acFull')
2171
+ ) {
2172
+ const queryParam = `param${++count.i}`;
2173
+ curQuery +=
2174
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2175
+ 'MATCH (' +
2176
+ ieTable +
2177
+ '.' +
2178
+ MySQLDriver.escape(curValue[0]) +
2179
+ ') AGAINST (@' +
2180
+ queryParam +
2181
+ ' IN BOOLEAN MODE)';
2182
+ params[queryParam] = '+' + curQguid;
2183
+ } else {
2184
+ const name = `param${++count.i}`;
2185
+ const guid = `param${++count.i}`;
2186
+ curQuery +=
2187
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2188
+ 'EXISTS (SELECT `guid` FROM ' +
2189
+ MySQLDriver.escape(this.prefix + 'references_' + etype) +
2190
+ ' WHERE `guid`=' +
2191
+ ieTable +
2192
+ '.`guid` AND `name`=@' +
2193
+ name +
2194
+ ' AND `reference`=UNHEX(@' +
2195
+ guid +
2196
+ '))';
2197
+ params[name] = curValue[0];
2198
+ params[guid] = curQguid;
2199
+ }
1552
2200
  break;
1553
2201
  case 'selector':
1554
2202
  case '!selector':
1555
- const subquery = this.makeEntityQuery(
1556
- options,
2203
+ const innerquery = this.makeEntityQuery(
2204
+ { ...options, sort: null, limit: undefined },
1557
2205
  [curValue],
1558
2206
  etype,
1559
2207
  count,
1560
2208
  params,
1561
2209
  true,
1562
2210
  tableSuffix,
1563
- etypes
2211
+ etypes,
1564
2212
  );
1565
2213
  if (curQuery) {
1566
2214
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1568,47 +2216,135 @@ export default class MySQLDriver extends NymphDriver {
1568
2216
  curQuery +=
1569
2217
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1570
2218
  '(' +
1571
- subquery.query +
2219
+ innerquery.query +
1572
2220
  ')';
1573
2221
  break;
1574
2222
  case 'qref':
1575
2223
  case '!qref':
2224
+ const referenceTableSuffix = makeTableSuffix();
1576
2225
  const [qrefOptions, ...qrefSelectors] = curValue[1] as [
1577
2226
  Options,
1578
- ...FormattedSelector[]
2227
+ ...FormattedSelector[],
1579
2228
  ];
1580
2229
  const QrefEntityClass = qrefOptions.class as EntityConstructor;
1581
2230
  etypes.push(QrefEntityClass.ETYPE);
1582
- const qrefQuery = this.makeEntityQuery(
1583
- { ...qrefOptions, return: 'guid', class: QrefEntityClass },
1584
- qrefSelectors,
1585
- QrefEntityClass.ETYPE,
1586
- count,
1587
- params,
1588
- false,
1589
- makeTableSuffix(),
1590
- etypes
1591
- );
1592
2231
  if (curQuery) {
1593
2232
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1594
2233
  }
1595
- const qrefName = `param${++count.i}`;
1596
- curQuery +=
1597
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1598
- ieTable +
1599
- '.`guid` IN (SELECT `guid` FROM ' +
1600
- MySQLDriver.escape(this.prefix + 'references_' + etype) +
1601
- ' WHERE `name`=@' +
1602
- qrefName +
1603
- ' AND `reference` IN (' +
1604
- qrefQuery.query +
1605
- '))';
1606
- params[qrefName] = curValue[0];
2234
+ if (
2235
+ this.nymph.tilmeld != null &&
2236
+ (curValue[0] === 'user' || curValue[0] === 'group')
2237
+ ) {
2238
+ const qrefQuery = this.makeEntityQuery(
2239
+ {
2240
+ ...qrefOptions,
2241
+ sort: qrefOptions.sort ?? null,
2242
+ return: 'guid',
2243
+ class: QrefEntityClass,
2244
+ },
2245
+ qrefSelectors,
2246
+ QrefEntityClass.ETYPE,
2247
+ count,
2248
+ params,
2249
+ false,
2250
+ makeTableSuffix(),
2251
+ etypes,
2252
+ 'r' +
2253
+ referenceTableSuffix +
2254
+ '.' +
2255
+ MySQLDriver.escape(curValue[0]),
2256
+ );
2257
+
2258
+ curQuery +=
2259
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2260
+ 'EXISTS (SELECT `guid` FROM ' +
2261
+ MySQLDriver.escape(this.prefix + 'entities_' + etype) +
2262
+ ' r' +
2263
+ referenceTableSuffix +
2264
+ ' WHERE r' +
2265
+ referenceTableSuffix +
2266
+ '.`guid`=' +
2267
+ ieTable +
2268
+ '.`guid` AND EXISTS (' +
2269
+ qrefQuery.query +
2270
+ '))';
2271
+ } else if (
2272
+ this.nymph.tilmeld != null &&
2273
+ (curValue[0] === 'acRead' ||
2274
+ curValue[0] === 'acWrite' ||
2275
+ curValue[0] === 'acFull')
2276
+ ) {
2277
+ const qrefQuery = this.makeEntityQuery(
2278
+ {
2279
+ ...qrefOptions,
2280
+ sort: qrefOptions.sort ?? null,
2281
+ return: 'guid',
2282
+ class: QrefEntityClass,
2283
+ },
2284
+ qrefSelectors,
2285
+ QrefEntityClass.ETYPE,
2286
+ count,
2287
+ params,
2288
+ false,
2289
+ makeTableSuffix(),
2290
+ etypes,
2291
+ undefined,
2292
+ (guid) =>
2293
+ ieTable +
2294
+ '.' +
2295
+ MySQLDriver.escape(curValue[0]) +
2296
+ " LIKE CONCAT('% ', LOWER(HEX(" +
2297
+ guid +
2298
+ ")), ' %')",
2299
+ );
2300
+
2301
+ curQuery +=
2302
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2303
+ 'EXISTS (' +
2304
+ qrefQuery.query +
2305
+ ')';
2306
+ } else {
2307
+ const qrefQuery = this.makeEntityQuery(
2308
+ {
2309
+ ...qrefOptions,
2310
+ sort: qrefOptions.sort ?? null,
2311
+ return: 'guid',
2312
+ class: QrefEntityClass,
2313
+ },
2314
+ qrefSelectors,
2315
+ QrefEntityClass.ETYPE,
2316
+ count,
2317
+ params,
2318
+ false,
2319
+ makeTableSuffix(),
2320
+ etypes,
2321
+ 'r' + referenceTableSuffix + '.`reference`',
2322
+ );
2323
+ const qrefName = `param${++count.i}`;
2324
+ curQuery +=
2325
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2326
+ 'EXISTS (SELECT `guid` FROM ' +
2327
+ MySQLDriver.escape(this.prefix + 'references_' + etype) +
2328
+ ' r' +
2329
+ referenceTableSuffix +
2330
+ ' WHERE r' +
2331
+ referenceTableSuffix +
2332
+ '.`guid`=' +
2333
+ ieTable +
2334
+ '.`guid` AND r' +
2335
+ referenceTableSuffix +
2336
+ '.`name`=@' +
2337
+ qrefName +
2338
+ ' AND EXISTS (' +
2339
+ qrefQuery.query +
2340
+ '))';
2341
+ params[qrefName] = curValue[0];
2342
+ }
1607
2343
  break;
1608
2344
  }
1609
2345
  }
1610
2346
  return curQuery;
1611
- }
2347
+ },
1612
2348
  );
1613
2349
 
1614
2350
  let sortBy: string;
@@ -1616,33 +2352,38 @@ export default class MySQLDriver extends NymphDriver {
1616
2352
  let sortJoin = '';
1617
2353
  let sortJoinInner = '';
1618
2354
  const order = options.reverse ? ' DESC' : '';
1619
- switch (sort) {
1620
- case 'mdate':
1621
- sortBy = `${eTable}.\`mdate\`${order}`;
1622
- sortByInner = `${ieTable}.\`mdate\`${order}`;
1623
- break;
1624
- case 'cdate':
1625
- sortBy = `${eTable}.\`cdate\`${order}`;
1626
- sortByInner = `${ieTable}.\`cdate\`${order}`;
1627
- break;
1628
- default:
1629
- const name = `param${++count.i}`;
1630
- sortJoin = `LEFT JOIN (
1631
- SELECT \`guid\`, \`string\`, \`number\`
1632
- FROM ${MySQLDriver.escape(this.prefix + 'comparisons_' + etype)}
1633
- WHERE \`name\`=@${name}
1634
- ORDER BY \`number\`${order}, \`string\`${order}
1635
- ) ${sTable} ON ${eTable}.\`guid\`=${sTable}.\`guid\``;
1636
- sortJoinInner = `LEFT JOIN (
1637
- SELECT \`guid\`, \`string\`, \`number\`
1638
- FROM ${MySQLDriver.escape(this.prefix + 'comparisons_' + etype)}
1639
- WHERE \`name\`=@${name}
1640
- ORDER BY \`number\`${order}, \`string\`${order}
1641
- ) ${sTable} ON ${ieTable}.\`guid\`=${sTable}.\`guid\``;
1642
- sortBy = `${sTable}.\`number\`${order}, ${sTable}.\`string\`${order}`;
1643
- sortByInner = sortBy;
1644
- params[name] = sort;
1645
- break;
2355
+ if (sort == null) {
2356
+ sortBy = '';
2357
+ sortByInner = '';
2358
+ } else {
2359
+ switch (sort) {
2360
+ case 'mdate':
2361
+ sortBy = `ORDER BY ${eTable}.\`mdate\`${order}`;
2362
+ sortByInner = `ORDER BY ${ieTable}.\`mdate\`${order}`;
2363
+ break;
2364
+ case 'cdate':
2365
+ sortBy = `ORDER BY ${eTable}.\`cdate\`${order}`;
2366
+ sortByInner = `ORDER BY ${ieTable}.\`cdate\`${order}`;
2367
+ break;
2368
+ default:
2369
+ const name = `param${++count.i}`;
2370
+ sortJoin = `LEFT JOIN (
2371
+ SELECT \`guid\`, \`string\`, \`number\`
2372
+ FROM ${MySQLDriver.escape(this.prefix + 'data_' + etype)}
2373
+ WHERE \`name\`=@${name}
2374
+ ORDER BY \`number\`${order}, \`string\`${order}
2375
+ ) ${sTable} ON ${eTable}.\`guid\`=${sTable}.\`guid\``;
2376
+ sortJoinInner = `LEFT JOIN (
2377
+ SELECT \`guid\`, \`string\`, \`number\`
2378
+ FROM ${MySQLDriver.escape(this.prefix + 'data_' + etype)}
2379
+ WHERE \`name\`=@${name}
2380
+ ORDER BY \`number\`${order}, \`string\`${order}
2381
+ ) ${sTable} ON ${ieTable}.\`guid\`=${sTable}.\`guid\``;
2382
+ sortBy = `ORDER BY ${sTable}.\`number\`${order}, ${sTable}.\`string\`${order}`;
2383
+ sortByInner = sortBy;
2384
+ params[name] = sort;
2385
+ break;
2386
+ }
1646
2387
  }
1647
2388
 
1648
2389
  let query: string;
@@ -1651,33 +2392,38 @@ export default class MySQLDriver extends NymphDriver {
1651
2392
  query = '(' + queryParts.join(') AND (') + ')';
1652
2393
  } else {
1653
2394
  let limit = '';
1654
- if ('limit' in options) {
2395
+ if ('limit' in options && options.limit != null) {
1655
2396
  limit = ` LIMIT ${Math.floor(
1656
- isNaN(Number(options.limit)) ? 0 : Number(options.limit)
2397
+ isNaN(Number(options.limit)) ? 0 : Number(options.limit),
1657
2398
  )}`;
1658
2399
  }
1659
2400
  let offset = '';
1660
- if ('offset' in options) {
2401
+ if ('offset' in options && options.offset != null) {
1661
2402
  offset = ` OFFSET ${Math.floor(
1662
- isNaN(Number(options.offset)) ? 0 : Number(options.offset)
2403
+ isNaN(Number(options.offset)) ? 0 : Number(options.offset),
1663
2404
  )}`;
1664
2405
  }
1665
2406
  const whereClause = queryParts.join(') AND (');
2407
+ const guidClause = guidExplicitSelector
2408
+ ? `${guidExplicitSelector(`${ieTable}.\`guid\``)} AND `
2409
+ : guidSelector
2410
+ ? `${ieTable}.\`guid\`=${guidSelector} AND `
2411
+ : '';
1666
2412
  if (options.return === 'count') {
1667
2413
  if (limit || offset) {
1668
2414
  query = `SELECT COUNT(${countTable}.\`guid\`) AS \`count\` FROM (
1669
2415
  SELECT ${ieTable}.\`guid\` AS \`guid\`
1670
2416
  FROM ${MySQLDriver.escape(
1671
- `${this.prefix}entities_${etype}`
2417
+ `${this.prefix}entities_${etype}`,
1672
2418
  )} ${ieTable}
1673
- WHERE (${whereClause})${limit}${offset}
2419
+ WHERE ${guidClause}(${whereClause})${limit}${offset}
1674
2420
  ) ${countTable}`;
1675
2421
  } else {
1676
2422
  query = `SELECT COUNT(${ieTable}.\`guid\`) AS \`count\`
1677
2423
  FROM ${MySQLDriver.escape(
1678
- `${this.prefix}entities_${etype}`
2424
+ `${this.prefix}entities_${etype}`,
1679
2425
  )} ${ieTable}
1680
- WHERE (${whereClause})`;
2426
+ WHERE ${guidClause}(${whereClause})`;
1681
2427
  }
1682
2428
  } else if (options.return === 'guid') {
1683
2429
  const guidColumn =
@@ -1686,41 +2432,47 @@ export default class MySQLDriver extends NymphDriver {
1686
2432
  : `${ieTable}.\`guid\``;
1687
2433
  query = `SELECT ${guidColumn} AS \`guid\`
1688
2434
  FROM ${MySQLDriver.escape(
1689
- `${this.prefix}entities_${etype}`
2435
+ `${this.prefix}entities_${etype}`,
1690
2436
  )} ${ieTable}
1691
2437
  ${sortJoinInner}
1692
- WHERE (${whereClause})
1693
- ORDER BY ${sortByInner}, ${ieTable}.\`guid\`${limit}${offset}`;
2438
+ WHERE ${guidClause}(${whereClause})
2439
+ ${sortByInner ? sortByInner + ', ' : 'ORDER BY '}${ieTable}.\`guid\`${limit}${offset}`;
1694
2440
  } else {
1695
2441
  query = `SELECT
1696
2442
  LOWER(HEX(${eTable}.\`guid\`)) AS \`guid\`,
1697
2443
  ${eTable}.\`tags\`,
1698
2444
  ${eTable}.\`cdate\`,
1699
2445
  ${eTable}.\`mdate\`,
2446
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2447
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2448
+ ${eTable}.\`acUser\`,
2449
+ ${eTable}.\`acGroup\`,
2450
+ ${eTable}.\`acOther\`,
2451
+ ${eTable}.\`acRead\`,
2452
+ ${eTable}.\`acWrite\`,
2453
+ ${eTable}.\`acFull\`,
1700
2454
  ${dTable}.\`name\`,
1701
2455
  ${dTable}.\`value\`,
1702
- ${cTable}.\`string\`,
1703
- ${cTable}.\`number\`
2456
+ ${dTable}.\`json\`,
2457
+ ${dTable}.\`string\`,
2458
+ ${dTable}.\`number\`
1704
2459
  FROM ${MySQLDriver.escape(
1705
- `${this.prefix}entities_${etype}`
2460
+ `${this.prefix}entities_${etype}`,
1706
2461
  )} ${eTable}
1707
2462
  LEFT JOIN ${MySQLDriver.escape(
1708
- `${this.prefix}data_${etype}`
2463
+ `${this.prefix}data_${etype}`,
1709
2464
  )} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1710
- INNER JOIN ${MySQLDriver.escape(
1711
- `${this.prefix}comparisons_${etype}`
1712
- )} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1713
2465
  ${sortJoin}
1714
2466
  INNER JOIN (
1715
2467
  SELECT ${ieTable}.\`guid\`
1716
2468
  FROM ${MySQLDriver.escape(
1717
- `${this.prefix}entities_${etype}`
2469
+ `${this.prefix}entities_${etype}`,
1718
2470
  )} ${ieTable}
1719
2471
  ${sortJoinInner}
1720
- WHERE (${whereClause})
1721
- ORDER BY ${sortByInner}${limit}${offset}
2472
+ WHERE ${guidClause}(${whereClause})
2473
+ ${sortByInner}${limit}${offset}
1722
2474
  ) ${fTable} ON ${eTable}.\`guid\`=${fTable}.\`guid\`
1723
- ORDER BY ${sortBy}, ${eTable}.\`guid\``;
2475
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1724
2476
  }
1725
2477
  }
1726
2478
  } else {
@@ -1728,30 +2480,35 @@ export default class MySQLDriver extends NymphDriver {
1728
2480
  query = '';
1729
2481
  } else {
1730
2482
  let limit = '';
1731
- if ('limit' in options) {
2483
+ if ('limit' in options && options.limit != null) {
1732
2484
  limit = ` LIMIT ${Math.floor(
1733
- isNaN(Number(options.limit)) ? 0 : Number(options.limit)
2485
+ isNaN(Number(options.limit)) ? 0 : Number(options.limit),
1734
2486
  )}`;
1735
2487
  }
1736
2488
  let offset = '';
1737
- if ('offset' in options) {
2489
+ if ('offset' in options && options.offset != null) {
1738
2490
  offset = ` OFFSET ${Math.floor(
1739
- isNaN(Number(options.offset)) ? 0 : Number(options.offset)
2491
+ isNaN(Number(options.offset)) ? 0 : Number(options.offset),
1740
2492
  )}`;
1741
2493
  }
2494
+ const guidClause = guidExplicitSelector
2495
+ ? ` WHERE ${guidExplicitSelector(`${ieTable}.\`guid\``)}`
2496
+ : guidSelector
2497
+ ? ` WHERE ${ieTable}.\`guid\`=${guidSelector}`
2498
+ : '';
1742
2499
  if (options.return === 'count') {
1743
2500
  if (limit || offset) {
1744
2501
  query = `SELECT COUNT(${countTable}.\`guid\`) AS \`count\` FROM (
1745
2502
  SELECT ${ieTable}.\`guid\` AS \`guid\`
1746
2503
  FROM ${MySQLDriver.escape(
1747
- `${this.prefix}entities_${etype}`
1748
- )} ${ieTable}${limit}${offset}
2504
+ `${this.prefix}entities_${etype}`,
2505
+ )} ${ieTable}${guidClause}${limit}${offset}
1749
2506
  ) ${countTable}`;
1750
2507
  } else {
1751
2508
  query = `SELECT COUNT(${ieTable}.\`guid\`) AS \`count\`
1752
2509
  FROM ${MySQLDriver.escape(
1753
- `${this.prefix}entities_${etype}`
1754
- )} ${ieTable}`;
2510
+ `${this.prefix}entities_${etype}`,
2511
+ )} ${ieTable}${guidClause}`;
1755
2512
  }
1756
2513
  } else if (options.return === 'guid') {
1757
2514
  const guidColumn =
@@ -1760,10 +2517,11 @@ export default class MySQLDriver extends NymphDriver {
1760
2517
  : `${ieTable}.\`guid\``;
1761
2518
  query = `SELECT ${guidColumn} AS \`guid\`
1762
2519
  FROM ${MySQLDriver.escape(
1763
- `${this.prefix}entities_${etype}`
2520
+ `${this.prefix}entities_${etype}`,
1764
2521
  )} ${ieTable}
1765
2522
  ${sortJoinInner}
1766
- ORDER BY ${sortByInner}, ${ieTable}.\`guid\`${limit}${offset}`;
2523
+ ${guidClause}
2524
+ ${sortByInner ? sortByInner + ', ' : 'ORDER BY '}${ieTable}.\`guid\`${limit}${offset}`;
1767
2525
  } else {
1768
2526
  if (limit || offset) {
1769
2527
  query = `SELECT
@@ -1771,50 +2529,64 @@ export default class MySQLDriver extends NymphDriver {
1771
2529
  ${eTable}.\`tags\`,
1772
2530
  ${eTable}.\`cdate\`,
1773
2531
  ${eTable}.\`mdate\`,
2532
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2533
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2534
+ ${eTable}.\`acUser\`,
2535
+ ${eTable}.\`acGroup\`,
2536
+ ${eTable}.\`acOther\`,
2537
+ ${eTable}.\`acRead\`,
2538
+ ${eTable}.\`acWrite\`,
2539
+ ${eTable}.\`acFull\`,
1774
2540
  ${dTable}.\`name\`,
1775
2541
  ${dTable}.\`value\`,
1776
- ${cTable}.\`string\`,
1777
- ${cTable}.\`number\`
2542
+ ${dTable}.\`json\`,
2543
+ ${dTable}.\`string\`,
2544
+ ${dTable}.\`number\`
1778
2545
  FROM ${MySQLDriver.escape(
1779
- `${this.prefix}entities_${etype}`
2546
+ `${this.prefix}entities_${etype}`,
1780
2547
  )} ${eTable}
1781
2548
  LEFT JOIN ${MySQLDriver.escape(
1782
- `${this.prefix}data_${etype}`
2549
+ `${this.prefix}data_${etype}`,
1783
2550
  )} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1784
- INNER JOIN ${MySQLDriver.escape(
1785
- `${this.prefix}comparisons_${etype}`
1786
- )} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1787
2551
  ${sortJoin}
1788
2552
  INNER JOIN (
1789
2553
  SELECT ${ieTable}.\`guid\`
1790
2554
  FROM ${MySQLDriver.escape(
1791
- `${this.prefix}entities_${etype}`
2555
+ `${this.prefix}entities_${etype}`,
1792
2556
  )} ${ieTable}
1793
2557
  ${sortJoinInner}
1794
- ORDER BY ${sortByInner}${limit}${offset}
2558
+ ${guidClause}
2559
+ ${sortByInner}${limit}${offset}
1795
2560
  ) ${fTable} ON ${eTable}.\`guid\`=${fTable}.\`guid\`
1796
- ORDER BY ${sortBy}, ${eTable}.\`guid\``;
2561
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1797
2562
  } else {
1798
2563
  query = `SELECT
1799
2564
  LOWER(HEX(${eTable}.\`guid\`)) AS \`guid\`,
1800
2565
  ${eTable}.\`tags\`,
1801
2566
  ${eTable}.\`cdate\`,
1802
2567
  ${eTable}.\`mdate\`,
2568
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2569
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2570
+ ${eTable}.\`acUser\`,
2571
+ ${eTable}.\`acGroup\`,
2572
+ ${eTable}.\`acOther\`,
2573
+ ${eTable}.\`acRead\`,
2574
+ ${eTable}.\`acWrite\`,
2575
+ ${eTable}.\`acFull\`,
1803
2576
  ${dTable}.\`name\`,
1804
2577
  ${dTable}.\`value\`,
1805
- ${cTable}.\`string\`,
1806
- ${cTable}.\`number\`
2578
+ ${dTable}.\`json\`,
2579
+ ${dTable}.\`string\`,
2580
+ ${dTable}.\`number\`
1807
2581
  FROM ${MySQLDriver.escape(
1808
- `${this.prefix}entities_${etype}`
2582
+ `${this.prefix}entities_${etype}`,
1809
2583
  )} ${eTable}
1810
2584
  LEFT JOIN ${MySQLDriver.escape(
1811
- `${this.prefix}data_${etype}`
2585
+ `${this.prefix}data_${etype}`,
1812
2586
  )} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1813
- INNER JOIN ${MySQLDriver.escape(
1814
- `${this.prefix}comparisons_${etype}`
1815
- )} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1816
2587
  ${sortJoin}
1817
- ORDER BY ${sortBy}, ${eTable}.\`guid\``;
2588
+ ${guidExplicitSelector ? `WHERE ${guidExplicitSelector(`${eTable}.\`guid\``)}` : guidSelector ? `WHERE ${eTable}.\`guid\`=${guidSelector}` : ''}
2589
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1818
2590
  }
1819
2591
  }
1820
2592
  }
@@ -1834,38 +2606,18 @@ export default class MySQLDriver extends NymphDriver {
1834
2606
  protected performQuery(
1835
2607
  options: Options,
1836
2608
  formattedSelectors: FormattedSelector[],
1837
- etype: string
2609
+ etype: string,
1838
2610
  ): {
1839
2611
  result: any;
1840
2612
  } {
1841
2613
  const { query, params, etypes } = this.makeEntityQuery(
1842
2614
  options,
1843
2615
  formattedSelectors,
1844
- etype
1845
- );
1846
- const result = this.queryIter(query, { etypes, params }).then((val) =>
1847
- val[Symbol.iterator]()
2616
+ etype,
1848
2617
  );
1849
- return {
1850
- result,
1851
- };
1852
- }
1853
-
1854
- protected performQuerySync(
1855
- options: Options,
1856
- formattedSelectors: FormattedSelector[],
1857
- etype: string
1858
- ): {
1859
- result: any;
1860
- } {
1861
- const { query, params, etypes } = this.makeEntityQuery(
1862
- options,
1863
- formattedSelectors,
1864
- etype
2618
+ const result = this.queryArray(query, { etypes, params }).then((val) =>
2619
+ val[Symbol.iterator](),
1865
2620
  );
1866
- const result = (this.queryIterSync(query, { etypes, params }) || [])[
1867
- Symbol.iterator
1868
- ]();
1869
2621
  return {
1870
2622
  result,
1871
2623
  };
@@ -1879,20 +2631,26 @@ export default class MySQLDriver extends NymphDriver {
1879
2631
  options: Options<T> & { return: 'guid' },
1880
2632
  ...selectors: Selector[]
1881
2633
  ): Promise<string[]>;
2634
+ public async getEntities<T extends EntityConstructor = EntityConstructor>(
2635
+ options: Options<T> & { return: 'object' },
2636
+ ...selectors: Selector[]
2637
+ ): Promise<EntityObjectType<T>[]>;
1882
2638
  public async getEntities<T extends EntityConstructor = EntityConstructor>(
1883
2639
  options?: Options<T>,
1884
2640
  ...selectors: Selector[]
1885
- ): Promise<ReturnType<T['factorySync']>[]>;
2641
+ ): Promise<EntityInstanceType<T>[]>;
1886
2642
  public async getEntities<T extends EntityConstructor = EntityConstructor>(
1887
2643
  options: Options<T> = {},
1888
2644
  ...selectors: Selector[]
1889
- ): Promise<ReturnType<T['factorySync']>[] | string[] | number> {
1890
- const { result: resultPromise, process } = this.getEntitesRowLike<T>(
2645
+ ): Promise<
2646
+ EntityInstanceType<T>[] | EntityObjectType<T>[] | string[] | number
2647
+ > {
2648
+ const { result: resultPromise, process } = this.getEntitiesRowLike<T>(
1891
2649
  // @ts-ignore: options is correct here.
1892
2650
  options,
1893
2651
  selectors,
1894
- (options, formattedSelectors, etype) =>
1895
- this.performQuery(options, formattedSelectors, etype),
2652
+ ({ options, selectors, etype }) =>
2653
+ this.performQuery(options, selectors, etype),
1896
2654
  () => {
1897
2655
  const next: any = result.next();
1898
2656
  return next.done ? null : next.value;
@@ -1901,9 +2659,25 @@ export default class MySQLDriver extends NymphDriver {
1901
2659
  (row) => Number(row.count),
1902
2660
  (row) => row.guid,
1903
2661
  (row) => ({
1904
- tags: row.tags.length > 2 ? row.tags.slice(1, -1).split(' ') : [],
1905
- cdate: isNaN(Number(row.cdate)) ? null : Number(row.cdate),
1906
- mdate: isNaN(Number(row.mdate)) ? null : Number(row.mdate),
2662
+ tags:
2663
+ row.tags.length > 2
2664
+ ? MySQLDriver.unescapeTags(
2665
+ row.tags
2666
+ .slice(1, -1)
2667
+ .split(' ')
2668
+ .filter((tag: string) => tag),
2669
+ )
2670
+ : [],
2671
+ cdate: isNaN(Number(row.cdate)) ? Date.now() : Number(row.cdate),
2672
+ mdate: isNaN(Number(row.mdate)) ? Date.now() : Number(row.mdate),
2673
+ user: row.user,
2674
+ group: row.group,
2675
+ acUser: row.acUser,
2676
+ acGroup: row.acGroup,
2677
+ acOther: row.acOther,
2678
+ acRead: row.acRead?.slice(1, -1).split(' ') ?? [],
2679
+ acWrite: row.acWrite?.slice(1, -1).split(' ') ?? [],
2680
+ acFull: row.acFull?.slice(1, -1).split(' ') ?? [],
1907
2681
  }),
1908
2682
  (row) => ({
1909
2683
  name: row.name,
@@ -1911,9 +2685,11 @@ export default class MySQLDriver extends NymphDriver {
1911
2685
  row.value === 'N'
1912
2686
  ? JSON.stringify(row.number)
1913
2687
  : row.value === 'S'
1914
- ? JSON.stringify(row.string)
1915
- : row.value,
1916
- })
2688
+ ? JSON.stringify(row.string)
2689
+ : row.value === 'J'
2690
+ ? JSON.stringify(row.json)
2691
+ : row.value,
2692
+ }),
1917
2693
  );
1918
2694
 
1919
2695
  const result = await resultPromise;
@@ -1924,231 +2700,390 @@ export default class MySQLDriver extends NymphDriver {
1924
2700
  return value;
1925
2701
  }
1926
2702
 
1927
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1928
- options: Options<T> & { return: 'count' },
1929
- ...selectors: Selector[]
1930
- ): number;
1931
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1932
- options: Options<T> & { return: 'guid' },
1933
- ...selectors: Selector[]
1934
- ): string[];
1935
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1936
- options?: Options<T>,
1937
- ...selectors: Selector[]
1938
- ): ReturnType<T['factorySync']>[];
1939
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1940
- options: Options<T> = {},
1941
- ...selectors: Selector[]
1942
- ): ReturnType<T['factorySync']>[] | string[] | number {
1943
- const { result, process } = this.getEntitesRowLike<T>(
1944
- // @ts-ignore: options is correct here.
1945
- options,
1946
- selectors,
1947
- (options, formattedSelectors, etype) =>
1948
- this.performQuerySync(options, formattedSelectors, etype),
1949
- () => {
1950
- const next: any = result.next();
1951
- return next.done ? null : next.value;
1952
- },
1953
- () => undefined,
1954
- (row) => Number(row.count),
1955
- (row) => row.guid,
1956
- (row) => ({
1957
- tags: row.tags.length > 2 ? row.tags.slice(1, -1).split(',') : [],
1958
- cdate: isNaN(Number(row.cdate)) ? null : Number(row.cdate),
1959
- mdate: isNaN(Number(row.mdate)) ? null : Number(row.mdate),
1960
- }),
1961
- (row) => ({
1962
- name: row.name,
1963
- svalue:
1964
- row.value === 'N'
1965
- ? JSON.stringify(row.number)
1966
- : row.value === 'S'
1967
- ? JSON.stringify(row.string)
1968
- : row.value,
1969
- })
1970
- );
1971
- const value = process();
1972
- if (value instanceof Error) {
1973
- throw value;
1974
- }
1975
- return value;
1976
- }
1977
-
1978
2703
  public async getUID(name: string) {
1979
2704
  if (name == null) {
1980
2705
  throw new InvalidParametersError('Name not given for UID.');
1981
2706
  }
2707
+ if (name.length > 128) {
2708
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
2709
+ }
1982
2710
  const result = await this.queryGet(
1983
2711
  `SELECT \`cur_uid\` FROM ${MySQLDriver.escape(
1984
- `${this.prefix}uids`
2712
+ `${this.prefix}uids`,
1985
2713
  )} WHERE \`name\`=@name;`,
1986
2714
  {
1987
2715
  params: {
1988
2716
  name: name,
1989
2717
  },
1990
- }
2718
+ },
1991
2719
  );
1992
2720
  return (result?.cur_uid as number | null) ?? null;
1993
2721
  }
1994
2722
 
1995
- public async import(filename: string) {
2723
+ public async importEntity(entity: {
2724
+ guid: string;
2725
+ cdate: number;
2726
+ mdate: number;
2727
+ tags: string[];
2728
+ sdata: SerializedEntityData;
2729
+ etype: string;
2730
+ }) {
2731
+ return await this.importEntityInternal(entity);
2732
+ }
2733
+
2734
+ public async importEntityTokens(entity: {
2735
+ guid: string;
2736
+ cdate: number;
2737
+ mdate: number;
2738
+ tags: string[];
2739
+ sdata: SerializedEntityData;
2740
+ etype: string;
2741
+ }) {
2742
+ return await this.importEntityInternal(entity, { only: 'tokens' });
2743
+ }
2744
+
2745
+ public async importEntityTilmeldAC(entity: {
2746
+ guid: string;
2747
+ cdate: number;
2748
+ mdate: number;
2749
+ tags: string[];
2750
+ sdata: SerializedEntityData;
2751
+ etype: string;
2752
+ }) {
2753
+ return await this.importEntityInternal(entity, { only: 'tilmeldAC' });
2754
+ }
2755
+
2756
+ private async importEntityInternal(
2757
+ {
2758
+ guid,
2759
+ cdate,
2760
+ mdate,
2761
+ tags,
2762
+ sdata,
2763
+ etype,
2764
+ }: {
2765
+ guid: string;
2766
+ cdate: number;
2767
+ mdate: number;
2768
+ tags: string[];
2769
+ sdata: SerializedEntityData;
2770
+ etype: string;
2771
+ },
2772
+ { only = undefined }: { only?: 'tokens' | 'tilmeldAC' } = {},
2773
+ ) {
1996
2774
  try {
1997
- const result = await this.importFromFile(
1998
- filename,
1999
- async (guid, tags, sdata, etype) => {
2000
- await this.queryRun(
2001
- `REPLACE INTO ${MySQLDriver.escape(
2002
- `${this.prefix}entities_${etype}`
2003
- )} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`) VALUES (UNHEX(@guid), @tags, @cdate, @mdate);`,
2775
+ let promises = [];
2776
+ if (only == null) {
2777
+ promises.push(
2778
+ this.queryRun(
2779
+ `DELETE FROM ${MySQLDriver.escape(
2780
+ `${this.prefix}entities_${etype}`,
2781
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2004
2782
  {
2005
2783
  etypes: [etype],
2006
2784
  params: {
2007
2785
  guid,
2008
- tags: ' ' + tags.join(' ') + ' ',
2009
- cdate: isNaN(Number(JSON.parse(sdata.cdate)))
2010
- ? null
2011
- : Number(JSON.parse(sdata.cdate)),
2012
- mdate: isNaN(Number(JSON.parse(sdata.mdate)))
2013
- ? null
2014
- : Number(JSON.parse(sdata.mdate)),
2015
2786
  },
2016
- }
2017
- );
2018
- const promises = [];
2019
- promises.push(
2020
- this.queryRun(
2021
- `DELETE FROM ${MySQLDriver.escape(
2022
- `${this.prefix}data_${etype}`
2023
- )} WHERE \`guid\`=UNHEX(@guid);`,
2024
- {
2025
- etypes: [etype],
2026
- params: {
2027
- guid,
2028
- },
2029
- }
2030
- )
2031
- );
2032
- promises.push(
2033
- this.queryRun(
2034
- `DELETE FROM ${MySQLDriver.escape(
2035
- `${this.prefix}comparisons_${etype}`
2036
- )} WHERE \`guid\`=UNHEX(@guid);`,
2037
- {
2038
- etypes: [etype],
2039
- params: {
2040
- guid,
2041
- },
2042
- }
2043
- )
2044
- );
2787
+ },
2788
+ ),
2789
+ );
2790
+ promises.push(
2791
+ this.queryRun(
2792
+ `DELETE FROM ${MySQLDriver.escape(
2793
+ `${this.prefix}data_${etype}`,
2794
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2795
+ {
2796
+ etypes: [etype],
2797
+ params: {
2798
+ guid,
2799
+ },
2800
+ },
2801
+ ),
2802
+ );
2803
+ promises.push(
2804
+ this.queryRun(
2805
+ `DELETE FROM ${MySQLDriver.escape(
2806
+ `${this.prefix}references_${etype}`,
2807
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2808
+ {
2809
+ etypes: [etype],
2810
+ params: {
2811
+ guid,
2812
+ },
2813
+ },
2814
+ ),
2815
+ );
2816
+ }
2817
+ if (only == null || only === 'tokens') {
2818
+ promises.push(
2819
+ this.queryRun(
2820
+ `DELETE FROM ${MySQLDriver.escape(
2821
+ `${this.prefix}tokens_${etype}`,
2822
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2823
+ {
2824
+ etypes: [etype],
2825
+ params: {
2826
+ guid,
2827
+ },
2828
+ },
2829
+ ),
2830
+ );
2831
+ }
2832
+ if (only == null) {
2833
+ promises.push(
2834
+ this.queryRun(
2835
+ `DELETE FROM ${MySQLDriver.escape(
2836
+ `${this.prefix}uniques_${etype}`,
2837
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2838
+ {
2839
+ etypes: [etype],
2840
+ params: {
2841
+ guid,
2842
+ },
2843
+ },
2844
+ ),
2845
+ );
2846
+ }
2847
+
2848
+ await Promise.all(promises);
2849
+ promises = [];
2850
+
2851
+ if (only == null) {
2852
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull } =
2853
+ this.removeAndReturnACValues(etype, {}, sdata);
2854
+
2855
+ await this.queryRun(
2856
+ `INSERT INTO ${MySQLDriver.escape(
2857
+ `${this.prefix}entities_${etype}`,
2858
+ )} (\`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);`,
2859
+ {
2860
+ etypes: [etype],
2861
+ params: {
2862
+ guid,
2863
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2864
+ cdate: isNaN(cdate) ? null : cdate,
2865
+ mdate: isNaN(mdate) ? null : mdate,
2866
+ user,
2867
+ group,
2868
+ acUser,
2869
+ acGroup,
2870
+ acOther,
2871
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2872
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2873
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2874
+ },
2875
+ },
2876
+ );
2877
+
2878
+ for (const name in sdata) {
2879
+ if (
2880
+ typeof name !== 'string' ||
2881
+ !name.length ||
2882
+ name.match(/^\s|=|\s$/)
2883
+ ) {
2884
+ throw new EntityInvalidDataError(
2885
+ 'Property names must be non-empty strings without leading or trailing spaces or equals signs.',
2886
+ );
2887
+ }
2888
+
2889
+ const value = sdata[name];
2890
+ const uvalue = JSON.parse(value);
2891
+ if (value === undefined) {
2892
+ continue;
2893
+ }
2894
+ const storageValue =
2895
+ typeof uvalue === 'number'
2896
+ ? 'N'
2897
+ : typeof uvalue === 'string'
2898
+ ? 'S'
2899
+ : 'J';
2900
+ const jsonValue = storageValue === 'J' ? value : null;
2901
+
2045
2902
  promises.push(
2046
2903
  this.queryRun(
2047
- `DELETE FROM ${MySQLDriver.escape(
2048
- `${this.prefix}references_${etype}`
2049
- )} WHERE \`guid\`=UNHEX(@guid);`,
2904
+ `INSERT INTO ${MySQLDriver.escape(
2905
+ `${this.prefix}data_${etype}`,
2906
+ )} (\`guid\`, \`name\`, \`value\`, \`json\`, \`string\`, \`number\`, \`truthy\`) VALUES (UNHEX(@guid), @name, @storageValue, @jsonValue, @string, @number, @truthy);`,
2050
2907
  {
2051
2908
  etypes: [etype],
2052
2909
  params: {
2053
2910
  guid,
2911
+ name,
2912
+ storageValue,
2913
+ jsonValue,
2914
+ string: storageValue === 'J' ? null : `${uvalue}`,
2915
+ number: isNaN(Number(uvalue)) ? null : Number(uvalue),
2916
+ truthy: !!uvalue,
2054
2917
  },
2055
- }
2056
- )
2918
+ },
2919
+ ),
2057
2920
  );
2058
- await Promise.all(promises);
2059
- delete sdata.cdate;
2060
- delete sdata.mdate;
2061
- for (const name in sdata) {
2062
- const value = sdata[name];
2063
- const uvalue = JSON.parse(value);
2064
- if (value === undefined) {
2065
- continue;
2066
- }
2067
- const storageValue =
2068
- typeof uvalue === 'number'
2069
- ? 'N'
2070
- : typeof uvalue === 'string'
2071
- ? 'S'
2072
- : value;
2073
- const promises = [];
2074
- promises.push(
2075
- this.queryRun(
2076
- `INSERT INTO ${MySQLDriver.escape(
2077
- `${this.prefix}data_${etype}`
2078
- )} (\`guid\`, \`name\`, \`value\`) VALUES (UNHEX(@guid), @name, @storageValue);`,
2079
- {
2080
- etypes: [etype],
2081
- params: {
2082
- guid,
2083
- name,
2084
- storageValue,
2085
- },
2086
- }
2087
- )
2088
- );
2921
+
2922
+ const references = this.findReferences(value);
2923
+ for (const reference of references) {
2089
2924
  promises.push(
2090
2925
  this.queryRun(
2091
2926
  `INSERT INTO ${MySQLDriver.escape(
2092
- `${this.prefix}comparisons_${etype}`
2093
- )} (\`guid\`, \`name\`, \`truthy\`, \`string\`, \`number\`) VALUES (UNHEX(@guid), @name, @truthy, @string, @number);`,
2927
+ `${this.prefix}references_${etype}`,
2928
+ )} (\`guid\`, \`name\`, \`reference\`) VALUES (UNHEX(@guid), @name, UNHEX(@reference));`,
2094
2929
  {
2095
2930
  etypes: [etype],
2096
2931
  params: {
2097
2932
  guid,
2098
2933
  name,
2099
- truthy: !!uvalue,
2100
- string: `${uvalue}`,
2101
- number: isNaN(Number(uvalue)) ? null : Number(uvalue),
2934
+ reference,
2102
2935
  },
2103
- }
2104
- )
2936
+ },
2937
+ ),
2105
2938
  );
2106
- const references = this.findReferences(value);
2107
- for (const reference of references) {
2939
+ }
2940
+ }
2941
+ }
2942
+
2943
+ if (only === 'tilmeldAC') {
2944
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull } =
2945
+ this.removeAndReturnACValues(etype, {}, sdata);
2946
+
2947
+ promises.push(
2948
+ this.queryRun(
2949
+ `UPDATE ${MySQLDriver.escape(
2950
+ `${this.prefix}entities_${etype}`,
2951
+ )} 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);`,
2952
+ {
2953
+ etypes: [etype],
2954
+ params: {
2955
+ user,
2956
+ group,
2957
+ acUser,
2958
+ acGroup,
2959
+ acOther,
2960
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2961
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2962
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2963
+ guid,
2964
+ },
2965
+ },
2966
+ ),
2967
+ );
2968
+ }
2969
+
2970
+ const EntityClass = this.nymph.getEntityClassByEtype(etype);
2971
+
2972
+ if (only == null || only === 'tokens') {
2973
+ for (let name in sdata) {
2974
+ let tokenString: string | null = null;
2975
+ try {
2976
+ tokenString = EntityClass.getFTSText(name, JSON.parse(sdata[name]));
2977
+ } catch (e: any) {
2978
+ // Ignore error.
2979
+ }
2980
+
2981
+ if (tokenString != null) {
2982
+ const tokens = this.tokenizer.tokenize(tokenString);
2983
+ while (tokens.length) {
2984
+ const currentTokens = tokens.splice(0, 100);
2985
+ const params: { [k: string]: any } = {
2986
+ guid,
2987
+ name,
2988
+ };
2989
+ const values: string[] = [];
2990
+
2991
+ for (let i = 0; i < currentTokens.length; i++) {
2992
+ const token = currentTokens[i];
2993
+ params['token' + i] = token.token;
2994
+ params['position' + i] = token.position;
2995
+ params['stem' + i] = token.stem;
2996
+ values.push(
2997
+ '(UNHEX(@guid), @name, @token' +
2998
+ i +
2999
+ ', @position' +
3000
+ i +
3001
+ ', @stem' +
3002
+ i +
3003
+ ')',
3004
+ );
3005
+ }
3006
+
2108
3007
  promises.push(
2109
3008
  this.queryRun(
2110
3009
  `INSERT INTO ${MySQLDriver.escape(
2111
- `${this.prefix}references_${etype}`
2112
- )} (\`guid\`, \`name\`, \`reference\`) VALUES (UNHEX(@guid), @name, UNHEX(@reference));`,
3010
+ `${this.prefix}tokens_${etype}`,
3011
+ )} (\`guid\`, \`name\`, \`token\`, \`position\`, \`stem\`) VALUES ${values.join(', ')};`,
2113
3012
  {
2114
3013
  etypes: [etype],
2115
- params: {
2116
- guid,
2117
- name,
2118
- reference,
2119
- },
2120
- }
2121
- )
3014
+ params,
3015
+ },
3016
+ ),
2122
3017
  );
2123
3018
  }
2124
3019
  }
2125
- await Promise.all(promises);
2126
- },
2127
- async (name, curUid) => {
2128
- await this.queryRun(
2129
- `INSERT INTO ${MySQLDriver.escape(
2130
- `${this.prefix}uids`
2131
- )} (\`name\`, \`cur_uid\`) VALUES (@name, @curUid) ON DUPLICATE KEY UPDATE \`cur_uid\`=@curUid;`,
2132
- {
2133
- params: {
2134
- name,
2135
- curUid,
3020
+ }
3021
+ }
3022
+
3023
+ if (only == null) {
3024
+ const uniques = await EntityClass.getUniques({
3025
+ guid,
3026
+ cdate,
3027
+ mdate,
3028
+ tags,
3029
+ data: {},
3030
+ sdata,
3031
+ });
3032
+ for (const unique of uniques) {
3033
+ promises.push(
3034
+ this.queryRun(
3035
+ `INSERT INTO ${MySQLDriver.escape(
3036
+ `${this.prefix}uniques_${etype}`,
3037
+ )} (\`guid\`, \`unique\`) VALUES (UNHEX(@guid), @unique);`,
3038
+ {
3039
+ etypes: [etype],
3040
+ params: {
3041
+ guid,
3042
+ unique,
3043
+ },
2136
3044
  },
2137
- }
3045
+ ).catch((e: any) => {
3046
+ if (e instanceof EntityUniqueConstraintError) {
3047
+ this.nymph.config.debugError(
3048
+ 'mysql',
3049
+ `Import entity unique constraint violation for GUID "${guid}" on etype "${etype}": "${unique}"`,
3050
+ );
3051
+ }
3052
+ return e;
3053
+ }),
2138
3054
  );
2139
- },
2140
- async () => {
2141
- await this.internalTransaction('nymph-import');
2142
- },
2143
- async () => {
2144
- await this.commit('nymph-import');
2145
3055
  }
2146
- );
3056
+ }
2147
3057
 
2148
- return result;
3058
+ await Promise.all(promises);
3059
+ } catch (e: any) {
3060
+ this.nymph.config.debugError('mysql', `Import entity error: "${e}"`);
3061
+ throw e;
3062
+ }
3063
+ }
3064
+
3065
+ public async importUID({ name, value }: { name: string; value: number }) {
3066
+ if (name.length > 128) {
3067
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3068
+ }
3069
+ try {
3070
+ await this.internalTransaction(`nymph-import-uid-${name}`);
3071
+ await this.queryRun(
3072
+ `INSERT INTO ${MySQLDriver.escape(
3073
+ `${this.prefix}uids`,
3074
+ )} (\`name\`, \`cur_uid\`) VALUES (@name, @value) ON DUPLICATE KEY UPDATE \`cur_uid\`=@value;`,
3075
+ {
3076
+ params: {
3077
+ name,
3078
+ value,
3079
+ },
3080
+ },
3081
+ );
3082
+ await this.commit(`nymph-import-uid-${name}`);
2149
3083
  } catch (e: any) {
2150
- await this.rollback('nymph-import');
2151
- return false;
3084
+ this.nymph.config.debugError('mysql', `Import UID error: "${e}"`);
3085
+ await this.rollback(`nymph-import-uid-${name}`);
3086
+ throw e;
2152
3087
  }
2153
3088
  }
2154
3089
 
@@ -2156,72 +3091,80 @@ export default class MySQLDriver extends NymphDriver {
2156
3091
  if (name == null) {
2157
3092
  throw new InvalidParametersError('Name not given for UID.');
2158
3093
  }
3094
+ if (name.length > 128) {
3095
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3096
+ }
2159
3097
  await this.internalTransaction('nymph-newuid');
3098
+ let curUid: number | null = null;
2160
3099
  try {
2161
3100
  const lock = await this.queryGet(
2162
3101
  `SELECT GET_LOCK(${MySQLDriver.escapeValue(
2163
- `${this.prefix}uids_${name}`
2164
- )}, 10) AS \`lock\`;`
3102
+ `${this.prefix}uids_${name}`,
3103
+ )}, 10) AS \`lock\`;`,
2165
3104
  );
2166
3105
  if (lock.lock !== 1) {
2167
3106
  throw new QueryFailedError("Couldn't get lock for UID: " + name);
2168
3107
  }
2169
- let curUid: number | null = null;
2170
3108
  await this.queryRun(
2171
3109
  `INSERT INTO ${MySQLDriver.escape(
2172
- `${this.prefix}uids`
3110
+ `${this.prefix}uids`,
2173
3111
  )} (\`name\`, \`cur_uid\`) VALUES (@name, 1) ON DUPLICATE KEY UPDATE \`cur_uid\`=\`cur_uid\`+1;`,
2174
3112
  {
2175
3113
  params: {
2176
3114
  name,
2177
3115
  },
2178
- }
3116
+ },
2179
3117
  );
2180
3118
  const result = await this.queryGet(
2181
3119
  `SELECT \`cur_uid\` FROM ${MySQLDriver.escape(
2182
- `${this.prefix}uids`
3120
+ `${this.prefix}uids`,
2183
3121
  )} WHERE \`name\`=@name;`,
2184
3122
  {
2185
3123
  params: {
2186
3124
  name,
2187
3125
  },
2188
- }
3126
+ },
2189
3127
  );
2190
3128
  await this.queryRun(
2191
3129
  `SELECT RELEASE_LOCK(${MySQLDriver.escapeValue(
2192
- `${this.prefix}uids_${name}`
2193
- )});`
3130
+ `${this.prefix}uids_${name}`,
3131
+ )});`,
2194
3132
  );
2195
- await this.commit('nymph-newuid');
2196
3133
  curUid = result.cur_uid ?? null;
2197
- return curUid;
2198
3134
  } catch (e: any) {
3135
+ this.nymph.config.debugError('mysql', `New UID error: "${e}"`);
2199
3136
  if (e?.message !== "Couldn't get lock for UID: " + name) {
2200
3137
  await this.queryRun(
2201
3138
  `SELECT RELEASE_LOCK(${MySQLDriver.escapeValue(
2202
- `${this.prefix}uids_${name}`
2203
- )});`
3139
+ `${this.prefix}uids_${name}`,
3140
+ )});`,
2204
3141
  );
2205
3142
  }
2206
3143
  await this.rollback('nymph-newuid');
2207
3144
  throw e;
2208
3145
  }
3146
+
3147
+ await this.commit('nymph-newuid');
3148
+ return curUid;
2209
3149
  }
2210
3150
 
2211
3151
  public async renameUID(oldName: string, newName: string) {
2212
3152
  if (oldName == null || newName == null) {
2213
3153
  throw new InvalidParametersError('Name not given for UID.');
2214
3154
  }
3155
+ if (oldName.length > 128 || newName.length > 128) {
3156
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3157
+ }
2215
3158
  await this.queryRun(
2216
3159
  `UPDATE ${MySQLDriver.escape(
2217
- `${this.prefix}uids`
3160
+ `${this.prefix}uids`,
2218
3161
  )} SET \`name\`=@newName WHERE \`name\`=@oldName;`,
2219
3162
  {
2220
3163
  params: {
2221
3164
  newName,
2222
3165
  oldName,
2223
3166
  },
2224
- }
3167
+ },
2225
3168
  );
2226
3169
  return true;
2227
3170
  }
@@ -2229,7 +3172,7 @@ export default class MySQLDriver extends NymphDriver {
2229
3172
  public async rollback(name: string) {
2230
3173
  if (name == null || typeof name !== 'string' || name.length === 0) {
2231
3174
  throw new InvalidParametersError(
2232
- 'Transaction rollback attempted without a name.'
3175
+ 'Transaction rollback attempted without a name.',
2233
3176
  );
2234
3177
  }
2235
3178
  if (!this.transaction || this.transaction.count === 0) {
@@ -2254,13 +3197,26 @@ export default class MySQLDriver extends NymphDriver {
2254
3197
  guid: string,
2255
3198
  data: EntityData,
2256
3199
  sdata: SerializedEntityData,
2257
- etype: string
3200
+ uniques: string[],
3201
+ etype: string,
2258
3202
  ) => {
3203
+ const EntityClass = this.nymph.getEntityClassByEtype(etype);
3204
+
2259
3205
  const runInsertQuery = async (
2260
3206
  name: string,
2261
3207
  value: any,
2262
- svalue: string
3208
+ svalue: string,
2263
3209
  ) => {
3210
+ if (
3211
+ typeof name !== 'string' ||
3212
+ !name.length ||
3213
+ name.match(/^\s|=|\s$/)
3214
+ ) {
3215
+ throw new EntityInvalidDataError(
3216
+ 'Property names must be non-empty strings without leading or trailing spaces or equals signs.',
3217
+ );
3218
+ }
3219
+
2264
3220
  if (value === undefined) {
2265
3221
  return;
2266
3222
  }
@@ -2268,47 +3224,38 @@ export default class MySQLDriver extends NymphDriver {
2268
3224
  typeof value === 'number'
2269
3225
  ? 'N'
2270
3226
  : typeof value === 'string'
2271
- ? 'S'
2272
- : svalue;
3227
+ ? 'S'
3228
+ : 'J';
3229
+ const jsonValue = storageValue === 'J' ? svalue : null;
3230
+
2273
3231
  const promises = [];
3232
+
2274
3233
  promises.push(
2275
3234
  this.queryRun(
2276
3235
  `INSERT INTO ${MySQLDriver.escape(
2277
- `${this.prefix}data_${etype}`
2278
- )} (\`guid\`, \`name\`, \`value\`) VALUES (UNHEX(@guid), @name, @storageValue);`,
3236
+ `${this.prefix}data_${etype}`,
3237
+ )} (\`guid\`, \`name\`, \`value\`, \`json\`, \`string\`, \`number\`, \`truthy\`) VALUES (UNHEX(@guid), @name, @storageValue, @jsonValue, @string, @number, @truthy);`,
2279
3238
  {
2280
3239
  etypes: [etype],
2281
3240
  params: {
2282
3241
  guid,
2283
3242
  name,
2284
3243
  storageValue,
2285
- },
2286
- }
2287
- )
2288
- );
2289
- promises.push(
2290
- this.queryRun(
2291
- `INSERT INTO ${MySQLDriver.escape(
2292
- `${this.prefix}comparisons_${etype}`
2293
- )} (\`guid\`, \`name\`, \`truthy\`, \`string\`, \`number\`) VALUES (UNHEX(@guid), @name, @truthy, @string, @number);`,
2294
- {
2295
- etypes: [etype],
2296
- params: {
2297
- guid,
2298
- name,
2299
- truthy: !!value,
2300
- string: `${value}`,
3244
+ jsonValue,
3245
+ string: storageValue === 'J' ? null : `${value}`,
2301
3246
  number: isNaN(Number(value)) ? null : Number(value),
3247
+ truthy: !!value,
2302
3248
  },
2303
- }
2304
- )
3249
+ },
3250
+ ),
2305
3251
  );
3252
+
2306
3253
  const references = this.findReferences(svalue);
2307
3254
  for (const reference of references) {
2308
3255
  promises.push(
2309
3256
  this.queryRun(
2310
3257
  `INSERT INTO ${MySQLDriver.escape(
2311
- `${this.prefix}references_${etype}`
3258
+ `${this.prefix}references_${etype}`,
2312
3259
  )} (\`guid\`, \`name\`, \`reference\`) VALUES (UNHEX(@guid), @name, UNHEX(@reference));`,
2313
3260
  {
2314
3261
  etypes: [etype],
@@ -2317,12 +3264,85 @@ export default class MySQLDriver extends NymphDriver {
2317
3264
  name,
2318
3265
  reference,
2319
3266
  },
2320
- }
2321
- )
3267
+ },
3268
+ ),
2322
3269
  );
2323
3270
  }
3271
+
3272
+ let tokenString: string | null = null;
3273
+ try {
3274
+ tokenString = EntityClass.getFTSText(name, value);
3275
+ } catch (e: any) {
3276
+ // Ignore error.
3277
+ }
3278
+
3279
+ if (tokenString != null) {
3280
+ const tokens = this.tokenizer.tokenize(tokenString);
3281
+ while (tokens.length) {
3282
+ const currentTokens = tokens.splice(0, 100);
3283
+ const params: { [k: string]: any } = {
3284
+ guid,
3285
+ name,
3286
+ };
3287
+ const values: string[] = [];
3288
+
3289
+ for (let i = 0; i < currentTokens.length; i++) {
3290
+ const token = currentTokens[i];
3291
+ params['token' + i] = token.token;
3292
+ params['position' + i] = token.position;
3293
+ params['stem' + i] = token.stem;
3294
+ values.push(
3295
+ '(UNHEX(@guid), @name, @token' +
3296
+ i +
3297
+ ', @position' +
3298
+ i +
3299
+ ', @stem' +
3300
+ i +
3301
+ ')',
3302
+ );
3303
+ }
3304
+
3305
+ promises.push(
3306
+ this.queryRun(
3307
+ `INSERT INTO ${MySQLDriver.escape(
3308
+ `${this.prefix}tokens_${etype}`,
3309
+ )} (\`guid\`, \`name\`, \`token\`, \`position\`, \`stem\`) VALUES ${values.join(', ')};`,
3310
+ {
3311
+ etypes: [etype],
3312
+ params,
3313
+ },
3314
+ ),
3315
+ );
3316
+ }
3317
+ }
3318
+
2324
3319
  await Promise.all(promises);
2325
3320
  };
3321
+
3322
+ for (const unique of uniques) {
3323
+ try {
3324
+ await this.queryRun(
3325
+ `INSERT INTO ${MySQLDriver.escape(
3326
+ `${this.prefix}uniques_${etype}`,
3327
+ )} (\`guid\`, \`unique\`) VALUES (UNHEX(@guid), @unique);`,
3328
+ {
3329
+ etypes: [etype],
3330
+ params: {
3331
+ guid,
3332
+ unique,
3333
+ },
3334
+ },
3335
+ );
3336
+ } catch (e: any) {
3337
+ if (e instanceof EntityUniqueConstraintError) {
3338
+ this.nymph.config.debugError(
3339
+ 'mysql',
3340
+ `Save entity unique constraint violation for GUID "${guid}" on etype "${etype}": "${unique}"`,
3341
+ );
3342
+ }
3343
+ throw e;
3344
+ }
3345
+ }
2326
3346
  for (const name in data) {
2327
3347
  await runInsertQuery(name, data[name], JSON.stringify(data[name]));
2328
3348
  }
@@ -2330,109 +3350,207 @@ export default class MySQLDriver extends NymphDriver {
2330
3350
  await runInsertQuery(name, JSON.parse(sdata[name]), sdata[name]);
2331
3351
  }
2332
3352
  };
3353
+ let inTransaction = false;
2333
3354
  try {
2334
3355
  const result = await this.saveEntityRowLike(
2335
3356
  entity,
2336
- async (_entity, guid, tags, data, sdata, cdate, etype) => {
3357
+ async ({ guid, tags, data, sdata, uniques, cdate, etype }) => {
3358
+ if (
3359
+ Object.keys(data).length === 0 &&
3360
+ Object.keys(sdata).length === 0
3361
+ ) {
3362
+ throw new EntityInvalidDataError('Entity contains no data.');
3363
+ }
3364
+ for (let tag of tags) {
3365
+ if (
3366
+ typeof tag !== 'string' ||
3367
+ !tag.length ||
3368
+ tag.match(/[\x00-\x1F\x7F\[\],]/)
3369
+ ) {
3370
+ throw new EntityInvalidDataError(
3371
+ 'Tags must be non-empty strings without square brackets, control characters, or commas.',
3372
+ );
3373
+ }
3374
+ }
3375
+ let processedData = this.removeAndReturnACValues(
3376
+ etype,
3377
+ { ...data },
3378
+ { ...sdata },
3379
+ );
3380
+ ({ data, sdata } = processedData);
3381
+ let {
3382
+ user,
3383
+ group,
3384
+ acUser,
3385
+ acGroup,
3386
+ acOther,
3387
+ acRead,
3388
+ acWrite,
3389
+ acFull,
3390
+ } = processedData;
2337
3391
  await this.queryRun(
2338
3392
  `INSERT INTO ${MySQLDriver.escape(
2339
- `${this.prefix}entities_${etype}`
2340
- )} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`) VALUES (UNHEX(@guid), @tags, @cdate, @cdate);`,
3393
+ `${this.prefix}entities_${etype}`,
3394
+ )} (\`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);`,
2341
3395
  {
2342
3396
  etypes: [etype],
2343
3397
  params: {
2344
3398
  guid,
2345
- tags: ' ' + tags.join(' ') + ' ',
3399
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2346
3400
  cdate,
3401
+ user,
3402
+ group,
3403
+ acUser,
3404
+ acGroup,
3405
+ acOther,
3406
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
3407
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
3408
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2347
3409
  },
2348
- }
3410
+ },
2349
3411
  );
2350
- await insertData(guid, data, sdata, etype);
3412
+ await insertData(guid, data, sdata, uniques, etype);
2351
3413
  return true;
2352
3414
  },
2353
- async (entity, guid, tags, data, sdata, mdate, etype) => {
3415
+ async ({ entity, guid, tags, data, sdata, uniques, mdate, etype }) => {
3416
+ if (
3417
+ Object.keys(data).length === 0 &&
3418
+ Object.keys(sdata).length === 0
3419
+ ) {
3420
+ throw new EntityInvalidDataError('Entity contains no data.');
3421
+ }
3422
+ for (let tag of tags) {
3423
+ if (
3424
+ typeof tag !== 'string' ||
3425
+ !tag.length ||
3426
+ tag.match(/[\x00-\x1F\x7F\[\],]/)
3427
+ ) {
3428
+ throw new EntityInvalidDataError(
3429
+ 'Tags must be non-empty strings without square brackets, control characters, or commas.',
3430
+ );
3431
+ }
3432
+ }
3433
+ let processedData = this.removeAndReturnACValues(
3434
+ etype,
3435
+ { ...data },
3436
+ { ...sdata },
3437
+ );
3438
+ ({ data, sdata } = processedData);
3439
+ let {
3440
+ user,
3441
+ group,
3442
+ acUser,
3443
+ acGroup,
3444
+ acOther,
3445
+ acRead,
3446
+ acWrite,
3447
+ acFull,
3448
+ } = processedData;
2354
3449
  if (this.config.rowLocking) {
2355
3450
  const promises = [];
2356
3451
  promises.push(
2357
3452
  this.queryRun(
2358
3453
  `SELECT 1 FROM ${MySQLDriver.escape(
2359
- `${this.prefix}entities_${etype}`
3454
+ `${this.prefix}entities_${etype}`,
2360
3455
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2361
3456
  {
2362
3457
  etypes: [etype],
2363
3458
  params: {
2364
3459
  guid,
2365
3460
  },
2366
- }
2367
- )
3461
+ },
3462
+ ),
2368
3463
  );
2369
3464
  promises.push(
2370
3465
  this.queryRun(
2371
3466
  `SELECT 1 FROM ${MySQLDriver.escape(
2372
- `${this.prefix}data_${etype}`
3467
+ `${this.prefix}data_${etype}`,
2373
3468
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2374
3469
  {
2375
3470
  etypes: [etype],
2376
3471
  params: {
2377
3472
  guid,
2378
3473
  },
2379
- }
2380
- )
3474
+ },
3475
+ ),
2381
3476
  );
2382
3477
  promises.push(
2383
3478
  this.queryRun(
2384
3479
  `SELECT 1 FROM ${MySQLDriver.escape(
2385
- `${this.prefix}comparisons_${etype}`
3480
+ `${this.prefix}references_${etype}`,
2386
3481
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2387
3482
  {
2388
3483
  etypes: [etype],
2389
3484
  params: {
2390
3485
  guid,
2391
3486
  },
2392
- }
2393
- )
3487
+ },
3488
+ ),
2394
3489
  );
2395
3490
  promises.push(
2396
3491
  this.queryRun(
2397
3492
  `SELECT 1 FROM ${MySQLDriver.escape(
2398
- `${this.prefix}references_${etype}`
3493
+ `${this.prefix}tokens_${etype}`,
2399
3494
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2400
3495
  {
2401
3496
  etypes: [etype],
2402
3497
  params: {
2403
3498
  guid,
2404
3499
  },
2405
- }
2406
- )
3500
+ },
3501
+ ),
3502
+ );
3503
+ promises.push(
3504
+ this.queryRun(
3505
+ `SELECT 1 FROM ${MySQLDriver.escape(
3506
+ `${this.prefix}uniques_${etype}`,
3507
+ )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
3508
+ {
3509
+ etypes: [etype],
3510
+ params: {
3511
+ guid,
3512
+ },
3513
+ },
3514
+ ),
2407
3515
  );
2408
3516
  await Promise.all(promises);
2409
3517
  }
2410
3518
  if (this.config.tableLocking) {
2411
3519
  await this.queryRun(
2412
3520
  `LOCK TABLES ${MySQLDriver.escape(
2413
- `${this.prefix}entities_${etype}`
3521
+ `${this.prefix}entities_${etype}`,
2414
3522
  )} WRITE, ${MySQLDriver.escape(
2415
- `${this.prefix}data_${etype}`
3523
+ `${this.prefix}data_${etype}`,
2416
3524
  )} WRITE, ${MySQLDriver.escape(
2417
- `${this.prefix}comparisons_${etype}`
3525
+ `${this.prefix}references_${etype}`,
2418
3526
  )} WRITE, ${MySQLDriver.escape(
2419
- `${this.prefix}references_${etype}`
2420
- )} WRITE;`
3527
+ `${this.prefix}tokens_${etype}`,
3528
+ )} WRITE, ${MySQLDriver.escape(
3529
+ `${this.prefix}uniques_${etype}`,
3530
+ )} WRITE;`,
2421
3531
  );
2422
3532
  }
2423
3533
  const info = await this.queryRun(
2424
3534
  `UPDATE ${MySQLDriver.escape(
2425
- `${this.prefix}entities_${etype}`
2426
- )} SET \`tags\`=@tags, \`mdate\`=@mdate WHERE \`guid\`=UNHEX(@guid) AND \`mdate\` <= @emdate;`,
3535
+ `${this.prefix}entities_${etype}`,
3536
+ )} 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;`,
2427
3537
  {
2428
3538
  etypes: [etype],
2429
3539
  params: {
2430
- tags: ' ' + tags.join(' ') + ' ',
3540
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2431
3541
  mdate,
3542
+ user,
3543
+ group,
3544
+ acUser,
3545
+ acGroup,
3546
+ acOther,
3547
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
3548
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
3549
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2432
3550
  guid,
2433
3551
  emdate: isNaN(Number(entity.mdate)) ? 0 : Number(entity.mdate),
2434
3552
  },
2435
- }
3553
+ },
2436
3554
  );
2437
3555
  let success = false;
2438
3556
  if (info.changes === 1) {
@@ -2440,67 +3558,92 @@ export default class MySQLDriver extends NymphDriver {
2440
3558
  promises.push(
2441
3559
  this.queryRun(
2442
3560
  `DELETE FROM ${MySQLDriver.escape(
2443
- `${this.prefix}data_${etype}`
3561
+ `${this.prefix}data_${etype}`,
2444
3562
  )} WHERE \`guid\`=UNHEX(@guid);`,
2445
3563
  {
2446
3564
  etypes: [etype],
2447
3565
  params: {
2448
3566
  guid,
2449
3567
  },
2450
- }
2451
- )
3568
+ },
3569
+ ),
2452
3570
  );
2453
3571
  promises.push(
2454
3572
  this.queryRun(
2455
3573
  `DELETE FROM ${MySQLDriver.escape(
2456
- `${this.prefix}comparisons_${etype}`
3574
+ `${this.prefix}references_${etype}`,
2457
3575
  )} WHERE \`guid\`=UNHEX(@guid);`,
2458
3576
  {
2459
3577
  etypes: [etype],
2460
3578
  params: {
2461
3579
  guid,
2462
3580
  },
2463
- }
2464
- )
3581
+ },
3582
+ ),
2465
3583
  );
2466
3584
  promises.push(
2467
3585
  this.queryRun(
2468
3586
  `DELETE FROM ${MySQLDriver.escape(
2469
- `${this.prefix}references_${etype}`
3587
+ `${this.prefix}tokens_${etype}`,
2470
3588
  )} WHERE \`guid\`=UNHEX(@guid);`,
2471
3589
  {
2472
3590
  etypes: [etype],
2473
3591
  params: {
2474
3592
  guid,
2475
3593
  },
2476
- }
2477
- )
3594
+ },
3595
+ ),
3596
+ );
3597
+ promises.push(
3598
+ this.queryRun(
3599
+ `DELETE FROM ${MySQLDriver.escape(
3600
+ `${this.prefix}uniques_${etype}`,
3601
+ )} WHERE \`guid\`=UNHEX(@guid);`,
3602
+ {
3603
+ etypes: [etype],
3604
+ params: {
3605
+ guid,
3606
+ },
3607
+ },
3608
+ ),
2478
3609
  );
2479
3610
  await Promise.all(promises);
2480
- await insertData(guid, data, sdata, etype);
3611
+ await insertData(guid, data, sdata, uniques, etype);
2481
3612
  success = true;
2482
3613
  }
2483
3614
  if (this.config.tableLocking) {
2484
3615
  await this.queryRun('UNLOCK TABLES;');
2485
3616
  }
3617
+ if (!success && info.changes === 0) {
3618
+ throw new EntityConflictError(
3619
+ "Entity either doesn't exist or is newer in the DB.",
3620
+ );
3621
+ }
2486
3622
  return success;
2487
3623
  },
2488
3624
  async () => {
2489
3625
  await this.internalTransaction('nymph-save');
3626
+ inTransaction = true;
2490
3627
  },
2491
3628
  async (success) => {
2492
- if (success) {
2493
- await this.commit('nymph-save');
2494
- } else {
2495
- await this.rollback('nymph-save');
3629
+ if (inTransaction) {
3630
+ inTransaction = false;
3631
+ if (success) {
3632
+ success = await this.commit('nymph-save');
3633
+ } else {
3634
+ await this.rollback('nymph-save');
3635
+ }
2496
3636
  }
2497
3637
  return success;
2498
- }
3638
+ },
2499
3639
  );
2500
3640
 
2501
3641
  return result;
2502
3642
  } catch (e: any) {
2503
- await this.rollback('nymph-save');
3643
+ this.nymph.config.debugError('mysql', `Save entity error: "${e}"`);
3644
+ if (inTransaction) {
3645
+ await this.rollback('nymph-save');
3646
+ }
2504
3647
  throw e;
2505
3648
  }
2506
3649
  }
@@ -2509,58 +3652,214 @@ export default class MySQLDriver extends NymphDriver {
2509
3652
  if (name == null) {
2510
3653
  throw new InvalidParametersError('Name not given for UID.');
2511
3654
  }
3655
+ if (name.length > 128) {
3656
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3657
+ }
2512
3658
  await this.queryRun(
2513
3659
  `INSERT INTO ${MySQLDriver.escape(
2514
- `${this.prefix}uids`
3660
+ `${this.prefix}uids`,
2515
3661
  )} (\`name\`, \`cur_uid\`) VALUES (@name, @curUid) ON DUPLICATE KEY UPDATE \`cur_uid\`=@curUid;`,
2516
3662
  {
2517
3663
  params: {
2518
3664
  name,
2519
3665
  curUid,
2520
3666
  },
2521
- }
3667
+ },
2522
3668
  );
2523
3669
  return true;
2524
3670
  }
2525
3671
 
2526
- private async internalTransaction(name: string) {
3672
+ protected async internalTransaction(name: string, setOnSelf = true) {
2527
3673
  if (name == null || typeof name !== 'string' || name.length === 0) {
2528
3674
  throw new InvalidParametersError(
2529
- 'Transaction start attempted without a name.'
3675
+ 'Transaction start attempted without a name.',
2530
3676
  );
2531
3677
  }
2532
3678
 
2533
- if (!this.transaction || this.transaction.count === 0) {
3679
+ let transaction = this.transaction;
3680
+
3681
+ if (!transaction) {
2534
3682
  // Lock to one connection.
2535
- this.transaction = {
3683
+ transaction = {
2536
3684
  count: 0,
2537
3685
  connection: await this.getConnection(),
3686
+ latestPromise: Promise.resolve(),
2538
3687
  };
2539
- if (this.config.transactions) {
2540
- // We're not in a transaction yet, so start one.
2541
- await this.queryRun('START TRANSACTION;');
3688
+ if (setOnSelf) {
3689
+ this.transaction = transaction;
2542
3690
  }
2543
3691
  }
2544
3692
 
2545
- if (this.config.transactions) {
2546
- await this.queryRun(`SAVEPOINT ${MySQLDriver.escape(name)};`);
3693
+ if (this.config.transactions && transaction.count === 0) {
3694
+ // We're not in a transaction yet, so start one.
3695
+ await this.queryRun('START TRANSACTION;', { transaction });
2547
3696
  }
2548
3697
 
2549
- this.transaction.count++;
3698
+ transaction.count++;
3699
+
3700
+ if (this.config.transactions) {
3701
+ await this.queryRun(`SAVEPOINT ${MySQLDriver.escape(name)};`, {
3702
+ transaction,
3703
+ });
3704
+ }
2550
3705
 
2551
- return this.transaction;
3706
+ return transaction;
2552
3707
  }
2553
3708
 
2554
3709
  public async startTransaction(name: string) {
2555
- const inTransaction = this.inTransaction();
2556
- const transaction = await this.internalTransaction(name);
2557
- if (!inTransaction) {
2558
- this.transaction = null;
2559
- }
3710
+ const transaction = await this.internalTransaction(name, false);
2560
3711
 
2561
3712
  const nymph = this.nymph.clone();
2562
3713
  (nymph.driver as MySQLDriver).transaction = transaction;
2563
3714
 
2564
3715
  return nymph;
2565
3716
  }
3717
+
3718
+ private async removeTilmeldOldRows(etype: string) {
3719
+ await this.internalTransaction('nymph-remove-tilmeld-rows');
3720
+ try {
3721
+ for (let name of [
3722
+ 'user',
3723
+ 'group',
3724
+ 'acUser',
3725
+ 'acGroup',
3726
+ 'acOther',
3727
+ 'acRead',
3728
+ 'acWrite',
3729
+ 'acFull',
3730
+ ]) {
3731
+ await this.queryRun(
3732
+ `DELETE FROM ${MySQLDriver.escape(
3733
+ `${this.prefix}data_${etype}`,
3734
+ )} WHERE \`name\`=@name;`,
3735
+ {
3736
+ etypes: [etype],
3737
+ params: {
3738
+ name,
3739
+ },
3740
+ },
3741
+ );
3742
+ await this.queryRun(
3743
+ `DELETE FROM ${MySQLDriver.escape(
3744
+ `${this.prefix}references_${etype}`,
3745
+ )} WHERE \`name\`=@name;`,
3746
+ {
3747
+ etypes: [etype],
3748
+ params: {
3749
+ name,
3750
+ },
3751
+ },
3752
+ );
3753
+ await this.queryRun(
3754
+ `DELETE FROM ${MySQLDriver.escape(
3755
+ `${this.prefix}tokens_${etype}`,
3756
+ )} WHERE \`name\`=@name;`,
3757
+ {
3758
+ etypes: [etype],
3759
+ params: {
3760
+ name,
3761
+ },
3762
+ },
3763
+ );
3764
+ }
3765
+ } catch (e: any) {
3766
+ this.nymph.config.debugError(
3767
+ 'mysql',
3768
+ `Remove tilmeld rows error: "${e}"`,
3769
+ );
3770
+ await this.rollback('nymph-remove-tilmeld-rows');
3771
+ throw e;
3772
+ }
3773
+
3774
+ await this.commit('nymph-remove-tilmeld-rows');
3775
+ return true;
3776
+ }
3777
+
3778
+ public async needsMigration(): Promise<
3779
+ 'json' | 'tokens' | 'tilmeldColumns' | false
3780
+ > {
3781
+ const table = await this.queryGet(
3782
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix LIMIT 1;',
3783
+ {
3784
+ params: {
3785
+ db: this.config.database,
3786
+ prefix: this.prefix + 'data_' + '%',
3787
+ },
3788
+ },
3789
+ );
3790
+ if (table?.table_name) {
3791
+ const result = await this.queryGet(
3792
+ "SELECT 1 AS `exists` FROM `information_schema`.`columns` WHERE `table_schema`=@db AND `table_name`=@table AND `column_name`='json';",
3793
+ {
3794
+ params: {
3795
+ db: this.config.database,
3796
+ table: table.table_name,
3797
+ },
3798
+ },
3799
+ );
3800
+ if (!result?.exists) {
3801
+ return 'json';
3802
+ }
3803
+ }
3804
+ const table2 = await this.queryGet(
3805
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @tokenTable LIMIT 1;',
3806
+ {
3807
+ params: {
3808
+ db: this.config.database,
3809
+ tokenTable: this.prefix + 'tokens_' + '%',
3810
+ },
3811
+ },
3812
+ );
3813
+ if (!table2 || !table2.table_name) {
3814
+ return 'tokens';
3815
+ }
3816
+ const table3 = await this.queryGet(
3817
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix LIMIT 1;',
3818
+ {
3819
+ params: {
3820
+ db: this.config.database,
3821
+ prefix: this.prefix + 'entities_' + '%',
3822
+ },
3823
+ },
3824
+ );
3825
+ if (table3?.table_name) {
3826
+ const result = await this.queryGet(
3827
+ "SELECT 1 AS `exists` FROM `information_schema`.`columns` WHERE `table_schema`=@db AND `table_name`=@table AND `column_name`='user';",
3828
+ {
3829
+ params: {
3830
+ db: this.config.database,
3831
+ table: table3.table_name,
3832
+ },
3833
+ },
3834
+ );
3835
+ if (!result?.exists) {
3836
+ return 'tilmeldColumns';
3837
+ }
3838
+ }
3839
+ return false;
3840
+ }
3841
+
3842
+ public async liveMigration(
3843
+ migrationType: 'tokenTables' | 'tilmeldColumns' | 'tilmeldRemoveOldRows',
3844
+ ) {
3845
+ if (migrationType === 'tokenTables') {
3846
+ const etypes = await this.getEtypes();
3847
+
3848
+ for (let etype of etypes) {
3849
+ await this.createTokensTable(etype);
3850
+ }
3851
+ } else if (migrationType === 'tilmeldColumns') {
3852
+ const etypes = await this.getEtypes();
3853
+
3854
+ for (let etype of etypes) {
3855
+ await this.addTilmeldColumnsAndIndexes(etype);
3856
+ }
3857
+ } else if (migrationType === 'tilmeldRemoveOldRows') {
3858
+ const etypes = await this.getEtypes();
3859
+
3860
+ for (let etype of etypes) {
3861
+ await this.removeTilmeldOldRows(etype);
3862
+ }
3863
+ }
3864
+ }
2566
3865
  }