import { join } from 'node:path' import { canonicalizeSqlFragments, isUnknownDatabaseError, listDictionaryDetails, listViewDetails, type ClickHouseExecutor, type IntrospectedTable, type SchemaObjectRef, } from '@chkit/clickhouse' import { compareCodePoints, configuredIndexGranularity, type ChxConfig, type DictionaryDefinition, type MaterializedViewDefinition, type Snapshot, type TableDefinition, type ViewDefinition, } from '@chkit/core' import { debug } from '../../runtime/debug.js' import type { TableScope } from '../../runtime/table-scope.js' import { collectDictionarySqlQueries, collectTableSqlFragments, collectViewSqlQueries, compareDictionaryShape, compareObjectComments, compareSchemaObjects, compareTableShape, compareViewShape, type ObjectDriftDetail, type SqlCanonicalizer, type TableDriftDetail, } from './compare.js' /** * Build a canonicalizer for every SQL fragment across the compared tables, * views and dictionaries, one batched ClickHouse query per kind. Returns * undefined when there is nothing to canonicalize or ClickHouse can't format * (old server, offline) — the comparer then falls back to plain string * normalization. */ async function buildSqlCanonicalizer( db: ClickHouseExecutor, pairs: Array<{ expected: TableDefinition; actual: IntrospectedTable }>, objectQueries: string[] ): Promise { const expressions: string[] = [] const queries: string[] = [...objectQueries] for (const { expected, actual } of pairs) { const fragments = collectTableSqlFragments(expected, actual) expressions.push(...fragments.expressions) queries.push(...fragments.queries) } if (expressions.length === 0 && queries.length === 0) return undefined try { // Report an unreadable system.functions registry once for both calls: // without it the #729 FLOOR drift would silently come back. let registryWarningLogged = false const onRegistryUnavailable = (error: unknown) => { if (registryWarningLogged) return registryWarningLogged = true debug('drift', `function registry unavailable, keeping function names as written: ${String(error)}`) } // One after the other: the CLI's executor is bound to one HTTP session, and // ClickHouse rejects a second query while the session is busy. const expressionMap = await canonicalizeSqlFragments(db, expressions, { wrap: true, onRegistryUnavailable }) const queryMap = await canonicalizeSqlFragments(db, queries, { wrap: false, onRegistryUnavailable }) return { expression: (fragment) => expressionMap.get(fragment) ?? null, query: (fragment) => queryMap.get(fragment) ?? null, } } catch (error) { debug('drift', `sql canonicalization unavailable, using string comparison: ${String(error)}`) return undefined } } export interface DriftPayload { scope?: TableScope snapshotFile: string expectedCount: number actualCount: number drifted: boolean databaseMissing?: boolean database?: string missing: string[] extra: string[] kindMismatches: Array<{ expected: string; actual: string; object: string }> objectDrift: ObjectDriftDetail[] tableDrift: TableDriftDetail[] } /** * Decide whether a schema has drifted. Objects that exist in ClickHouse but are * not in the schema (`extra_object` → `extraCount`) are NOT drift by default: * on a shared database every unmanaged table would otherwise break the CI gate. * Opt in with `check.failOnExtraObjects` to treat them as drift (e.g. when chkit * owns the whole database). */ export function computeDrifted(input: { missingCount: number kindMismatchCount: number tableDriftCount: number viewDriftCount: number extraCount: number failOnExtraObjects: boolean }): boolean { return ( input.missingCount > 0 || input.kindMismatchCount > 0 || input.tableDriftCount > 0 || input.viewDriftCount > 0 || (input.failOnExtraObjects && input.extraCount > 0) ) } export async function buildDriftPayload( config: ChxConfig, metaDir: string, snapshot: Snapshot, scope?: TableScope, executor?: ClickHouseExecutor ): Promise { const selectedTables = scope?.enabled && scope.matchCount > 0 ? new Set(scope.matchedTables) : undefined if (!executor) throw new Error('clickhouse config is required for drift checks') const db = executor debug('drift', `building drift payload — expected: ${snapshot.definitions.length} definitions`) let actualObjects: SchemaObjectRef[] try { actualObjects = await db.listSchemaObjects() } catch (error) { if (isUnknownDatabaseError(error)) { const allExpected = snapshot.definitions .filter((def) => { if (!selectedTables) return true if (def.kind !== 'table') return true return selectedTables.has(`${def.database}.${def.name}`) }) .map((def) => `${def.database}.${def.name}`) return { scope, snapshotFile: join(metaDir, 'snapshot.json'), expectedCount: allExpected.length, actualCount: 0, drifted: allExpected.length > 0, databaseMissing: true, database: config.clickhouse?.database, missing: allExpected, extra: [], kindMismatches: [], objectDrift: [], tableDrift: [], } } throw error } const expectedObjects = snapshot.definitions .filter((def) => { if (!selectedTables) return true if (def.kind !== 'table') return true return selectedTables.has(`${def.database}.${def.name}`) }) .map((def) => ({ kind: def.kind, database: def.database, name: def.name, comment: def.comment, })) const expectedDatabases = new Set(expectedObjects.map((def) => def.database)) const actualInScope = actualObjects.filter((item) => expectedDatabases.has(item.database)) const { missing, extra, kindMismatches, objectDrift } = compareSchemaObjects( expectedObjects, actualInScope ) const expectedTables = snapshot.definitions.filter((def): def is TableDefinition => { if (def.kind !== 'table') return false if (!selectedTables) return true return selectedTables.has(`${def.database}.${def.name}`) }) const expectedTableMap = new Map( expectedTables.map((table) => [`${table.database}.${table.name}`, table]) ) const actualTables = await db.listTableDetails([...expectedDatabases]) const pairs = actualTables.flatMap((actual) => { const expected = expectedTableMap.get(`${actual.database}.${actual.name}`) return expected ? [{ expected, actual }] : [] }) const expectedViewMap = new Map( snapshot.definitions .filter( (def): def is ViewDefinition | MaterializedViewDefinition => def.kind === 'view' || def.kind === 'materialized_view' ) .map((def) => [`${def.kind}:${def.database}.${def.name}`, def]) ) const actualViews = expectedViewMap.size > 0 ? await listViewDetails(db, [...expectedDatabases]) : [] const viewPairs = actualViews.flatMap((actual) => { const expected = expectedViewMap.get(`${actual.kind}:${actual.database}.${actual.name}`) return expected ? [{ expected, actual }] : [] }) const expectedDictionaryMap = new Map( snapshot.definitions .filter((def): def is DictionaryDefinition => def.kind === 'dictionary') .map((def) => [`${def.database}.${def.name}`, def]) ) const actualDictionaries = expectedDictionaryMap.size > 0 ? await listDictionaryDetails(db, [...expectedDatabases]) : [] const dictionaryPairs = actualDictionaries.flatMap((actual) => { const expected = expectedDictionaryMap.get(`${actual.database}.${actual.name}`) return expected ? [{ expected, queries: collectDictionarySqlQueries(expected, actual) }] : [] }) // Unqualified names in a view's query resolve to the session database. const currentDatabase = viewPairs.length > 0 ? (await db.query<{ database: string }>('SELECT currentDatabase() AS database'))[0]?.database : undefined const canonicalizer = await buildSqlCanonicalizer( db, pairs, [ ...viewPairs.flatMap(({ expected, actual }) => collectViewSqlQueries(expected, actual)), ...dictionaryPairs.flatMap(({ queries }) => (queries ? [queries.expected, queries.actual] : [])), ] ) const tableDrift = pairs .map(({ expected, actual }) => compareTableShape(expected, actual, canonicalizer, configuredIndexGranularity(config))) .filter((item): item is NonNullable => item !== null) .sort((a, b) => compareCodePoints(a.table, b.table)) const objectShapeDrift = [ ...viewPairs.flatMap(({ expected, actual }) => compareViewShape(expected, actual, currentDatabase ?? '', canonicalizer) ), ...dictionaryPairs.flatMap(({ expected, queries }) => compareDictionaryShape(expected, queries, canonicalizer)), ...compareObjectComments(expectedObjects, actualInScope), ].sort((a, b) => compareCodePoints(a.object, b.object)) const objectDriftWithViews = [...objectDrift, ...objectShapeDrift] debug('drift', `comparison: missing=${missing.length}, extra=${extra.length}, kindMismatches=${kindMismatches.length}, objectDrift=${objectDrift.length}, tableDrift=${tableDrift.length}, viewDrift=${objectShapeDrift.length}`) const drifted = computeDrifted({ missingCount: missing.length, kindMismatchCount: kindMismatches.length, tableDriftCount: tableDrift.length, viewDriftCount: objectShapeDrift.length, extraCount: extra.length, failOnExtraObjects: config.check?.failOnExtraObjects === true, }) return { scope, snapshotFile: join(metaDir, 'snapshot.json'), expectedCount: expectedObjects.length, actualCount: actualInScope.length, drifted, missing, extra, kindMismatches, objectDrift: objectDriftWithViews, tableDrift, } }