mirror of
https://github.com/Abdulazizzn/n8n-enterprise-unlocked.git
synced 2025-12-22 12:19:09 +00:00
refactor(core): Enforce filename casing in cli package (no-changelog) (#10594)
This commit is contained in:
75
packages/cli/src/db.ts
Normal file
75
packages/cli/src/db.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Container } from 'typedi';
|
||||
// eslint-disable-next-line n8n-local-rules/misplaced-n8n-typeorm-import
|
||||
import type { EntityManager } from '@n8n/typeorm';
|
||||
// eslint-disable-next-line n8n-local-rules/misplaced-n8n-typeorm-import
|
||||
import { DataSource as Connection } from '@n8n/typeorm';
|
||||
import { ErrorReporterProxy as ErrorReporter } from 'n8n-workflow';
|
||||
|
||||
import { inTest } from '@/constants';
|
||||
import { wrapMigration } from '@/databases/utils/migration-helpers';
|
||||
import type { Migration } from '@/databases/types';
|
||||
import { getConnectionOptions } from '@/databases/config';
|
||||
|
||||
let connection: Connection;
|
||||
|
||||
export const getConnection = () => connection!;
|
||||
|
||||
type ConnectionState = {
|
||||
connected: boolean;
|
||||
migrated: boolean;
|
||||
};
|
||||
|
||||
export const connectionState: ConnectionState = {
|
||||
connected: false,
|
||||
migrated: false,
|
||||
};
|
||||
|
||||
// Ping DB connection every 2 seconds
|
||||
let pingTimer: NodeJS.Timer | undefined;
|
||||
if (!inTest) {
|
||||
const pingDBFn = async () => {
|
||||
if (connection?.isInitialized) {
|
||||
try {
|
||||
await connection.query('SELECT 1');
|
||||
connectionState.connected = true;
|
||||
return;
|
||||
} catch (error) {
|
||||
ErrorReporter.error(error);
|
||||
} finally {
|
||||
pingTimer = setTimeout(pingDBFn, 2000);
|
||||
}
|
||||
}
|
||||
connectionState.connected = false;
|
||||
};
|
||||
pingTimer = setTimeout(pingDBFn, 2000);
|
||||
}
|
||||
|
||||
export async function transaction<T>(fn: (entityManager: EntityManager) => Promise<T>): Promise<T> {
|
||||
return await connection.transaction(fn);
|
||||
}
|
||||
|
||||
export async function init(): Promise<void> {
|
||||
if (connectionState.connected) return;
|
||||
|
||||
const connectionOptions = getConnectionOptions();
|
||||
connection = new Connection(connectionOptions);
|
||||
Container.set(Connection, connection);
|
||||
await connection.initialize();
|
||||
|
||||
connectionState.connected = true;
|
||||
}
|
||||
|
||||
export async function migrate() {
|
||||
(connection.options.migrations as Migration[]).forEach(wrapMigration);
|
||||
await connection.runMigrations({ transaction: 'each' });
|
||||
connectionState.migrated = true;
|
||||
}
|
||||
|
||||
export const close = async () => {
|
||||
if (pingTimer) {
|
||||
clearTimeout(pingTimer);
|
||||
pingTimer = undefined;
|
||||
}
|
||||
|
||||
if (connection.isInitialized) await connection.destroy();
|
||||
};
|
||||
Reference in New Issue
Block a user