ToolJet/server/data-migrations/1639734070615-BackfillDataSourcesAndQueriesForAppVersions.ts
Midhun G S 90e7c4cab9
Cloud licensing related changes (#13033)
* added all pending cloud migration

* restrict cloud migrations

* added cloud data-migrations

* Added cloud entities

* keep tables across all

* cloud licensing initial changes

* fix

* payments module

* license counts updates

* update

* Added all pending cloud migration to pre-release + Payments module (#13006)

* added all pending cloud migration

* restrict cloud migrations

* added cloud data-migrations

* Added cloud entities

* keep tables across all

* payments module

* license counts updates

* update

* migration fixes

* pass orgId

* movement

* added cloud instance settings

* org id to license terms

* before merge

* dockerfile changes for cloud

* migration fixes

* subscription

* merge main

* posthog-js package

* fix

* selhostcustomer migration timestamp update

* fix

* fixes

* fix

* fix

* Adding cloud dockerfile changes

* migration fix

* fix

* fix

* fix

* fixes

* added migration progress

* fix

* added migration files for cloud

* fix

* added migrations for cloud

* add organizationId for pages controller

* fixes for plugins script

* fix

* final

* added cloud licensing envs

* UI WRAPPER BUG

* fix

* orgId groups fix

* lint check fixes

* Refactor Dockerfiles to use dynamic branch names for builds

* Feature/promote release permission management (#13020)

* migration and entity changes

* removed extra migration

* added default group permissions

* basic ui changes

* added promote and release permissions

* fixed tooltips for promote and release buttons

* fix

* fixed app promote ability check

* ce compatibility ui change

* ui fixes

* removed console.log

* removed comments

* updated ee-preview.Dockerile

* using base img node:22.15.1-bullseye

* fix for ce render

* Update ce-preview.Dockerfile

* Update ee-preview.Dockerfile

* ui fix

* fix

* fixes

* fixes

* fixes

* fixes

* minor fixes

* fix

---------

Co-authored-by: Souvik <psouvik260@gmail.com>
Co-authored-by: Adish M <44204658+adishM98@users.noreply.github.com>

* Bugfix/git sync pre release (#13098)

* bugfixes

* ui fixes for disabled states in version creation

* minor fixes

* removed unused imports

* fixes

* removed comments

* module file fixes

* module fixes

* white-labelling fixes

* login-configs

* fix for migration for ce

* Fix for app count guard (#13131)

* fix for app count guard

* added check

* for debug

* license key

* Modules : Platform Functionality  (#12994)

* init

* mod

* app import-export

* licensing and UI

* review and permissions

* update

* updates

* update

* update

* fix breadcrumb

* fix app builder error

* remove launch button for modules

* fixed homepage

* fix permission check

---------

Co-authored-by: platform-ops123 <platformops545@gmail.com>
Co-authored-by: gsmithun4 <gsmithun4@gmail.com>

* reverted logs

* tjdb guard and dark mode (#13137)

* ui fixes

* added modules module

* removed unused imports

* fix

* fix

* Cypress fix

* fixes for cloud instance level licensing (#13146)

---------

Co-authored-by: platform-ops123 <platformops545@gmail.com>
Co-authored-by: Rudra deep Biswas <rudra21ultra@gmail.com>
Co-authored-by: Adish M <adish.madhu@gmail.com>
Co-authored-by: Rudhra Deep Biswas <98055396+rudeUltra@users.noreply.github.com>
Co-authored-by: Vijaykant Yadav <vjy239@gmail.com>
Co-authored-by: Rohan Lahori <64496391+rohanlahori@users.noreply.github.com>
Co-authored-by: Souvik <psouvik260@gmail.com>
Co-authored-by: Adish M <44204658+adishM98@users.noreply.github.com>
Co-authored-by: rohanlahori <rohanlahori99@gmail.com>
Co-authored-by: ajith-k-v <ajith.jaban@gmail.com>
2025-07-02 10:57:36 +05:30

242 lines
8.9 KiB
TypeScript

import { NestFactory } from '@nestjs/core';
import { App } from '@entities/app.entity';
import { AppVersion } from '@entities/app_version.entity';
import { DataSource } from '@entities/data_source.entity';
import { Organization } from '@entities/organization.entity';
import { EntityManager, MigrationInterface, QueryRunner } from 'typeorm';
import { Credential } from '@entities/credential.entity';
import { cloneDeep } from 'lodash';
import { AppModule } from '@modules/app/module';
import { TOOLJET_EDITIONS, getImportPath } from '@modules/app/constants';
import { IDataSourcesUtilService } from '@modules/data-sources/interfaces/IUtilService';
import { getTooljetEdition } from '@helpers/utils.helper';
export class BackfillDataSourcesAndQueriesForAppVersions1639734070615 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const entityManager = queryRunner.manager;
const organizations = await entityManager.find(Organization, {
select: ['id', 'name'],
});
if (organizations.length === 0) {
console.log('No organizations found, skipping backfill.');
return;
}
const nestApp = await NestFactory.createApplicationContext(await AppModule.register({ IS_GET_CONTEXT: true }));
const edition: TOOLJET_EDITIONS = getTooljetEdition() as TOOLJET_EDITIONS;
const { DataSourcesUtilService } = await import(`${await getImportPath(true, edition)}/data-sources/util.service`);
const dataSourcesService = nestApp.get(DataSourcesUtilService);
for (const org of organizations) {
console.log(`Backfilling for organization ${org.name} : ${org.id}`);
const apps = await entityManager.find(App, {
where: { organizationId: org.id },
});
for (const app of apps) {
await this.associateDataSourcesAndQueriesToAppVersions(app, entityManager, dataSourcesService);
}
}
console.log(`Backfill done for ${organizations.length} organization/s`);
await nestApp.close();
}
async associateDataSourcesAndQueriesToAppVersions(
app: App,
entityManager: EntityManager,
dataSourcesService: IDataSourcesUtilService
) {
const appVersions = await entityManager.find(AppVersion, {
where: { appId: app.id },
order: { createdAt: 'ASC' },
});
const dataSources = await entityManager.query(
'select * from data_sources where app_id = $1 and app_version_id IS NULL',
[app.id]
);
const dataQueries = await entityManager.query(
'select * from data_queries where app_id = $1 and app_version_id IS NULL',
[app.id]
);
const [firstAppVersion, ...restAppVersions] = appVersions;
await this.associateExistingDataSourceAndQueriesToVersion(firstAppVersion, dataSources, dataQueries, entityManager);
await this.createNewDataSourcesAndQueriesForVersions(
restAppVersions,
dataSources,
dataQueries,
entityManager,
dataSourcesService
);
}
async associateExistingDataSourceAndQueriesToVersion(
firstAppVersion: AppVersion,
dataSources: any[],
dataQueries: any[],
entityManager: EntityManager
) {
if (!firstAppVersion) return;
for (const dataSource of dataSources) {
await entityManager.update(DataSource, dataSource.id, {
appVersionId: firstAppVersion.id,
});
}
if (dataQueries?.length) {
await entityManager.query(
`update data_queries set app_version_id = $1 where id IN(${dataQueries.map((dq) => `'${dq.id}'`)?.join()})`,
[firstAppVersion.id]
);
}
}
async createNewDataSourcesAndQueriesForVersions(
restAppVersions: AppVersion[],
dataSources,
dataQueries,
entityManager: EntityManager,
dataSourcesService: IDataSourcesUtilService
) {
if (restAppVersions.length == 0) return;
for (const appVersion of restAppVersions) {
const oldDataSourceToNewMapping = {};
for (const dataSource of dataSources) {
const convertedOptions = this.convertToArrayOfKeyValuePairs(dataSource.options);
const newOptions = await dataSourcesService.parseOptionsForCreate(convertedOptions, false, entityManager);
await this.setNewCredentialValueFromOldValue(newOptions, convertedOptions, entityManager);
const newDataSource = await entityManager.query(
'insert into data_sources (name, kind, options, app_id, app_version_id) values ($1, $2, $3, $4, $5) returning "id"',
[dataSource.name, dataSource.kind, newOptions, dataSource.app_id, appVersion.id]
);
oldDataSourceToNewMapping[dataSource.id] = newDataSource[0].id;
}
const newDataQueries = [];
const dataQueryMapping = {};
for (const dataQuery of dataQueries) {
const newDataQueryResult = await entityManager.query(
'insert into data_queries (name, kind, options, data_source_id, app_id, app_version_id) values ($1, $2, $3, $4, $5, $6) returning *',
[
dataQuery.name,
dataQuery.kind,
cloneDeep(dataQuery.options),
oldDataSourceToNewMapping[dataQuery.data_source_id],
dataQuery.app_id,
appVersion.id,
]
);
const newDataQuery = newDataQueryResult[0];
newDataQueries.push(newDataQuery);
dataQueryMapping[dataQuery.id] = newDataQuery.id;
}
for (const newQuery of newDataQueries) {
const newOptions = this.replaceDataQueryOptionsWithNewDataQueryIds(newQuery.options, dataQueryMapping);
newQuery.options = newOptions;
await entityManager.query('update data_queries set options = $1 where id = $2', [newOptions, newQuery.id]);
}
appVersion.definition = this.replaceDataQueryIdWithinDefinitions(appVersion.definition, dataQueryMapping);
await entityManager.save(appVersion);
}
}
convertToArrayOfKeyValuePairs(options): Array<object> {
return Object.keys(options).map((key) => {
return {
key: key,
value: options[key]['value'],
encrypted: options[key]['encrypted'],
credential_id: options[key]['credential_id'],
};
});
}
replaceDataQueryOptionsWithNewDataQueryIds(options, dataQueryMapping) {
if (options && options.events) {
const replacedEvents = options.events.map((event) => {
if (event.queryId) {
event.queryId = dataQueryMapping[event.queryId];
}
return event;
});
options.events = replacedEvents;
}
return options;
}
replaceDataQueryIdWithinDefinitions(definition, dataQueryMapping) {
if (definition?.components) {
for (const id of Object.keys(definition.components)) {
const component = definition.components[id].component;
if (component?.definition?.events) {
const replacedComponentEvents = component.definition.events.map((event) => {
if (event.queryId) {
event.queryId = dataQueryMapping[event.queryId];
}
return event;
});
component.definition.events = replacedComponentEvents;
}
if (component?.definition?.properties?.actions?.value) {
for (const value of component.definition.properties.actions.value) {
if (value?.events) {
const replacedComponentActionEvents = value.events.map((event) => {
if (event.queryId) {
event.queryId = dataQueryMapping[event.queryId];
}
return event;
});
value.events = replacedComponentActionEvents;
}
}
}
if (component?.component === 'Table') {
for (const column of component?.definition?.properties?.columns?.value ?? []) {
if (column?.events) {
const replacedComponentActionEvents = column.events.map((event) => {
if (event.queryId) {
event.queryId = dataQueryMapping[event.queryId];
}
return event;
});
column.events = replacedComponentActionEvents;
}
}
}
definition.components[id].component = component;
}
}
return definition;
}
async setNewCredentialValueFromOldValue(newOptions: any, oldOptions: any, entityManager: EntityManager) {
const newOptionsWithCredentials = this.convertToArrayOfKeyValuePairs(newOptions).filter((opt) => opt['encrypted']);
for (const newOption of newOptionsWithCredentials) {
const oldOption = oldOptions.find((oldOption) => oldOption['key'] == newOption['key']);
const oldCredential = await entityManager.findOne(Credential, { where: { id: oldOption.credential_id } });
const newCredential = await entityManager.findOne(Credential, { where: { id: newOption['credential_id'] } });
newCredential.valueCiphertext = oldCredential?.valueCiphertext;
await entityManager.save(newCredential);
}
}
public async down(queryRunner: QueryRunner): Promise<void> {}
}