123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474 |
- const getModel = () => require('../../model/Model');
- const Relation = require('../Relation');
- const RelationProperty = require('../RelationProperty');
- const { ref } = require('../../queryBuilder/ReferenceBuilder');
- const { isSqlite, isMySql } = require('../../utils/knexUtils');
- const { inheritModel } = require('../../model/inheritModel');
- const { resolveModel } = require('../../utils/resolveModel');
- const { mapAfterAllReturn } = require('../../utils/promiseUtils');
- const ManyToManyFindOperation = require('./find/ManyToManyFindOperation');
- const ManyToManyInsertOperation = require('./insert/ManyToManyInsertOperation');
- const ManyToManyRelateOperation = require('./relate/ManyToManyRelateOperation');
- const ManyToManyUnrelateOperation = require('./unrelate/ManyToManyUnrelateOperation');
- const ManyToManyUnrelateMySqlOperation = require('./unrelate/ManyToManyUnrelateMySqlOperation');
- const ManyToManyUnrelateSqliteOperation = require('./unrelate/ManyToManyUnrelateSqliteOperation');
- const ManyToManyUpdateOperation = require('./update/ManyToManyUpdateOperation');
- const ManyToManyUpdateMySqlOperation = require('./update/ManyToManyUpdateMySqlOperation');
- const ManyToManyUpdateSqliteOperation = require('./update/ManyToManyUpdateSqliteOperation');
- const ManyToManyDeleteOperation = require('./delete/ManyToManyDeleteOperation');
- const ManyToManyDeleteMySqlOperation = require('./delete/ManyToManyDeleteMySqlOperation');
- const ManyToManyDeleteSqliteOperation = require('./delete/ManyToManyDeleteSqliteOperation');
- class ManyToManyRelation extends Relation {
- setMapping(mapping) {
- const retVal = super.setMapping(mapping);
- let ctx = {
- mapping,
- ownerModelClass: this.ownerModelClass,
- relatedModelClass: this.relatedModelClass,
- ownerProp: this.ownerProp,
- relatedProp: this.relatedProp,
- joinTableModelClass: null,
- joinTableOwnerProp: null,
- joinTableRelatedProp: null,
- joinTableBeforeInsert: null,
- joinTableExtras: [],
- createError: msg => this.createError(msg)
- };
- ctx = checkThroughObject(ctx);
- ctx = resolveJoinModelClassIfDefined(ctx);
- ctx = createJoinProperties(ctx);
- ctx = parseExtras(ctx);
- ctx = parseBeforeInsert(ctx);
- ctx = finalizeJoinModelClass(ctx);
- this.joinTableExtras = ctx.joinTableExtras;
- this.joinTableModelClass = ctx.joinTableModelClass;
- this.joinTableOwnerProp = ctx.joinTableOwnerProp;
- this.joinTableRelatedProp = ctx.joinTableRelatedProp;
- this.joinTableBeforeInsert = ctx.joinTableBeforeInsert;
- return retVal;
- }
- get forbiddenMappingProperties() {
- return [];
- }
- joinTableAlias(builder) {
- const table = builder.tableRefFor(this.joinTableModelClass);
- return `${table}_rel_${this.name}`;
- }
- findQuery(builder, opt) {
- const joinTableOwnerRefs = this.joinTableOwnerProp.refs(builder);
- builder.join(this.joinTable, join => {
- for (let i = 0, l = this.relatedProp.size; i < l; ++i) {
- const relatedRef = this.relatedProp.ref(builder, i);
- const joinTableRelatedRef = this.joinTableRelatedProp.ref(builder, i);
- join.on(relatedRef, joinTableRelatedRef);
- }
- });
- if (opt.isColumnRef) {
- for (let i = 0, l = joinTableOwnerRefs.length; i < l; ++i) {
- builder.where(joinTableOwnerRefs[i], ref(opt.ownerIds[i]));
- }
- } else if (containsNonNull(opt.ownerIds)) {
- builder.whereInComposite(joinTableOwnerRefs, opt.ownerIds);
- } else {
- builder.resolve([]);
- }
- return builder.modify(this.modify);
- }
- join(
- builder,
- {
- joinOperation = 'join',
- relatedTableAlias = this.relatedTableAlias(builder),
- relatedJoinSelectQuery = this.relatedModelClass.query().childQueryOf(builder),
- relatedTable = builder.tableNameFor(this.relatedModelClass),
- ownerTable = builder.tableRefFor(this.ownerModelClass),
- joinTableAlias = `${relatedTableAlias}_join`
- } = {}
- ) {
- const joinTableAsAlias = `${this.joinTable} as ${joinTableAlias}`;
- let relatedJoinSelect = relatedJoinSelectQuery.modify(this.modify).as(relatedTableAlias);
- if (relatedJoinSelect.isSelectAll()) {
- // No need to join a subquery if the query is `select * from "RelatedTable"`.
- relatedJoinSelect = `${relatedTable} as ${relatedTableAlias}`;
- }
- return builder[joinOperation](joinTableAsAlias, join => {
- const ownerProp = this.ownerProp;
- const joinTableOwnerProp = this.joinTableOwnerProp;
- for (let i = 0, l = ownerProp.size; i < l; ++i) {
- const joinTableOwnerRef = joinTableOwnerProp.ref(builder, i).table(joinTableAlias);
- const ownerRef = ownerProp.ref(builder, i).table(ownerTable);
- join.on(joinTableOwnerRef, ownerRef);
- }
- })[joinOperation](relatedJoinSelect, join => {
- const relatedProp = this.relatedProp;
- const joinTableRelatedProp = this.joinTableRelatedProp;
- for (let i = 0, l = relatedProp.size; i < l; ++i) {
- const joinTableRelatedRef = joinTableRelatedProp.ref(builder, i).table(joinTableAlias);
- const relatedRef = relatedProp.ref(builder, i).table(relatedTableAlias);
- join.on(joinTableRelatedRef, relatedRef);
- }
- });
- }
- find(builder, owners) {
- return new ManyToManyFindOperation('find', {
- relation: this,
- owners: owners
- });
- }
- insert(builder, owner) {
- return new ManyToManyInsertOperation('insert', {
- relation: this,
- owner: owner
- });
- }
- update(builder, owner) {
- if (isSqlite(builder.knex())) {
- return new ManyToManyUpdateSqliteOperation('update', {
- relation: this,
- owner: owner
- });
- } else if (isMySql(builder.knex())) {
- return new ManyToManyUpdateMySqlOperation('update', {
- relation: this,
- owner: owner
- });
- } else {
- return new ManyToManyUpdateOperation('update', {
- relation: this,
- owner: owner
- });
- }
- }
- patch(builder, owner) {
- if (isSqlite(builder.knex())) {
- return new ManyToManyUpdateSqliteOperation('patch', {
- modelOptions: { patch: true },
- relation: this,
- owner: owner
- });
- } else if (isMySql(builder.knex())) {
- return new ManyToManyUpdateMySqlOperation('patch', {
- modelOptions: { patch: true },
- relation: this,
- owner: owner
- });
- } else {
- return new ManyToManyUpdateOperation('patch', {
- modelOptions: { patch: true },
- relation: this,
- owner: owner
- });
- }
- }
- delete(builder, owner) {
- if (isSqlite(builder.knex())) {
- return new ManyToManyDeleteSqliteOperation('delete', {
- relation: this,
- owner: owner
- });
- } else if (isMySql(builder.knex())) {
- return new ManyToManyDeleteMySqlOperation('delete', {
- relation: this,
- owner: owner
- });
- } else {
- return new ManyToManyDeleteOperation('delete', {
- relation: this,
- owner: owner
- });
- }
- }
- relate(builder, owner) {
- return new ManyToManyRelateOperation('relate', {
- relation: this,
- owner: owner
- });
- }
- unrelate(builder, owner) {
- if (isSqlite(builder.knex())) {
- return new ManyToManyUnrelateSqliteOperation('unrelate', {
- relation: this,
- owner: owner
- });
- } else if (isMySql(builder.knex())) {
- return new ManyToManyUnrelateMySqlOperation('unrelate', {
- relation: this,
- owner: owner
- });
- } else {
- return new ManyToManyUnrelateOperation('unrelate', {
- relation: this,
- owner: owner
- });
- }
- }
- createJoinModels(ownerId, related) {
- const joinModels = new Array(related.length);
- for (let i = 0, lr = related.length; i < lr; ++i) {
- const rel = related[i];
- let joinModel = {};
- for (let j = 0, lp = this.joinTableOwnerProp.size; j < lp; ++j) {
- this.joinTableOwnerProp.setProp(joinModel, j, ownerId[j]);
- }
- for (let j = 0, lp = this.joinTableRelatedProp.size; j < lp; ++j) {
- this.joinTableRelatedProp.setProp(joinModel, j, this.relatedProp.getProp(rel, j));
- }
- for (let j = 0, lp = this.joinTableExtras.length; j < lp; ++j) {
- const extra = this.joinTableExtras[j];
- const extraValue = rel[extra.aliasProp];
- if (extraValue !== undefined) {
- joinModel[extra.joinTableProp] = extraValue;
- }
- }
- joinModels[i] = joinModel;
- }
- return joinModels;
- }
- omitExtraProps(models) {
- if (this.joinTableExtras && this.joinTableExtras.length) {
- const props = this.joinTableExtras.map(extra => extra.aliasProp);
- for (let i = 0, l = models.length; i < l; ++i) {
- const queryProps = models[i].$$queryProps;
- // Omit extra properties instead of deleting them from the models so that they can
- // be used in the `$before` and `$after` hooks.
- models[i].$omitFromDatabaseJson(props);
- if (queryProps) {
- // We can delete the query properties since they shouldn't be used by anything
- // other than `$toDatabaseJson()`.
- for (let j = 0; j < props.length; ++j) {
- const prop = props[j];
- if (prop in queryProps) {
- delete queryProps[prop];
- }
- }
- }
- }
- }
- }
- executeJoinTableBeforeInsert(models, queryContext, result) {
- return mapAfterAllReturn(
- models,
- model => this.joinTableBeforeInsert(model, queryContext),
- result
- );
- }
- }
- function checkThroughObject(ctx) {
- const mapping = ctx.mapping;
- if (!mapping.join.through || typeof mapping.join.through !== 'object') {
- throw ctx.createError('join must have a `through` object that describes the join table.');
- }
- if (!mapping.join.through.from || !mapping.join.through.to) {
- throw ctx.createError(
- 'join.through must be an object that describes the join table. For example: {from: "JoinTable.someId", to: "JoinTable.someOtherId"}'
- );
- }
- return ctx;
- }
- function resolveJoinModelClassIfDefined(ctx) {
- let joinTableModelClass = null;
- if (ctx.mapping.join.through.modelClass) {
- try {
- joinTableModelClass = resolveModel(
- ctx.mapping.join.through.modelClass,
- ctx.ownerModelClass.modelPaths,
- 'join.through.modelClass'
- );
- } catch (err) {
- throw ctx.createError(err.message);
- }
- }
- return Object.assign(ctx, { joinTableModelClass });
- }
- function createJoinProperties(ctx) {
- let ret;
- let fromProp;
- let toProp;
- let relatedProp;
- let ownerProp;
- ret = createRelationProperty(ctx, ctx.mapping.join.through.from, 'join.through.from');
- fromProp = ret.prop;
- ctx = ret.ctx;
- ret = createRelationProperty(ctx, ctx.mapping.join.through.to, 'join.through.to');
- toProp = ret.prop;
- ctx = ret.ctx;
- if (fromProp.modelClass.getTableName() !== toProp.modelClass.getTableName()) {
- throw ctx.createError('join.through `from` and `to` must point to the same join table.');
- }
- if (ctx.relatedProp.modelClass.getTableName() === fromProp.modelClass.getTableName()) {
- relatedProp = fromProp;
- ownerProp = toProp;
- } else {
- relatedProp = toProp;
- ownerProp = fromProp;
- }
- return Object.assign(ctx, {
- joinTableOwnerProp: ownerProp,
- joinTableRelatedProp: relatedProp
- });
- }
- function createRelationProperty(ctx, refString, messagePrefix) {
- let prop = null;
- let joinTableModelClass = ctx.joinTableModelClass;
- const resolveModelClass = table => {
- if (joinTableModelClass === null) {
- joinTableModelClass = inheritModel(getModel());
- joinTableModelClass.tableName = table;
- joinTableModelClass.idColumn = null;
- joinTableModelClass.concurrency = 1;
- }
- if (joinTableModelClass.getTableName() === table) {
- return joinTableModelClass;
- } else {
- return null;
- }
- };
- try {
- prop = new RelationProperty(refString, resolveModelClass);
- } catch (err) {
- if (err instanceof RelationProperty.ModelNotFoundError) {
- throw ctx.createError('join.through `from` and `to` must point to the same join table.');
- } else {
- throw ctx.createError(
- `${messagePrefix} must have format JoinTable.columnName. For example "JoinTable.someId" or in case of composite key ["JoinTable.a", "JoinTable.b"].`
- );
- }
- }
- return {
- ctx: Object.assign(ctx, { joinTableModelClass }),
- prop
- };
- }
- function parseExtras(ctx) {
- let extraDef = ctx.mapping.join.through.extra;
- if (!extraDef) {
- return ctx;
- }
- if (Array.isArray(extraDef)) {
- extraDef = extraDef.reduce((extraDef, col) => {
- extraDef[col] = col;
- return extraDef;
- }, {});
- }
- const joinTableExtras = Object.keys(extraDef).map(key => {
- const val = extraDef[key];
- return {
- joinTableCol: val,
- joinTableProp: ctx.joinTableModelClass.columnNameToPropertyName(val),
- aliasCol: key,
- aliasProp: ctx.joinTableModelClass.columnNameToPropertyName(key)
- };
- });
- return Object.assign(ctx, { joinTableExtras });
- }
- function parseBeforeInsert(ctx) {
- let joinTableBeforeInsert;
- if (typeof ctx.mapping.join.through.beforeInsert === 'function') {
- joinTableBeforeInsert = ctx.mapping.join.through.beforeInsert;
- } else {
- joinTableBeforeInsert = model => model;
- }
- return Object.assign(ctx, { joinTableBeforeInsert });
- }
- function finalizeJoinModelClass(ctx) {
- if (ctx.joinTableModelClass.getIdColumn() === null) {
- // We cannot know if the join table has a primary key. Therefore we set some
- // known column as the idColumn so that inserts will work.
- ctx.joinTableModelClass.idColumn = ctx.joinTableRelatedProp.cols;
- }
- return ctx;
- }
- function containsNonNull(arr) {
- for (let i = 0, l = arr.length; i < l; ++i) {
- const val = arr[i];
- if (Array.isArray(val) && containsNonNull(val)) {
- return true;
- } else if (val !== null && val !== undefined) {
- return true;
- }
- }
- return false;
- }
- module.exports = ManyToManyRelation;
|