| 1288 | @private |
| 1289 | */ |
| 1290 | selectQuery(tableName, options, model) { |
| 1291 | options = options || {}; |
| 1292 | const limit = options.limit; |
| 1293 | const mainQueryItems = []; |
| 1294 | const subQueryItems = []; |
| 1295 | const subQuery = options.subQuery === undefined ? limit && options.hasMultiAssociation : options.subQuery; |
| 1296 | const attributes = { |
| 1297 | main: options.attributes && options.attributes.slice(), |
| 1298 | subQuery: null |
| 1299 | }; |
| 1300 | const mainTable = { |
| 1301 | name: tableName, |
| 1302 | quotedName: null, |
| 1303 | as: null, |
| 1304 | model |
| 1305 | }; |
| 1306 | const topLevelInfo = { |
| 1307 | names: mainTable, |
| 1308 | options, |
| 1309 | subQuery |
| 1310 | }; |
| 1311 | let mainJoinQueries = []; |
| 1312 | let subJoinQueries = []; |
| 1313 | let query; |
| 1314 | |
| 1315 | // Aliases can be passed through subqueries and we don't want to reset them |
| 1316 | if (this.options.minifyAliases && !options.aliasesMapping) { |
| 1317 | options.aliasesMapping = new Map(); |
| 1318 | options.aliasesByTable = {}; |
| 1319 | options.includeAliases = new Map(); |
| 1320 | } |
| 1321 | |
| 1322 | // resolve table name options |
| 1323 | if (options.tableAs) { |
| 1324 | mainTable.as = this.quoteIdentifier(options.tableAs); |
| 1325 | } else if (!Array.isArray(mainTable.name) && mainTable.model) { |
| 1326 | mainTable.as = this.quoteIdentifier(mainTable.model.name); |
| 1327 | } |
| 1328 | |
| 1329 | mainTable.quotedName = !Array.isArray(mainTable.name) ? this.quoteTable(mainTable.name) : tableName.map(t => { |
| 1330 | return Array.isArray(t) ? this.quoteTable(t[0], t[1]) : this.quoteTable(t, true); |
| 1331 | }).join(', '); |
| 1332 | |
| 1333 | if (subQuery && attributes.main) { |
| 1334 | for (const keyAtt of mainTable.model.primaryKeyAttributes) { |
| 1335 | // Check if mainAttributes contain the primary key of the model either as a field or an aliased field |
| 1336 | if (!attributes.main.some(attr => keyAtt === attr || keyAtt === attr[0] || keyAtt === attr[1])) { |
| 1337 | attributes.main.push(mainTable.model.rawAttributes[keyAtt].field ? [keyAtt, mainTable.model.rawAttributes[keyAtt].field] : keyAtt); |
| 1338 | } |
| 1339 | } |
| 1340 | } |
| 1341 | |
| 1342 | attributes.main = this.escapeAttributes(attributes.main, options, mainTable.as); |
| 1343 | attributes.main = attributes.main || (options.include ? [`${mainTable.as}.*`] : ['*']); |
| 1344 | |
| 1345 | // If subquery, we add the mainAttributes to the subQuery and set the mainAttributes to select * from subquery |
| 1346 | if (subQuery || options.groupedLimit) { |
| 1347 | // We need primary keys |