Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

feat: unify model be changes

DarkPhoenix27042a034c3253fc
diff --git a/packages/nocodb-sdk/src/lib/globals.ts b/packages/nocodb-sdk/src/lib/globals.ts
index 5d26d6abd8..c4bd8d77bb 100644
--- a/packages/nocodb-sdk/src/lib/globals.ts
+++ b/packages/nocodb-sdk/src/lib/globals.ts
@@ -101,6 +101,7 @@ export enum PluginCategory {
export enum ModelTypes {
TABLE = 'table',
VIEW = 'view',
+ DASHBOARD = 'dashboard',
}
export enum ProjectStatus {
diff --git a/packages/nocodb/src/meta/meta.service.ts b/packages/nocodb/src/meta/meta.service.ts
index 538d8ff02e..1a0abc514d 100644
--- a/packages/nocodb/src/meta/meta.service.ts
+++ b/packages/nocodb/src/meta/meta.service.ts
@@ -503,7 +503,17 @@ export class MetaService {
): Promise<number> {
const query = this.knexConnection(target);
- query.where(condition);
+ if (!condition) {
+ condition = {};
+ }
+ Object.entries(condition).forEach(([key, value]) => {
+ if (Array.isArray(value)) {
+ query.whereIn(key, value);
+ } else {
+ query.where(key, value);
+ }
+ });
+
query.max('order', { as: 'order' });
return (+(await query.first())?.order || 0) + 1;
diff --git a/packages/nocodb/src/meta/migrations/XcMigrationSourcev2.ts b/packages/nocodb/src/meta/migrations/XcMigrationSourcev2.ts
index 37ab02e245..45a50e6680 100644
--- a/packages/nocodb/src/meta/migrations/XcMigrationSourcev2.ts
+++ b/packages/nocodb/src/meta/migrations/XcMigrationSourcev2.ts
@@ -77,6 +77,7 @@ import * as nc_087_widget_error from '~/meta/migrations/v2/nc_087_widget_error';
import * as nc_088_add_sso_client_to_api_tokens from '~/meta/migrations/v2/nc_088_add_sso_client_to_api_tokens';
import * as nc_089_dashboard_sharing from '~/meta/migrations/v2/nc_089_dashboard_sharing';
import * as nc_090_add_is_new_user_to_users from '~/meta/migrations/v2/nc_090_add_is_new_user_to_users';
+import * as nc_091_unify_model from '~/meta/migrations/v2/nc_091_unify_model';
// Create a custom migration source class
export default class XcMigrationSourcev2 {
@@ -165,6 +166,7 @@ export default class XcMigrationSourcev2 {
'nc_088_add_sso_client_to_api_tokens',
'nc_089_dashboard_sharing',
'nc_090_add_is_new_user_to_users',
+ 'nc_091_unify_model',
]);
}
@@ -332,6 +334,8 @@ export default class XcMigrationSourcev2 {
return nc_089_dashboard_sharing;
case 'nc_090_add_is_new_user_to_users':
return nc_090_add_is_new_user_to_users;
+ case 'nc_091_unify_model':
+ return nc_091_unify_model;
}
}
}
diff --git a/packages/nocodb/src/meta/migrations/v2/nc_091_unify_model.ts b/packages/nocodb/src/meta/migrations/v2/nc_091_unify_model.ts
new file mode 100644
index 0000000000..4329de5de4
--- /dev/null
+++ b/packages/nocodb/src/meta/migrations/v2/nc_091_unify_model.ts
@@ -0,0 +1,148 @@
+import { ModelTypes } from 'nocodb-sdk';
+import { Logger } from '@nestjs/common';
+import type { Knex } from 'knex';
+import { MetaTable } from '~/utils/globals';
+import { migrateTableInBatches } from '~/utils/migrationUtils';
+
+const logger = new Logger('nc_091_unify_models');
+
+const up = async (knex: Knex) => {
+ logger.log('Migration Started');
+
+ await knex.schema.alterTable(MetaTable.MODELS, (table) => {
+ // nc_dashboards_v2
+ table.string('created_by', 20);
+ table.string('owned_by', 20);
+ table.string('uuid', 255);
+ table.string('password', 255);
+ table.string('fk_custom_url_id', 20);
+
+ // Indexes
+
+ table.index('uuid');
+ table.index('type');
+ });
+
+ logger.log('Added columns and indexes');
+
+ logger.log('Starting migration of data from nc_dashboards_v2 to nc_models');
+
+ await migrateTableInBatches(
+ knex,
+ MetaTable.DASHBOARDS,
+ MetaTable.MODELS,
+ (dashboard) => {
+ return {
+ id: dashboard.id,
+ base_id: dashboard.base_id,
+ title: dashboard.title,
+ type: ModelTypes.DASHBOARD, // Set type to distinguish from other records
+ meta: dashboard.meta,
+ deleted: false,
+ order: dashboard.order,
+ created_at: dashboard.created_at,
+ updated_at: dashboard.updated_at,
+ description: dashboard.description,
+ fk_workspace_id: dashboard.fk_workspace_id,
+ created_by: dashboard.created_by,
+ owned_by: dashboard.owned_by,
+ uuid: dashboard.uuid,
+ password: dashboard.password,
+ fk_custom_url_id: dashboard.fk_custom_url_id,
+ };
+ },
+ logger,
+ );
+
+ logger.log('Data migration completed for nc_dashboards_v2 to nc_models');
+
+ logger.log('Dropping tables');
+
+ // await knex.schema.dropTableIfExists(MetaTable.DASHBOARDS);
+
+ logger.log('Dropping tables completed');
+
+ logger.log('Migration Completed');
+};
+
+const down = async (knex: Knex) => {
+ logger.log('Rollback Migration Started');
+
+ await knex.schema.createTable(MetaTable.DASHBOARDS, function (table) {
+ table.string('id', 20).primary();
+ table.string('fk_workspace_id', 20);
+ table.string('base_id', 20);
+ table.string('title', 255).notNullable();
+ table.text('description');
+ table.text('meta');
+ table.integer('order');
+ table.string('created_by', 20);
+ table.string('owned_by', 20);
+ table.string('uuid', 255);
+ table.string('password', 255);
+ table.string('fk_custom_url_id', 20);
+
+ table.timestamps(true, true);
+ table.index(['base_id', 'fk_workspace_id'], 'nc_dashboards_v2_context');
+ });
+
+ logger.log('Created nc_dashboards_v2 table');
+
+ logger.log('Starting migration of data from nc_models to nc_dashboards_v2');
+
+ await migrateTableInBatches(
+ knex,
+ MetaTable.MODELS,
+ MetaTable.DASHBOARDS,
+ (model) => {
+ return {
+ id: model.id,
+ fk_workspace_id: model.fk_workspace_id,
+ base_id: model.base_id,
+ title: model.title,
+ description: model.description,
+ meta: model.meta,
+ order: model.order,
+ created_by: model.created_by,
+ owned_by: model.owned_by,
+ uuid: model.uuid,
+ password: model.password,
+ fk_custom_url_id: model.fk_custom_url_id,
+
+ created_at: model.created_at,
+ updated_at: model.updated_at,
+ };
+ },
+ logger,
+ {
+ whereConditions: (queryBuilder) => {
+ return queryBuilder.where('type', ModelTypes.DASHBOARD);
+ },
+ },
+ );
+
+ logger.log('Data migration completed from nc_models to nc_dashboards_v2');
+
+ logger.log('Cleaning up nc_models table');
+
+ await knex(MetaTable.MODELS).whereIn('type', [ModelTypes.DASHBOARD]).del();
+
+ logger.log('Cleaning up nc_models table completed');
+
+ await knex.schema.alterTable(MetaTable.MODELS, (table) => {
+ // Indexes
+ table.dropIndex('uuid');
+ table.dropIndex('type');
+
+ // nc_dashboards_v2
+ table.dropColumn('created_by');
+ table.dropColumn('owned_by');
+ table.dropColumn('uuid');
+ table.dropColumn('password');
+ table.dropColumn('fk_custom_url_id');
+ });
+
+ logger.log('Rollback Migration Completed');
+};
+
+export { up, down };
diff --git a/packages/nocodb/src/models/Model.ts b/packages/nocodb/src/models/Model.ts
index 798ca58397..f177a76f57 100644
--- a/packages/nocodb/src/models/Model.ts
+++ b/packages/nocodb/src/models/Model.ts
@@ -40,6 +40,7 @@ import {
import { Source } from '~/models';
import { cleanBaseSchemaCacheForBase } from '~/helpers/scriptHelper';
import { dataWrapper } from '~/helpers/dbHelpers';
+import { isEE } from '~/utils';
const logger = new Logger('Model');
@@ -199,13 +200,23 @@ export default class Model implements TableType {
insertObj.mm = !!insertObj.mm;
+ const condition: Record<string, any> = {
+ base_id: baseId,
+ };
+ const source = await Source.get(context, sourceId, false, ncMeta);
+
+ if (!source?.isMeta()) {
+ condition.sourceId = sourceId;
+ }
+
+ if (isEE) {
+ condition.fk_workspace_id = context.workspace_id;
+ }
+
if (!insertObj.order) {
insertObj.order = await ncMeta.metaGetNextOrder(
- MetaTable.FORM_VIEW_COLUMNS,
- {
- base_id: baseId,
- source_id: sourceId,
- },
+ MetaTable.MODELS,
+ condition,
);
}
@@ -311,6 +322,20 @@ export default class Model implements TableType {
order: 'asc',
},
...(source_id ? { condition: { source_id } } : {}),
+ xcCondition: {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
},
);
@@ -361,6 +386,22 @@ export default class Model implements TableType {
context.workspace_id,
context.base_id,
MetaTable.MODELS,
+ {
+ xcCondition: {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
+ },
);
// parse meta of each model
@@ -391,6 +432,21 @@ export default class Model implements TableType {
context.base_id,
MetaTable.MODELS,
id,
+ undefined,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
if (modelData) {
@@ -427,6 +483,21 @@ export default class Model implements TableType {
context.base_id,
MetaTable.MODELS,
k,
+ undefined,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
if (modelData) {
modelData.meta = parseMetaProp(modelData);
@@ -465,6 +536,21 @@ export default class Model implements TableType {
id || {
table_name,
},
+ undefined,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
if (modelData) {
modelData.meta = parseMetaProp(modelData);
@@ -654,6 +740,20 @@ export default class Model implements TableType {
context.base_id,
MetaTable.MODELS,
this.id,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
// delete alias cache
@@ -801,6 +901,20 @@ export default class Model implements TableType {
table_name,
},
tableId,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
// get default view and update alias
@@ -872,6 +986,20 @@ export default class Model implements TableType {
mm: isMm,
},
tableId,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
await NocoCache.update(`${CacheScope.MODEL}:${tableId}`, {
@@ -914,6 +1042,20 @@ export default class Model implements TableType {
order,
},
tableId,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
await NocoCache.update(`${CacheScope.MODEL}:${tableId}`, {
@@ -1051,16 +1193,34 @@ export default class Model implements TableType {
{ base_id, source_id },
null,
{
- _or: [
+ _and: [
{
- id: {
- eq: aliasOrId,
- },
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
},
{
- title: {
- eq: aliasOrId,
- },
+ _or: [
+ {
+ id: {
+ eq: aliasOrId,
+ },
+ },
+ {
+ title: {
+ eq: aliasOrId,
+ },
+ },
+ ],
},
],
},
@@ -1072,16 +1232,34 @@ export default class Model implements TableType {
{ base_id },
null,
{
- _or: [
+ _and: [
{
- id: {
- eq: aliasOrId,
- },
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
},
{
- title: {
- eq: aliasOrId,
- },
+ _or: [
+ {
+ id: {
+ eq: aliasOrId,
+ },
+ },
+ {
+ title: {
+ eq: aliasOrId,
+ },
+ },
+ ],
},
],
},
@@ -1113,7 +1291,31 @@ export default class Model implements TableType {
...(source_id ? { source_id } : {}),
},
null,
- exclude_id && { id: { neq: exclude_id } },
+ {
+ _and: [
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ ...(exclude_id
+ ? {
+ id: {
+ neq: exclude_id,
+ },
+ }
+ : {}),
+ },
+ ],
+ },
));
}
@@ -1135,7 +1337,31 @@ export default class Model implements TableType {
...(source_id ? { source_id } : {}),
},
null,
- exclude_id && { id: { neq: exclude_id } },
+ {
+ _and: [
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ ...(exclude_id
+ ? {
+ id: {
+ neq: exclude_id,
+ },
+ }
+ : {}),
+ },
+ ],
+ },
));
}
@@ -1170,6 +1396,20 @@ export default class Model implements TableType {
MetaTable.MODELS,
prepareForDb(updateObj),
tableId,
+ {
+ _or: [
+ {
+ type: {
+ eq: ModelTypes.TABLE,
+ },
+ },
+ {
+ type: {
+ eq: ModelTypes.VIEW,
+ },
+ },
+ ],
+ },
);
await NocoCache.update(
diff --git a/packages/nocodb/src/services/tables.service.ts b/packages/nocodb/src/services/tables.service.ts
index afbd8dd43c..08f0b1e270 100644
--- a/packages/nocodb/src/services/tables.service.ts
+++ b/packages/nocodb/src/services/tables.service.ts
@@ -979,7 +979,6 @@ export class TablesService {
order: tableCreatePayLoad.columns.length + i + 1,
})),
],
- order: +(tables?.pop()?.order ?? 0) + 1,
} as any);
try {
diff --git a/packages/nocodb/src/utils/getInstance.ts b/packages/nocodb/src/utils/getInstance.ts
index 589ccbbe52..2bd8dc7ecb 100644
--- a/packages/nocodb/src/utils/getInstance.ts
+++ b/packages/nocodb/src/utils/getInstance.ts
@@ -1,3 +1,4 @@
+import { ModelTypes } from 'nocodb-sdk';
import { CacheGetType, CacheScope, MetaTable } from './globals';
import Noco from '~/Noco';
import NocoCache from '~/cache/NocoCache';
@@ -41,6 +42,7 @@ export default async function (force = false, ncMeta = Noco.ncMeta) {
.then((c) => c.count);
const tables = await ncMeta
.knex(MetaTable.MODELS)
+ .whereIn('type', [ModelTypes.TABLE, ModelTypes.VIEW])
.count('id as count')
.first()
.then((c) => c.count);
diff --git a/packages/nocodb/src/utils/migrationUtils.ts b/packages/nocodb/src/utils/migrationUtils.ts
new file mode 100644
index 0000000000..ad188da9b8
--- /dev/null
+++ b/packages/nocodb/src/utils/migrationUtils.ts
@@ -0,0 +1,92 @@
+import type { MetaTable } from '~/utils/globals';
+import type { Logger } from '@nestjs/common';
+import type { Knex } from 'knex';
+
+interface MigrationOptions {
+ READ_BATCH_SIZE?: number;
+ INSERT_BATCH_SIZE?: number;
+ whereConditions?: (queryBuilder: Knex.QueryBuilder) => Knex.QueryBuilder;
+ orderBy?: string | string[] | { column: string; order?: 'asc' | 'desc' }[];
+ selectColumns?: string | string[];
+}
+
+/**
+ * Utility function to migrate table data in batches
+ */
+export async function migrateTableInBatches(
+ knex: Knex,
+ sourceTable: keyof typeof MetaTable | string,
+ targetTable: keyof typeof MetaTable | string,
+ transformFn: (row: any) => any,
+ logger: Logger,
+ options: MigrationOptions = {},
+) {
+ const {
+ READ_BATCH_SIZE = 1000,
+ INSERT_BATCH_SIZE = 200,
+ whereConditions,
+ orderBy = 'id',
+ selectColumns = '*',
+ } = options;
+
+ let fetchNextBatch = true;
+ const insertedIds = new Set<string>();
+
+ for (let offset = 0; fetchNextBatch; offset += READ_BATCH_SIZE) {
+ // Build the base query
+ let query = knex.select(selectColumns).from(sourceTable as string);
+
+ // Apply where conditions if provided
+ if (whereConditions) {
+ query = whereConditions(query);
+ }
+
+ // Apply ordering and pagination
+ if (Array.isArray(orderBy)) {
+ orderBy.forEach((order) => {
+ if (typeof order === 'string') {
+ query = query.orderBy(order);
+ } else {
+ query = query.orderBy(order.column, order.order || 'asc');
+ }
+ });
+ } else {
+ query = query.orderBy(orderBy as string);
+ }
+
+ const rows = await query.offset(offset).limit(READ_BATCH_SIZE + 1); // +1 to check if there are more rows
+
+ logger.log(
+ `Data from ${sourceTable} fetched, batch: ${offset} - ${
+ offset + READ_BATCH_SIZE
+ }`,
+ );
+
+ const formattedRows = rows
+ .slice(0, READ_BATCH_SIZE) // exclude the last row used for pagination check
+ .filter((row) => {
+ if (insertedIds.has(row.id)) {
+ return false;
+ }
+ insertedIds.add(row.id);
+ return true;
+ })
+ .map(transformFn);
+
+ if (formattedRows.length > 0) {
+ await knex.batchInsert(
+ targetTable as string,
+ formattedRows,
+ INSERT_BATCH_SIZE,
+ );
+ logger.log(
+ `Inserted ${formattedRows.length} rows from ${sourceTable} to ${targetTable}`,
+ );
+ }
+
+ // check if there are more rows to fetch
+ fetchNextBatch = rows.length > READ_BATCH_SIZE;
+ }
+
+ logger.log(`Data migration from ${sourceTable} to ${targetTable} completed`);
+}