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

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