query-generator.js
11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
'use strict';
/* jshint -W110 */
const Utils = require('../../utils');
const Transaction = require('../../transaction');
const _ = require('lodash');
const MySqlQueryGenerator = Utils._.extend(
Utils._.clone(require('../abstract/query-generator')),
Utils._.clone(require('../mysql/query-generator'))
);
const QueryGenerator = {
options: {},
dialect: 'sqlite',
createSchema() {
return "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
},
showSchemasQuery() {
return "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
},
versionQuery() {
return 'SELECT sqlite_version() as `version`';
},
createTableQuery(tableName, attributes, options) {
options = options || {};
const primaryKeys = [];
const needsMultiplePrimaryKeys = (Utils._.values(attributes).filter(definition => _.includes(definition, 'PRIMARY KEY')).length > 1);
const attrArray = [];
for (const attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
let dataType = attributes[attr];
const containsAutoIncrement = Utils._.includes(dataType, 'AUTOINCREMENT');
if (containsAutoIncrement) {
dataType = dataType.replace(/BIGINT/, 'INTEGER');
}
let dataTypeString = dataType;
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (Utils._.includes(dataType, 'INTEGER')) { // Only INTEGER is allowed for primary key, see https://github.com/sequelize/sequelize/issues/969 (no lenght, unsigned etc)
dataTypeString = containsAutoIncrement ? 'INTEGER PRIMARY KEY AUTOINCREMENT' : 'INTEGER PRIMARY KEY';
}
if (needsMultiplePrimaryKeys) {
primaryKeys.push(attr);
dataTypeString = dataType.replace(/PRIMARY KEY/, 'NOT NULL');
}
}
attrArray.push(this.quoteIdentifier(attr) + ' ' + dataTypeString);
}
}
const table = this.quoteTable(tableName);
let attrStr = attrArray.join(', ');
const pkString = primaryKeys.map(pk => this.quoteIdentifier(pk)).join(', ');
if (!!options.uniqueKeys) {
Utils._.each(options.uniqueKeys, columns => {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
attrStr += ', UNIQUE (' + columns.fields.join(', ') + ')';
}
});
}
if (pkString.length > 0) {
attrStr += ', PRIMARY KEY (' + pkString + ')';
}
const sql = `CREATE TABLE IF NOT EXISTS ${table} (${attrStr});`;
return this.replaceBooleanDefaults(sql);
},
booleanValue(value){
return !!value ? 1 : 0;
},
addColumnQuery(table, key, dataType) {
const attributes = {};
attributes[key] = dataType;
const fields = this.attributesToSQL(attributes, {context: 'addColumn'});
const attribute = this.quoteIdentifier(key) + ' ' + fields[key];
const sql = `ALTER TABLE ${this.quoteTable(table)} ADD ${attribute};`;
return this.replaceBooleanDefaults(sql);
},
showTablesQuery() {
return "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
},
upsertQuery(tableName, insertValues, updateValues, where, rawAttributes, options) {
options.ignore = true;
const sql = this.insertQuery(tableName, insertValues, rawAttributes, options) + ' ' + this.updateQuery(tableName, updateValues, where, options, rawAttributes);
return sql;
},
updateQuery(tableName, attrValueHash, where, options, attributes) {
options = options || {};
_.defaults(options, this.options);
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, options.omitNull, options);
const modelAttributeMap = {};
const values = [];
if (attributes) {
_.each(attributes, (attribute, key) => {
modelAttributeMap[key] = attribute;
if (attribute.field) {
modelAttributeMap[attribute.field] = attribute;
}
});
}
for (const key in attrValueHash) {
const value = attrValueHash[key];
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, (modelAttributeMap && modelAttributeMap[key] || undefined), { context: 'UPDATE' }));
}
return `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} ${this.whereQuery(where)}`;
},
deleteQuery(tableName, where, options) {
options = options || {};
let whereClause = this.getWhereConditions(where);
if (whereClause) {
whereClause = ' WHERE ' + whereClause;
}
return `DELETE FROM ${this.quoteTable(tableName)}${whereClause}`;
},
attributesToSQL(attributes) {
const result = {};
for (const name in attributes) {
const dataType = attributes[name];
const fieldName = dataType.field || name;
if (Utils._.isObject(dataType)) {
let sql = dataType.type.toString();
if (dataType.hasOwnProperty('allowNull') && !dataType.allowNull) {
sql += ' NOT NULL';
}
if (Utils.defaultValueSchemable(dataType.defaultValue)) {
// TODO thoroughly check that DataTypes.NOW will properly
// get populated on all databases as DEFAULT value
// i.e. mysql requires: DEFAULT CURRENT_TIMESTAMP
sql += ' DEFAULT ' + this.escape(dataType.defaultValue, dataType);
}
if (dataType.unique === true) {
sql += ' UNIQUE';
}
if (dataType.primaryKey) {
sql += ' PRIMARY KEY';
if (dataType.autoIncrement) {
sql += ' AUTOINCREMENT';
}
}
if(dataType.references) {
const referencesTable = this.quoteTable(dataType.references.model);
let referencesKey;
if(dataType.references.key) {
referencesKey = this.quoteIdentifier(dataType.references.key);
} else {
referencesKey = this.quoteIdentifier('id');
}
sql += ` REFERENCES ${referencesTable} (${referencesKey})`;
if(dataType.onDelete) {
sql += ' ON DELETE ' + dataType.onDelete.toUpperCase();
}
if(dataType.onUpdate) {
sql += ' ON UPDATE ' + dataType.onUpdate.toUpperCase();
}
}
result[fieldName] = sql;
} else {
result[fieldName] = dataType;
}
}
return result;
},
findAutoIncrementField(factory) {
const fields = [];
for (const name in factory.attributes) {
if (factory.attributes.hasOwnProperty(name)) {
const definition = factory.attributes[name];
if (definition && definition.autoIncrement) {
fields.push(name);
}
}
}
return fields;
},
showIndexesQuery(tableName) {
return `PRAGMA INDEX_LIST(${this.quoteTable(tableName)})`;
},
removeIndexQuery(tableName, indexNameOrAttributes) {
let indexName = indexNameOrAttributes;
if (typeof indexName !== 'string') {
indexName = Utils.inflection.underscore(tableName + '_' + indexNameOrAttributes.join('_'));
}
return 'DROP INDEX IF EXISTS ' + indexName;
},
describeTableQuery(tableName, schema, schemaDelimiter) {
const table = {
$schema: schema,
$schemaDelimiter: schemaDelimiter,
tableName
};
return `PRAGMA TABLE_INFO(${this.quoteTable(this.addSchema(table))});`;
},
removeColumnQuery(tableName, attributes) {
attributes = this.attributesToSQL(attributes);
let backupTableName;
if (typeof tableName === 'object') {
backupTableName = {
tableName: tableName.tableName + '_backup',
schema: tableName.schema
};
} else {
backupTableName = tableName + '_backup';
}
const quotedTableName = this.quoteTable(tableName);
const quotedBackupTableName = this.quoteTable(backupTableName);
const attributeNames = Object.keys(attributes).join(', ');
return this.createTableQuery(backupTableName, attributes).replace('CREATE TABLE', 'CREATE TEMPORARY TABLE')
+ `INSERT INTO ${quotedBackupTableName} SELECT ${attributeNames} FROM ${quotedTableName};`
+ `DROP TABLE ${quotedTableName};`
+ this.createTableQuery(tableName, attributes)
+ `INSERT INTO ${quotedTableName} SELECT ${attributeNames} FROM ${quotedBackupTableName};`
+ `DROP TABLE ${quotedBackupTableName};`;
},
renameColumnQuery(tableName, attrNameBefore, attrNameAfter, attributes) {
let backupTableName;
attributes = this.attributesToSQL(attributes);
if (typeof tableName === 'object') {
backupTableName = {
tableName: tableName.tableName + '_backup',
schema: tableName.schema
};
} else {
backupTableName = tableName + '_backup';
}
const quotedTableName = this.quoteTable(tableName);
const quotedBackupTableName = this.quoteTable(backupTableName);
const attributeNamesImport = Object.keys(attributes).map(attr =>
(attrNameAfter === attr) ? this.quoteIdentifier(attrNameBefore) + ' AS ' + this.quoteIdentifier(attr) : this.quoteIdentifier(attr)
).join(', ');
const attributeNamesExport = Object.keys(attributes).map(attr => this.quoteIdentifier(attr)).join(', ');
return this.createTableQuery(backupTableName, attributes).replace('CREATE TABLE', 'CREATE TEMPORARY TABLE')
+ `INSERT INTO ${quotedBackupTableName} SELECT ${attributeNamesImport} FROM ${quotedTableName};`
+ `DROP TABLE ${quotedTableName};`
+ this.createTableQuery(tableName, attributes)
+ `INSERT INTO ${quotedTableName} SELECT ${attributeNamesExport} FROM ${quotedBackupTableName};`
+ `DROP TABLE ${quotedBackupTableName};`;
},
startTransactionQuery(transaction, options) {
if (transaction.parent) {
return 'SAVEPOINT ' + this.quoteIdentifier(transaction.name) + ';';
}
return 'BEGIN ' + transaction.options.type + ' TRANSACTION;';
},
setAutocommitQuery() {
// SQLite does not support SET autocommit
return null;
},
setIsolationLevelQuery(value) {
switch (value) {
case Transaction.ISOLATION_LEVELS.REPEATABLE_READ:
return '-- SQLite is not able to choose the isolation level REPEATABLE READ.';
case Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED:
return 'PRAGMA read_uncommitted = ON;';
case Transaction.ISOLATION_LEVELS.READ_COMMITTED:
return 'PRAGMA read_uncommitted = OFF;';
case Transaction.ISOLATION_LEVELS.SERIALIZABLE:
return "-- SQLite's default isolation level is SERIALIZABLE. Nothing to do.";
default:
throw new Error('Unknown isolation level: ' + value);
}
},
replaceBooleanDefaults(sql) {
return sql.replace(/DEFAULT '?false'?/g, 'DEFAULT 0').replace(/DEFAULT '?true'?/g, 'DEFAULT 1');
},
quoteIdentifier(identifier) {
if (identifier === '*') return identifier;
return Utils.addTicks(identifier, '`');
},
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {String} tableName The name of the table.
* @param {String} schemaName The name of the schema.
* @return {String} The generated sql query.
*/
getForeignKeysQuery(tableName, schemaName) {
return `PRAGMA foreign_key_list(${tableName})`;
}
};
module.exports = Utils._.extend({}, MySqlQueryGenerator, QueryGenerator);