Files
twenty/packages/twenty-server/src/engine/metadata-modules/remote-server/remote-table/utils/get-remote-table-local-name.util.ts
T
Weiko dec2239ae7 Remove typeorm service (#14116)
## Context
To simplify the way we inject our default datasource, I've recently
removed the token injection that was confusion since we only had once
configured on the module level. Now I'm removing TypeORM service which
allows us to instantiate a new Datasource with the same parameters as
the default one, it was redundant and confusing.
2025-08-28 13:21:26 +02:00

65 lines
1.6 KiB
TypeScript

import { singular } from 'pluralize';
import { type DataSource } from 'typeorm';
import {
RemoteTableException,
RemoteTableExceptionCode,
} from 'src/engine/metadata-modules/remote-server/remote-table/remote-table.exception';
import { camelCase } from 'src/utils/camel-case';
const MAX_SUFFIX = 10;
type RemoteTableLocalName = {
baseName: string;
suffix?: number;
};
const isNameAvailable = async (
tableName: string,
workspaceSchemaName: string,
coreDataSource: DataSource,
) => {
const numberOfTablesWithSameName = +(
await coreDataSource.query(
`SELECT count(table_name) FROM information_schema.tables WHERE table_name LIKE '${tableName}' AND table_schema IN ('core', '${workspaceSchemaName}')`,
)
)[0].count;
return numberOfTablesWithSameName === 0;
};
export const getRemoteTableLocalName = async (
distantTableName: string,
workspaceSchemaName: string,
coreDataSource: DataSource,
): Promise<RemoteTableLocalName> => {
const baseName = singular(camelCase(distantTableName));
const isBaseNameValid = await isNameAvailable(
baseName,
workspaceSchemaName,
coreDataSource,
);
if (isBaseNameValid) {
return { baseName };
}
for (let suffix = 2; suffix < MAX_SUFFIX; suffix++) {
const name = `${baseName}${suffix}`;
const isNameWithSuffixValid = await isNameAvailable(
name,
workspaceSchemaName,
coreDataSource,
);
if (isNameWithSuffixValid) {
return { baseName, suffix };
}
}
throw new RemoteTableException(
'Table name is already taken',
RemoteTableExceptionCode.INVALID_REMOTE_TABLE_INPUT,
);
};