import { lstat, mkdir, rename, writeFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' import { assertServerIndexGranularity, type ClickHouseExecutor, createClickHouseExecutor, type IntrospectedTable, } from '@chkit/clickhouse' import { canonicalizeDefinitions, type ChxInlinePluginRegistration, compareCodePoints, configuredIndexGranularity, type ColumnDefaultValue, createPluginRunner, defineFlags, type DictionaryDefinition, type FlagMapping, normalizeEngine, isKafkaEngine, parseKafkaSettings, type ResolvedChxConfig, type SafeParseable, type SchemaDefinition, splitTopLevelComma, stripWrappingParens, type TableDefinition, withFactoryDefaults, } from '@chkit/core' export { renderSchemaFile } from './render-schema.js' import { renderSchemaFile } from './render-schema.js' import { mapSystemTableRowToDefinition, parseAsClause, parseRefreshClause, parseToClause, type IntrospectedObject, type SystemTableRow, } from './view-parser.js' // ───── Pull command schema ───── export const PullSchema = z.object({ outFile: z.string().min(1).default('./src/db/schema/pulled.ts'), databases: z.array(z.string()).default([]).transform((arr) => [...new Set(arr.map((s) => s.trim()).filter((s) => s.length > 0))].sort(compareCodePoints) ), overwrite: z.boolean().default(false), }) type PullOptions = z.infer // ───── Types ───── export interface PullPluginOptions { outFile?: string databases?: string[] overwrite?: boolean introspect?: PullIntrospector } export interface PullPluginCommandContext { args: string[] flags: Record jsonMode: boolean options: PullOptions rawOptions: Record config: ResolvedChxConfig configPath: string print: (value: unknown) => void /** Executor resolved by the host (e.g. the ObsessionDB remote executor when a service is selected). */ pluginContext?: { executor: ClickHouseExecutor; hasExecutor: boolean } } export interface PullPlugin { manifest: { name: 'pull' apiVersion: 1 version?: string } optionsSchema?: SafeParseable commands: Array<{ name: 'schema' description: string takesArgs?: boolean flags?: ReadonlyArray<{ name: string type: 'boolean' | 'string' | 'string[]' description: string placeholder?: string negation?: boolean short?: string }> optionsSchema?: SafeParseable flagMapping?: FlagMapping run: (context: PullPluginCommandContext) => undefined | number | Promise }> } export type PullIntrospector = (input: { config: NonNullable databases: string[] }) => Promise export type PullPluginRegistration = ChxInlinePluginRegistration // ───── CLI flag definitions ───── const PULL_SCHEMA_FLAGS = defineFlags([ { name: '--dryrun', type: 'boolean', description: 'Preview without writing files' }, { name: '--force', short: '-f', type: 'boolean', description: 'Overwrite existing output file' }, { name: '--overwrite', type: 'boolean', description: 'Overwrite existing output file (alias for --force)' }, { name: '--out-file', short: '-o', type: 'string', description: 'Output file path', placeholder: '' }, { name: '--database', short: '-d', type: 'string[]', description: 'Database names to pull', placeholder: '' }, ] as const) // ───── Flag mapping ───── const PULL_FLAG_MAP: FlagMapping = { '--out-file': { key: 'outFile' }, '--force': { key: 'overwrite' }, '--overwrite': { key: 'overwrite' }, '--database': { key: 'databases' }, } // ───── Errors ───── class PullConfigError extends Error { constructor(message: string) { super(message) this.name = 'PullConfigError' } } // ───── Plugin ───── interface PullSchemaResult { outFile: string definitionCount: number tableCount: number databases: string[] skippedObjects: Array<{ kind: string; count: number }> content: string warnings: string[] } const PASSWORD_LITERAL_RE = /password\s+'(?!\[HIDDEN\])(?:[^'\\]|\\.)*'/i // ClickHouse redacts a dictionary's SOURCE(...) password to `[HIDDEN]` on // introspection by default, and offers no way to recover the real value via // pull — flag it so the placeholder doesn't sit unnoticed in the schema // file. That redaction can also be turned off server-side (server config // `display_secrets_in_show_and_select` plus the `displaySecretsInShowAndSelect` // grant on the connecting user), in which case ClickHouse hands chkit the // real password and it's written verbatim into the schema file — chkit has // no way to detect or opt out of that, so flag it too. function dictionaryPasswordWarnings(definitions: SchemaDefinition[]): string[] { return definitions .filter((def): def is DictionaryDefinition => def.kind === 'dictionary') .flatMap((def) => { if (def.source.includes('[HIDDEN]')) { return [ `Dictionary "${def.database}.${def.name}" SOURCE(...) password was redacted by ClickHouse to '[HIDDEN]' — chkit could not recover the real value. Replace it in the generated schema file before this dictionary's source can be diffed or migrated. To have ClickHouse reveal real passwords on introspection instead, grant the connecting user "displaySecretsInShowAndSelect" and enable the server-side "display_secrets_in_show_and_select" setting.`, ] } if (PASSWORD_LITERAL_RE.test(def.source)) { return [ `Dictionary "${def.database}.${def.name}" SOURCE(...) has a plain-text password — ClickHouse returned the real credential on introspection and it was written verbatim into the generated schema file.`, ] } return [] }) } function stringArrayFlag(value: string | string[] | boolean | undefined): string[] | undefined { if (Array.isArray(value)) return value if (typeof value === 'string') return [value] return undefined } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } const runCommand = createPluginRunner({ configErrorClass: PullConfigError, }) export function createPullPlugin(options: PullPluginOptions = {}): PullPlugin { const { introspect: introspector, ...factoryOptions } = options const optionsSchema = withFactoryDefaults(PullSchema, factoryOptions) return { manifest: { name: 'pull', apiVersion: 1, }, optionsSchema, commands: [ { name: 'schema', description: 'Pull live ClickHouse table schema and write chkit schema file', takesArgs: false, flags: PULL_SCHEMA_FLAGS, optionsSchema, flagMapping: PULL_FLAG_MAP, run: runCommand({ command: 'schema', label: 'Pull schema', fn: async ({ flags, jsonMode, print, options: opts, config, pluginContext }) => { const flagOptions = { ...(typeof flags['--out-file'] === 'string' ? { outFile: flags['--out-file'] } : {}), ...(flags['--force'] === true || flags['--overwrite'] === true ? { overwrite: true } : {}), ...(stringArrayFlag(flags['--database']) ? { databases: stringArrayFlag(flags['--database']) } : {}), } const effectiveOptions = PullSchema.parse({ ...factoryOptions, ...(isRecord(opts) ? opts : {}), ...flagOptions, }) const dryrun = flags['--dryrun'] === true const pulled = await pullSchema({ config, executor: pluginContext?.hasExecutor ? pluginContext.executor : null, options: { ...effectiveOptions, introspect: introspector }, }) if (!dryrun) { await writeSchemaFile({ outFile: pulled.outFile, content: pulled.content, overwrite: effectiveOptions.overwrite, }) } const payload = { ok: true, command: 'schema' as const, outFile: pulled.outFile, definitionCount: pulled.definitionCount, tableCount: pulled.tableCount, databases: pulled.databases, skippedObjects: pulled.skippedObjects, dryrun, warnings: pulled.warnings, ...(dryrun ? { content: pulled.content } : {}), } if (jsonMode) { print(payload) return 0 } if (dryrun) { print( `Pull preview: ${pulled.definitionCount} objects from ${pulled.databases.join(', ') || '(none)'}` ) print(pulled.content) } else { print( `Pulled ${pulled.definitionCount} objects from ${pulled.databases.join(', ') || '(none)'} to ${pulled.outFile}` ) } for (const warning of pulled.warnings) console.warn(`Warning: ${warning}`) return 0 }, }), }, ], } } export function pull(options: PullPluginOptions = {}): PullPluginRegistration { return { plugin: createPullPlugin(options), name: 'pull', enabled: true, options, } } // ───── Internal helpers ───── // ObsessionDB provisions these product-metadata tables inside customer // databases. They are ObsessionDB internals, not part of the user's schema, so // pull must neither emit them nor count them as skipped/unsupported (#126). const OBSESSIONDB_METADATA_TABLES = new Set([ 'metadata_folder', 'metadata_table_folder', 'metadata_table_tag', ]) function isObsessionDbMetadataTable(object: { kind?: string; name: string }): boolean { // An introspected object is a table when it says so or omits `kind` entirely, // mirroring mapIntrospectedObjectToDefinition — a custom introspector returns // bare table objects without a `kind` field. const isTable = object.kind == null || object.kind === 'table' return isTable && OBSESSIONDB_METADATA_TABLES.has(object.name) } // chkit's migration journal (CHKIT_JOURNAL_TABLE, `_chkit_migrations` by // default) is chkit's own bookkeeping, not part of the user's schema (#466). function isJournalTable(object: { kind?: string; name: string }): boolean { const isTable = object.kind == null || object.kind === 'table' return isTable && object.name === (process.env.CHKIT_JOURNAL_TABLE?.trim() || '_chkit_migrations') } // The table that stores the rows of a materialized view without `TO` // (`.inner_id.`, or `.inner.` in an Ordinary database). It belongs // to the view, which pull skips, so it is not a user table either. function isMaterializedViewInnerTable(object: { kind?: string; name: string }): boolean { const isTable = object.kind == null || object.kind === 'table' return isTable && (object.name.startsWith('.inner_id.') || object.name.startsWith('.inner.')) } function isPulledObject(object: { kind?: string; name: string }): boolean { return !isObsessionDbMetadataTable(object) && !isJournalTable(object) && !isMaterializedViewInnerTable(object) } async function pullSchema(input: { config: ResolvedChxConfig executor?: ClickHouseExecutor | null options: PullOptions & { introspect?: PullIntrospector } }): Promise { const customIntrospector = input.options.introspect // Prefer the host-provided executor — e.g. the ObsessionDB remote executor when a service is // selected — so pull introspects through whatever target the rest of the CLI targets, not just a // direct ClickHouse URL. Fall back to building one from the clickhouse config block. const db: ClickHouseExecutor | null = input.executor ?? (input.config.clickhouse ? createClickHouseExecutor(input.config.clickhouse) : null) // A custom introspector opens its own raw-ClickHouse connection and needs the config block. if (customIntrospector && !input.config.clickhouse) { throw new PullConfigError('clickhouse config is required for a custom pull introspector') } if (!customIntrospector && !db) { throw new PullConfigError( 'pull needs a target: set CLICKHOUSE_URL or select an ObsessionDB service (chkit obsessiondb service select)' ) } // The pulled tables are compared later against definitions canonicalized // with clickhouse.indexGranularity, which must be this server's default. A // custom introspector reads elsewhere, so ClickHouse is not asked. if (db && !customIntrospector) await assertServerIndexGranularity(db, configuredIndexGranularity(input.config)) const outFile = resolve(process.cwd(), input.options.outFile) let objects: Array<{ kind: 'table' | 'view' | 'materialized_view' | 'dictionary' database: string name: string }> = [] let selectedDatabases = input.options.databases if (db && (!customIntrospector || selectedDatabases.length === 0)) { objects = (await db.listSchemaObjects()).filter(isPulledObject) if (selectedDatabases.length === 0) { selectedDatabases = [...new Set(objects.map((item) => item.database))].sort(compareCodePoints) } } const introspection = customIntrospector ? { objects: await customIntrospector({ config: input.config.clickhouse as NonNullable, databases: selectedDatabases, }), warnings: [], } : await introspectWithExecutor(db as ClickHouseExecutor, selectedDatabases) const introspected = introspection.objects.filter(isPulledObject) const definitions = canonicalizeDefinitions(introspected.map(mapIntrospectedObjectToDefinition), { indexGranularity: configuredIndexGranularity(input.config), }) // ObsessionDB reports the engine as Shared*, which canonicalization strips. const sharedTables = new Set( introspected .filter((object) => !('kind' in object) || object.kind === 'table') .filter((object) => ((object as { engine?: string }).engine ?? '').startsWith('Shared')) .map((object) => `${object.database}.${object.name}`) ) const content = renderSchemaFile(definitions, { sharedTables }) const tableCount = definitions.filter((definition) => definition.kind === 'table').length const skippedObjects = summarizeSkippedObjects(objects, definitions, selectedDatabases) const warnings = [ ...introspection.warnings, ...dictionaryPasswordWarnings(definitions), ...definitions.flatMap((def) => def.kind === 'table' && isKafkaEngine(def.engine) ? Object.entries(def.settings ?? {}).filter(([key]) => /password|secret|token/i.test(key)).map(([key, value]) => value === '[HIDDEN]' ? `Kafka table "${def.database}.${def.name}" setting ${key} was redacted by ClickHouse. Restore it or use server-side configuration before generating migrations.` : `Kafka table "${def.database}.${def.name}" setting ${key} contains a credential returned by ClickHouse and written into the schema file. Prefer server-side configuration.`) : []), ] return { outFile, definitionCount: definitions.length, tableCount, databases: selectedDatabases, skippedObjects, content, warnings, } } async function introspectWithExecutor( db: ClickHouseExecutor, databases: string[] ): Promise<{ objects: IntrospectedObject[]; warnings: string[] }> { const tables = await db.listTableDetails(databases) const nonTableRows = await listNonTableRows(db, databases) const nonTableObjects = nonTableRows .map(mapSystemTableRowToDefinition) .filter((definition): definition is Exclude => definition !== null) return { objects: [...tables.map((table) => ({ kind: 'table' as const, ...table })), ...nonTableObjects], warnings: nonTableRows.flatMap(innerStorageWarning), } } function innerStorageWarning(row: SystemTableRow): string[] { if (row.engine !== 'MaterializedView' || parseToClause(row.create_table_query, row.database)) return [] return [ `Materialized view "${row.database}.${row.name}" stores its rows in an inner table (it has no TO table), which the schema DSL does not support. Pull skipped the view and its inner table.`, ] } function mapIntrospectedTableToDefinition(table: IntrospectedTable): TableDefinition { return { kind: 'table', database: table.database, name: table.name, engine: normalizeEngine(table.engine ?? 'MergeTree()'), columns: table.columns.map((column) => ({ ...column, default: normalizeDefault(column.default), })), primaryKey: splitTopLevelCommaSeparated(table.primaryKey), orderBy: splitTopLevelCommaSeparated(table.orderBy), ...(table.uniqueKey ? { uniqueKey: splitTopLevelCommaSeparated(table.uniqueKey) } : {}), ...(table.partitionBy ? { partitionBy: table.partitionBy } : {}), ...(table.ttl ? { ttl: table.ttl } : {}), ...(Object.keys(table.settings).length > 0 ? { settings: isKafkaEngine(table.engine ?? '') ? parseKafkaSettings(table.settings) : table.settings } : {}), ...(table.indexes.length > 0 ? { indexes: table.indexes } : {}), ...(table.projections.length > 0 ? { projections: table.projections } : {}), ...(table.constraints && table.constraints.length > 0 ? { constraints: table.constraints } : {}), ...(table.comment ? { comment: table.comment } : {}), } } function mapIntrospectedObjectToDefinition(introspected: IntrospectedObject): SchemaDefinition { if ('kind' in introspected) { if (introspected.kind === 'table') return mapIntrospectedTableToDefinition(introspected) if (introspected.kind === 'view') { return { kind: 'view', database: introspected.database, name: introspected.name, as: introspected.as, ...(introspected.comment ? { comment: introspected.comment } : {}), } } if (introspected.kind === 'dictionary') { return { kind: 'dictionary', database: introspected.database, name: introspected.name, attributes: introspected.attributes, primaryKey: introspected.primaryKey, source: introspected.source, layout: introspected.layout, lifetime: introspected.lifetime, ...(introspected.range ? { range: introspected.range } : {}), ...(introspected.settings ? { settings: introspected.settings } : {}), ...(introspected.comment ? { comment: introspected.comment } : {}), } } return { kind: 'materialized_view', database: introspected.database, name: introspected.name, to: introspected.to, as: introspected.as, ...(introspected.refresh ? { refresh: introspected.refresh } : {}), ...(introspected.comment ? { comment: introspected.comment } : {}), } } return mapIntrospectedTableToDefinition(introspected) } // Introspection returns the SQL that ClickHouse stores for a default // (`now64(3)`, `'web'`, `0`), so every string is an expression, never a // literal to quote again. function normalizeDefault(value: ColumnDefaultValue | undefined): ColumnDefaultValue | undefined { if (typeof value === 'string') return { expression: value } return value } function summarizeSkippedObjects( objects: Array<{ kind: 'table' | 'view' | 'materialized_view' | 'dictionary' database: string name: string }>, definitions: SchemaDefinition[], selectedDatabases: string[] ): Array<{ kind: string; count: number }> { if (objects.length === 0) return [] const scoped = objects.filter((object) => selectedDatabases.includes(object.database)) const includedKeys = new Set( definitions.map((definition) => `${definition.kind}:${definition.database}.${definition.name}`) ) const counts = new Map() for (const object of scoped) { const key = `${object.kind}:${object.database}.${object.name}` if (includedKeys.has(key)) continue counts.set(object.kind, (counts.get(object.kind) ?? 0) + 1) } return [...counts.entries()] .map(([kind, count]) => ({ kind, count })) .sort((a, b) => compareCodePoints(a.kind, b.kind)) } function splitTopLevelCommaSeparated(input: string | undefined): string[] { if (!input) return [] return splitTopLevelComma(input).map(stripWrappingParens) } async function listNonTableRows( db: ReturnType, databases: string[] ): Promise { if (databases.length === 0) return [] const quotedDatabases = databases.map((dbName) => `'${dbName.replace(/'/g, "''")}'`).join(', ') return db.query( `SELECT database, name, engine, create_table_query, comment FROM system.tables WHERE is_temporary = 0 AND database IN (${quotedDatabases}) AND engine IN ('View', 'MaterializedView', 'Dictionary')` ) } export const __testUtils = { summarizeSkippedObjects, parseAsClause, parseToClause, parseRefreshClause, mapSystemTableRowToDefinition, } async function writeSchemaFile(input: { outFile: string content: string overwrite: boolean }): Promise { if (!input.overwrite) { const exists = await pathExists(input.outFile) if (exists) { throw new PullConfigError( `Output file already exists at ${input.outFile}. Re-run with --force or set plugin option overwrite=true.` ) } } await mkdir(dirname(input.outFile), { recursive: true }) const tempPath = join(dirname(input.outFile), `.${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`) await writeFile(tempPath, input.content, 'utf8') await rename(tempPath, input.outFile) } // lstat, not access: a dangling symlink is an existing entry that rename would replace (#702). async function pathExists(path: string): Promise { try { await lstat(path) return true } catch { return false } }