From c0eaf66c26df6ac4407356719a6d80564f351b11 Mon Sep 17 00:00:00 2001 From: Gao Sun Date: Mon, 17 Oct 2022 21:51:32 +0800 Subject: [PATCH] refactor(cli): add skip when exists option (#2172) --- .../cli/src/commands/database/seed/index.ts | 30 ++++++++++++++----- packages/cli/src/queries/logto-config.ts | 9 ++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/packages/cli/src/commands/database/seed/index.ts b/packages/cli/src/commands/database/seed/index.ts index 21bbcce2b..526e44df7 100644 --- a/packages/cli/src/commands/database/seed/index.ts +++ b/packages/cli/src/commands/database/seed/index.ts @@ -12,6 +12,7 @@ import { z } from 'zod'; import { createPoolAndDatabaseIfNeeded, insertInto } from '../../../database'; import { getRowsByKeys, + isConfigsTableExists, updateDatabaseTimestamp, updateValueByKey, } from '../../../queries/logto-config'; @@ -126,19 +127,32 @@ export const seedByPool = async (pool: DatabasePool, type: SeedChoice) => { }); }; -const seed: CommandModule, { type: string }> = { +const seed: CommandModule, { type: string; swe?: boolean }> = { command: 'seed [type]', describe: 'Create database then seed tables and data', builder: (yargs) => - yargs.positional('type', { - describe: 'Optional seed type', - type: 'string', - choices: seedChoices, - default: 'all', - }), - handler: async ({ type }) => { + yargs + .option('swe', { + describe: 'Skip the seeding process when Logto configs table exists', + alias: 'skip-when-exists', + type: 'boolean', + }) + .positional('type', { + describe: 'Optional seed type', + type: 'string', + choices: seedChoices, + default: 'all', + }), + handler: async ({ type, swe }) => { const pool = await createPoolAndDatabaseIfNeeded(); + if (swe && (await isConfigsTableExists(pool))) { + log.info('Seeding skipped'); + await pool.end(); + + return; + } + try { // Cannot avoid `as` since the official type definition of `yargs` doesn't work. // The value of `type` can be ensured, so it's safe to use `as` here. diff --git a/packages/cli/src/queries/logto-config.ts b/packages/cli/src/queries/logto-config.ts index 3e46019eb..d5fd51ac9 100644 --- a/packages/cli/src/queries/logto-config.ts +++ b/packages/cli/src/queries/logto-config.ts @@ -7,11 +7,20 @@ import { AlterationStateKey, } from '@logto/schemas'; import { convertToIdentifiers } from '@logto/shared'; +import { Nullable } from '@silverhand/essentials'; import { DatabasePool, DatabaseTransactionConnection, sql } from 'slonik'; import { z } from 'zod'; const { table, fields } = convertToIdentifiers(LogtoConfigs); +export const isConfigsTableExists = async (pool: DatabasePool) => { + const { rows } = await pool.query>( + sql`select to_regclass(${LogtoConfigs.table})` + ); + + return Boolean(rows[0]); +}; + export const getRowsByKeys = async ( pool: DatabasePool | DatabaseTransactionConnection, keys: LogtoConfigKey[]