strapi/packages/core/database/lib/query/query-builder.js

374 lines
7.5 KiB
JavaScript
Raw Normal View History

2021-06-17 16:17:15 +02:00
'use strict';
const _ = require('lodash/fp');
const helpers = require('./helpers');
const createQueryBuilder = (uid, db) => {
const meta = db.metadata.get(uid);
const { tableName } = meta;
2021-07-01 14:32:50 +02:00
const state = {
2021-06-17 16:17:15 +02:00
type: 'select',
select: [],
count: null,
first: false,
data: null,
where: [],
joins: [],
populate: null,
limit: null,
offset: null,
orderBy: [],
groupBy: [],
};
let counter = 0;
const getAlias = () => `t${counter++}`;
return {
alias: getAlias(),
getAlias,
state,
2021-06-17 16:17:15 +02:00
2021-08-06 10:51:34 +02:00
select(args) {
state.type = 'select';
state.select = _.uniq(_.castArray(args));
2021-08-11 09:34:55 +02:00
return this;
},
addSelect(args) {
state.select = _.uniq([...state.select, ..._.castArray(args)]);
2021-08-06 10:51:34 +02:00
return this;
},
2021-06-17 16:17:15 +02:00
insert(data) {
state.type = 'insert';
state.data = data;
return this;
},
delete() {
state.type = 'delete';
return this;
},
ref(name) {
return db.connection.ref(helpers.toColumnName(meta, name));
},
2021-06-17 16:17:15 +02:00
update(data) {
state.type = 'update';
state.data = data;
return this;
},
count(count = '*') {
state.type = 'count';
state.count = count;
return this;
},
2021-06-22 17:13:11 +02:00
where(where = {}) {
if (!_.isPlainObject(where)) {
throw new Error('Where must be an object');
}
2021-06-17 16:17:15 +02:00
state.where.push(where);
2021-06-17 16:17:15 +02:00
return this;
},
limit(limit) {
state.limit = limit;
return this;
},
offset(offset) {
state.offset = offset;
return this;
},
orderBy(orderBy) {
state.orderBy = orderBy;
2021-06-17 16:17:15 +02:00
return this;
},
groupBy(groupBy) {
state.groupBy = groupBy;
2021-06-24 18:28:36 +02:00
return this;
2021-06-17 16:17:15 +02:00
},
populate(populate) {
state.populate = populate;
2021-07-28 21:03:32 +02:00
return this;
},
2021-06-17 16:17:15 +02:00
2021-07-28 21:03:32 +02:00
search(query) {
state.search = query;
2021-06-17 16:17:15 +02:00
return this;
},
init(params = {}) {
const { _q, filters, where, select, limit, offset, orderBy, groupBy, populate } = params;
2021-06-17 16:17:15 +02:00
2021-08-09 18:20:27 +02:00
if (!_.isNil(where)) {
2021-06-17 16:17:15 +02:00
this.where(where);
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(_q)) {
2021-07-28 21:03:32 +02:00
this.search(_q);
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(select)) {
2021-06-17 16:17:15 +02:00
this.select(select);
} else {
this.select('*');
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(limit)) {
2021-06-17 16:17:15 +02:00
this.limit(limit);
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(offset)) {
2021-06-17 16:17:15 +02:00
this.offset(offset);
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(orderBy)) {
2021-06-17 16:17:15 +02:00
this.orderBy(orderBy);
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(groupBy)) {
2021-06-17 16:17:15 +02:00
this.groupBy(groupBy);
}
2021-08-09 18:20:27 +02:00
if (!_.isNil(populate)) {
2021-06-17 16:17:15 +02:00
this.populate(populate);
}
if (!_.isNil(filters)) {
this.filters(filters);
}
2021-06-17 16:17:15 +02:00
return this;
},
filters(filters) {
state.filters = filters;
},
2021-06-17 16:17:15 +02:00
first() {
state.first = true;
return this;
},
join(join) {
state.joins.push(join);
return this;
},
mustUseAlias() {
return ['select', 'count'].includes(state.type);
},
aliasColumn(key, alias) {
if (typeof key !== 'string') {
return key;
2021-07-08 18:15:32 +02:00
}
if (key.indexOf('.') >= 0) {
return key;
2021-09-16 23:29:25 +02:00
}
if (!_.isNil(alias)) {
return `${alias}.${key}`;
}
return this.mustUseAlias() ? `${this.alias}.${key}` : key;
2021-06-17 16:17:15 +02:00
},
2021-07-08 18:15:32 +02:00
raw(...args) {
return db.connection.raw(...args);
},
shouldUseSubQuery() {
return ['delete', 'update'].includes(state.type) && state.joins.length > 0;
},
2021-06-24 18:28:36 +02:00
runSubQuery() {
this.select('id');
const subQB = this.getKnexQuery();
2021-06-17 16:17:15 +02:00
const nestedSubQuery = db
.getConnection()
.select('id')
.from(subQB.as('subQuery'));
return db
.getConnection(tableName)
[state.type]()
.whereIn('id', nestedSubQuery);
},
processState() {
state.orderBy = helpers.processOrderBy(state.orderBy, { qb: this, uid, db });
if (!_.isNil(state.filters)) {
if (_.isFunction(state.filters)) {
const filters = state.filters({ qb: this, uid, meta, db });
if (!_.isNil(filters)) {
state.where.push(filters);
}
} else {
state.where.push(state.filters);
}
}
state.where = helpers.processWhere(state.where, { qb: this, uid, db });
state.populate = helpers.processPopulate(state.populate, { qb: this, uid, db });
state.data = helpers.toRow(meta, state.data);
2021-09-22 18:49:04 +02:00
this.processSelect();
},
shouldUseDistinct() {
return state.joins.length > 0 && _.isEmpty(state.groupBy);
},
processSelect() {
state.select = state.select.map(field => helpers.toColumnName(meta, field));
if (this.shouldUseDistinct()) {
const joinsOrderByColumns = state.joins.flatMap(join => {
return _.keys(join.orderBy).map(key => this.aliasColumn(key, join.alias));
});
const orderByColumns = state.orderBy.map(({ column }) => column);
2021-09-22 20:10:48 +02:00
state.select = _.uniq([...joinsOrderByColumns, ...orderByColumns, ...state.select]);
2021-09-22 18:49:04 +02:00
}
},
getKnexQuery() {
2021-07-08 18:15:32 +02:00
if (!state.type) {
this.select('*');
}
const aliasedTableName = this.mustUseAlias() ? `${tableName} as ${this.alias}` : tableName;
const qb = db.getConnection(aliasedTableName);
if (this.shouldUseSubQuery()) {
return this.runSubQuery();
}
this.processState();
2021-07-05 18:35:16 +02:00
switch (state.type) {
case 'select': {
2021-09-22 18:49:04 +02:00
qb.select(state.select.map(column => this.aliasColumn(column)));
2021-09-21 19:16:25 +02:00
2021-09-22 18:49:04 +02:00
if (this.shouldUseDistinct()) {
qb.distinct();
2021-06-17 16:17:15 +02:00
}
2021-07-05 18:35:16 +02:00
break;
2021-06-24 18:28:36 +02:00
}
2021-07-05 18:35:16 +02:00
case 'count': {
qb.count({ count: state.count });
break;
2021-06-17 16:17:15 +02:00
}
2021-07-05 18:35:16 +02:00
case 'insert': {
qb.insert(state.data);
2021-06-17 16:17:15 +02:00
2021-07-05 18:35:16 +02:00
if (db.dialect.useReturning() && _.has('id', meta.attributes)) {
qb.returning('id');
}
2021-06-17 16:17:15 +02:00
2021-07-05 18:35:16 +02:00
break;
2021-06-24 18:28:36 +02:00
}
2021-07-05 18:35:16 +02:00
case 'update': {
qb.update(state.data);
break;
2021-06-24 18:28:36 +02:00
}
2021-07-05 18:35:16 +02:00
case 'delete': {
2021-09-16 23:29:25 +02:00
qb.delete();
break;
}
case 'truncate': {
db.truncate();
2021-07-05 18:35:16 +02:00
break;
2021-06-24 18:28:36 +02:00
}
2021-07-05 18:35:16 +02:00
}
2021-06-17 16:17:15 +02:00
2021-07-05 18:35:16 +02:00
if (state.limit) {
qb.limit(state.limit);
}
2021-06-17 16:17:15 +02:00
2021-07-05 18:35:16 +02:00
if (state.offset) {
qb.offset(state.offset);
}
if (state.orderBy.length > 0) {
qb.orderBy(state.orderBy);
}
if (state.first) {
qb.first();
}
if (state.groupBy.length > 0) {
qb.groupBy(state.groupBy);
}
2021-09-16 15:32:27 +02:00
// if there are joins and it is a delete or update use a sub query
2021-07-05 18:35:16 +02:00
if (state.where) {
helpers.applyWhere(qb, state.where);
}
2021-09-16 15:32:27 +02:00
// if there are joins and it is a delete or update use a sub query
2021-07-28 21:03:32 +02:00
if (state.search) {
qb.where(subQb => {
helpers.applySearch(subQb, state.search, { qb: this, db, uid });
2021-07-28 21:03:32 +02:00
});
}
2021-07-05 18:35:16 +02:00
if (state.joins.length > 0) {
helpers.applyJoins(qb, state.joins);
}
return qb;
},
async execute({ mapResults = true } = {}) {
try {
const qb = this.getKnexQuery();
2021-06-17 16:17:15 +02:00
2021-06-28 21:37:44 +02:00
const rows = await qb;
2021-06-17 16:17:15 +02:00
2021-06-30 20:00:03 +02:00
if (state.populate && !_.isNil(rows)) {
await helpers.applyPopulate(_.castArray(rows), state.populate, { qb: this, uid, db });
2021-06-28 21:37:44 +02:00
}
2021-06-17 16:17:15 +02:00
2021-06-30 20:00:03 +02:00
let results = rows;
if (mapResults && state.type === 'select') {
2021-06-30 21:17:32 +02:00
results = helpers.fromRow(meta, rows);
2021-06-24 18:28:36 +02:00
}
2021-06-17 16:17:15 +02:00
2021-06-24 18:28:36 +02:00
return results;
} catch (error) {
db.dialect.transformErrors(error);
}
2021-06-17 16:17:15 +02:00
},
};
};
module.exports = createQueryBuilder;