π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
feat: use trx for updateLTARCols & nested trx support for meta service
mertmitda23a74ffb38
diff --git a/packages/nocodb/src/db/BaseModelSqlv2.ts b/packages/nocodb/src/db/BaseModelSqlv2.tsindex 0e5a8c881f..1b133cb8d4 100644--- a/packages/nocodb/src/db/BaseModelSqlv2.ts+++ b/packages/nocodb/src/db/BaseModelSqlv2.ts@@ -3093,16 +3093,12 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {await transaction.rollback();}- // todo: wrap with transactionif (apiVersion === NcApiVersion.V3) {- for (const d of datas) {- // remove LTAR/Links if part of the update request- await this.updateLTARCols({- rowId: this.extractPksValues(d, true),- cookie,- newData: d,- });- }+ // remove LTAR/Links if part of the update request+ await this.updateLTARCols({+ datas,+ cookie,+ });await Promise.all(postUpdateOps.map((ops) => ops()));}@@ -3151,91 +3147,101 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {}}- async updateLTARCols({- rowId,- newData,- cookie,- }: {- newData: any;- rowId: string;- cookie;- }) {- for (const col of this.model.columns) {- // skip if not LTAR or Links- if (!isLinksOrLTAR(col)) continue;+ async updateLTARCols({ datas, cookie }: { datas: any[]; cookie: NcRequest }) {+ const trx = await this.dbDriver.transaction();- // skip if value is not part of the update- if (!(col.title in newData)) continue;+ const trxBaseModel = await Model.getBaseModelSQL(this.context, {+ model: this.model,+ dbDriver: trx,+ });- // extract existing link values to current record- let existingLinks = [];+ try {+ for (const d of datas) {+ const rowId = this.extractPksValues(d, true);- if (col.colOptions.type === RelationTypes.MANY_TO_MANY) {- existingLinks = await this.mmList({- colId: col.id,- parentId: rowId,- });- } else if (col.colOptions.type === RelationTypes.HAS_MANY) {- existingLinks = await this.hmList({- colId: col.id,- id: rowId,- });- } else {- existingLinks = await this.btRead({- colId: col.id,- id: rowId,- });- }+ for (const col of this.model.columns) {+ // skip if not LTAR or Links+ if (!isLinksOrLTAR(col)) continue;- existingLinks = existingLinks || [];+ // skip if value is not part of the update+ if (!(col.title in d)) continue;- if (!Array.isArray(existingLinks)) {- existingLinks = [existingLinks];- }+ // extract existing link values to current record+ let existingLinks = [];- const idsToLink = [- ...(Array.isArray(newData[col.title])- ? newData[col.title]- : [newData[col.title]]- ).map((rec) => this.extractPksValues(rec, true)),- ];+ if (col.colOptions.type === RelationTypes.MANY_TO_MANY) {+ existingLinks = await trxBaseModel.mmList({+ colId: col.id,+ parentId: rowId,+ });+ } else if (col.colOptions.type === RelationTypes.HAS_MANY) {+ existingLinks = await trxBaseModel.hmList({+ colId: col.id,+ id: rowId,+ });+ } else {+ existingLinks = await trxBaseModel.btRead({+ colId: col.id,+ id: rowId,+ });+ }- // check for any missing links then unlink- const idsToUnlink = existingLinks- .map((link) => this.extractPksValues(link, true))- .filter((existingLinkPk) => {- const index = idsToLink.findIndex((linkPk) => {- return existingLinkPk === linkPk;- });+ existingLinks = existingLinks || [];- // if found remove from both list- if (index > -1) {- idsToLink.splice(index, 1);- return false;+ if (!Array.isArray(existingLinks)) {+ existingLinks = [existingLinks];}- return true;- });+ const idsToLink = [+ ...(Array.isArray(d[col.title])+ ? d[col.title]+ : [d[col.title]]+ ).map((rec) => this.extractPksValues(rec, true)),+ ];++ // check for any missing links then unlink+ const idsToUnlink = existingLinks+ .map((link) => this.extractPksValues(link, true))+ .filter((existingLinkPk) => {+ const index = idsToLink.findIndex((linkPk) => {+ return existingLinkPk === linkPk;+ });- // check for missing links in new data and unlink them- if (idsToUnlink?.length) {- await this.removeLinks({- colId: col.id,- childIds: idsToUnlink,- cookie,- rowId,- });- }+ // if found remove from both list+ if (index > -1) {+ idsToLink.splice(index, 1);+ return false;+ }- // check for new data and link them- if (idsToLink?.length) {- await this.addLinks({- colId: col.id,- childIds: idsToLink,- cookie,- rowId,- });+ return true;+ });++ // check for missing links in new data and unlink them+ if (idsToUnlink?.length) {+ await trxBaseModel.removeLinks({+ colId: col.id,+ childIds: idsToUnlink,+ cookie,+ rowId,+ });+ }++ // check for new data and link them+ if (idsToLink?.length) {+ await trxBaseModel.addLinks({+ colId: col.id,+ childIds: idsToLink,+ cookie,+ rowId,+ });+ }+ }}++ await trx.commit();+ } catch (e) {+ await trx.rollback();+ throw e;}}diff --git a/packages/nocodb/src/db/CustomKnex.ts b/packages/nocodb/src/db/CustomKnex.tsindex aa51a8015e..c43bb658e6 100644--- a/packages/nocodb/src/db/CustomKnex.ts+++ b/packages/nocodb/src/db/CustomKnex.ts@@ -1059,17 +1059,9 @@ function CustomKnex(const knexRaw = kn.raw;- /**- * Wrapper for knex.raw- *- * @param args1- * @returns {Knex.Raw<any>}- */- // knex.raw = function (...args) {- // return knexRaw.apply(knex, args);- // };+ const knexTransaction = kn.transaction;- Object.defineProperties(kn, {+ const overrideProps = {raw: {enumerable: true,value: (...args) => {@@ -1100,7 +1092,29 @@ function CustomKnex(enumerable: false,value: !!extDb && process.env.NC_DISABLE_MUX !== 'true',},- });+ transaction: {+ enumerable: true,+ value: async (...args) => {+ const trx = await knexTransaction.apply(kn, args);++ Object.defineProperties(trx, overrideProps);++ return trx;+ },+ },+ };++ /**+ * Wrapper for knex.raw+ *+ * @param args1+ * @returns {Knex.Raw<any>}+ */+ // knex.raw = function (...args) {+ // return knexRaw.apply(knex, args);+ // };++ Object.defineProperties(kn, overrideProps);/*** Returns database typediff --git a/packages/nocodb/src/meta/meta.service.ts b/packages/nocodb/src/meta/meta.service.tsindex 83cdea56ed..538d8ff02e 100644--- a/packages/nocodb/src/meta/meta.service.ts+++ b/packages/nocodb/src/meta/meta.service.ts@@ -27,13 +27,18 @@ export class MetaService {protected _knex: knex.Knex;protected _config: any;- constructor(config: NcConfig, @Optional() trx = null) {+ constructor(+ config: NcConfig,+ @Optional() trx = null,+ @Optional() nested = 0,+ ) {this._config = config;this._knex = XKnex({...this._config.meta.db,useNullAsDefault: true,});this.trx = trx;+ this.nested = nested;}get knexInstance(): knex.Knex {@@ -355,6 +360,7 @@ export class MetaService {// private connection: XKnex;// todo: need to fixprotected trx: Knex.Transaction;+ protected nested: number;/**** Delete meta data@@ -719,10 +725,10 @@ export class MetaService {}async commit() {- if (this.trx) {+ if (this.trx && this.nested === 0) {await this.trx.commit();+ this.trx = null;}- this.trx = null;}async rollback(e?) {@@ -733,16 +739,17 @@ export class MetaService {}async startTransaction(): Promise<MetaService> {- const trx = await this.connection.transaction();-- // todo: Extend transaction class to add our custom properties- Object.assign(trx, {- clientType: this.connection.clientType,- searchPath: (this.connection as any).searchPath,- });+ const trx = this.connection.isTransaction+ ? this.connection+ : await this.connection.transaction();// todo: tobe done- return new MetaService(this.config, trx);+ return new MetaService(+ this.config,+ trx,+ // we need to keep track of the nested transaction level+ this.connection.isTransaction ? this.nested + 1 : 0,+ );}/***