import { parseAttributeListTextFromCreateDictionaryQuery, parseDictionaryPrimaryKeyFromCreateDictionaryQuery, parseDictionaryRangeFromCreateDictionaryQuery, parseDictionarySettingsFromCreateDictionaryQuery, parseLayoutFromCreateDictionaryQuery, parseLifetimeFromCreateDictionaryQuery, parseSourceFromCreateDictionaryQuery, replaceSourceInCreateDictionaryQuery, stringLiteral, } from '@chkit/clickhouse' import { canonicalizeTextIndex, columnCodecFingerprint, columnTypeFingerprint, compareCodePoints, DEFAULT_INDEX_GRANULARITY, literalDefaultFingerprint, constraintExpression, constraintKind, identifierName, normalizeEngine as coreNormalizeEngine, isKafkaEngine, parseKafkaSettings, kafkaSettingFingerprint, isIndexProjection, isSyntheticEphemeralDefault, normalizeProjectionIndex, normalizeSQLFragment, renderDefault, renderDictionarySQL, renderKeyClauseColumns, splitTopLevelComma, sqlExpressionFingerprint, findMatchingParen, isTrivia, keyClauseFingerprint, stringLiteralValue, type ColumnDefinition, type DictionaryDefinition, type ProjectionDefinition, type SkipIndexDefinition, type SQLToken, textIndexFingerprint, type TextSkipIndex, tokenizeSQL, renderVectorIndexType, replicatedEngineAsShared, type MaterializedViewDefinition, type TableConstraintDefinition, type TableDefinition, vectorIndexGranularity, type ViewDefinition, withDefaultIndexGranularity, } from '@chkit/core' import { debug } from '../../runtime/debug.js' import { diffByName, diffNamedShapeMaps, diffSettings } from './diff.js' /** * Canonicalizes SQL fragments to the exact form ClickHouse stores, so a schema * fragment compares equal to what a live table reports even when the two are * spelled differently (`cityHash64(a,b)` vs `cityHash64(a, b)`, `n*2+1` vs * `(n * 2) + 1`, `INTERVAL 5 YEAR` vs `toIntervalYear(5)`). Only ClickHouse's own * formatter can produce this, so it is injected by the drift command; when it is * absent (offline, or a fragment ClickHouse couldn't parse) each field falls * back to plain string normalization (#195). */ export interface SqlCanonicalizer { expression(fragment: string): string | null query(fragment: string): string | null } function canonicalizeExpression(base: string, canonicalizer?: SqlCanonicalizer): string { return canonicalizer?.expression(base) ?? base } type TableDriftReasonCode = | 'missing_column' | 'extra_column' | 'changed_column' | 'setting_mismatch' | 'index_mismatch' | 'ttl_mismatch' | 'engine_mismatch' | 'primary_key_mismatch' | 'order_by_mismatch' | 'partition_by_mismatch' | 'unique_key_mismatch' | 'projection_mismatch' | 'constraint_mismatch' type ObjectDriftReasonCode = | 'missing_object' | 'extra_object' | 'kind_mismatch' | 'query_mismatch' | 'target_mismatch' | 'comment_mismatch' | 'source_mismatch' | 'structure_mismatch' | 'layout_mismatch' | 'lifetime_mismatch' | 'dictionary_setting_mismatch' type DriftReasonCode = ObjectDriftReasonCode | TableDriftReasonCode interface SchemaObjectShape { kind: 'table' | 'view' | 'materialized_view' | 'dictionary' database: string name: string comment?: string } export interface ObjectDriftDetail { code: ObjectDriftReasonCode object: string expectedKind?: SchemaObjectShape['kind'] actualKind?: SchemaObjectShape['kind'] /** Any code that compares two values: the schema's value and the live one. */ expected?: string actual?: string } /** What ClickHouse stores in place of a secret in a view's query or a dictionary's source. */ const HIDDEN_SECRET = "'[HIDDEN]'" interface ActualViewShape { query: string to?: { database: string; name: string } } interface ActualDictionaryShape { /** The `CREATE DICTIONARY` statement as ClickHouse stores it. */ createQuery: string } interface ActualTableShape { columns: ColumnDefinition[] settings: Record indexes: SkipIndexDefinition[] ttl?: string engine?: string primaryKey?: string orderBy?: string uniqueKey?: string partitionBy?: string projections: ProjectionDefinition[] constraints?: TableConstraintDefinition[] } export interface TableDriftDetail { table: string reasonCodes: TableDriftReasonCode[] missingColumns: string[] extraColumns: string[] changedColumns: string[] settingDiffs: string[] indexDiffs: string[] ttlMismatch: boolean engineMismatch: boolean primaryKeyMismatch: boolean orderByMismatch: boolean uniqueKeyMismatch: boolean partitionByMismatch: boolean projectionDiffs: string[] constraintDiffs: string[] } interface DriftReasonSummary { counts: Partial> total: number object: number table: number } function schemaObjectKey(item: Pick): string { return `${item.kind}:${item.database}.${item.name}` } export function compareSchemaObjects( expectedObjects: SchemaObjectShape[], actualObjects: SchemaObjectShape[] ): { missing: string[] extra: string[] kindMismatches: Array<{ expected: string; actual: string; object: string }> objectDrift: ObjectDriftDetail[] } { const expectedMap = new Map(expectedObjects.map((item) => [schemaObjectKey(item), item.kind])) const actualMap = new Map(actualObjects.map((item) => [schemaObjectKey(item), item.kind])) const missing: string[] = [] const extra: string[] = [] const kindMismatches: Array<{ expected: string; actual: string; object: string }> = [] const objectDrift: ObjectDriftDetail[] = [] for (const [key, kind] of expectedMap.entries()) { const rest = key.slice(key.indexOf(':') + 1) const actualKind = actualMap.get(key) if (actualKind) continue const sameObjectDifferentKind = [...actualMap.entries()].find(([actualKey]) => actualKey.endsWith(`:${rest}`) ) if (sameObjectDifferentKind) { const mismatch = { object: rest, expected: kind, actual: sameObjectDifferentKind[1], } kindMismatches.push(mismatch) objectDrift.push({ code: 'kind_mismatch', object: rest, expectedKind: mismatch.expected, actualKind: mismatch.actual, }) continue } missing.push(key) objectDrift.push({ code: 'missing_object', object: key, expectedKind: kind, }) } for (const [key, kind] of actualMap.entries()) { if (expectedMap.has(key)) continue const rest = key.slice(key.indexOf(':') + 1) const hasExpectedWithDifferentKind = [...expectedMap.keys()].some((expectedKey) => expectedKey.endsWith(`:${rest}`) ) if (hasExpectedWithDifferentKind) continue extra.push(key) objectDrift.push({ code: 'extra_object', object: key, actualKind: kind, }) } return { missing, extra, kindMismatches, objectDrift, } } /** * Compares the comment of every table, view, materialized view and dictionary * that exists on both sides with the same kind. The live comment is * `system.tables.comment`, which ClickHouse has already decoded. */ export function compareObjectComments( expectedObjects: SchemaObjectShape[], actualObjects: SchemaObjectShape[] ): ObjectDriftDetail[] { const actualComments = new Map(actualObjects.map((item) => [schemaObjectKey(item), item.comment])) return expectedObjects.flatMap((item): ObjectDriftDetail[] => { const actual = actualComments.get(schemaObjectKey(item)) if (actual === undefined) return [] const expectedComment = item.comment?.trim() ?? '' const actualComment = actual.trim() if (expectedComment === actualComment) return [] return [ { code: 'comment_mismatch', object: `${item.database}.${item.name}`, expected: expectedComment, actual: actualComment, }, ] }) } export function summarizeDriftReasons(input: { objectDrift: ObjectDriftDetail[] tableDrift: TableDriftDetail[] }): DriftReasonSummary { const counts: Partial> = {} let object = 0 let table = 0 for (const item of input.objectDrift) { counts[item.code] = (counts[item.code] ?? 0) + 1 object += 1 } for (const tableDrift of input.tableDrift) { for (const code of tableDrift.reasonCodes) { counts[code] = (counts[code] ?? 0) + 1 table += 1 } } return { counts, total: object + table, object, table, } } // system.columns stores SQL, whereas schema strings are literals unless fn:-prefixed. function liveColumns(actual: ActualTableShape): ColumnDefinition[] { return actual.columns.map((column) => ({ ...column, default: typeof column.default === 'string' && !column.default.startsWith('fn:') ? `fn:${column.default}` : column.default, })) } // ClickHouse stores a bare EPHEMERAL column as defaultValueOfTypeName(''), // which introspection reads back as no expression; an explicit one matches it. function columnDefaultSql(column: ColumnDefinition): string | undefined { const rendered = column.default === undefined ? undefined : renderDefault(column.default) if (rendered === undefined) return undefined if (column.defaultKind === 'EPHEMERAL' && isSyntheticEphemeralDefault(rendered)) return undefined return rendered } // A DEFAULT, MATERIALIZED or ALIAS expression goes through the canonicalizer, // since ClickHouse re-formats it when it stores it (`id*2+1` comes back as // `(id * 2) + 1`). A literal compares by its value (#466). function normalizeColumnShape(column: ColumnDefinition, canonicalizer?: SqlCanonicalizer): string { const rendered = columnDefaultSql(column) const normalizedDefault = rendered === undefined ? '' : (literalDefaultFingerprint(rendered) ?? sqlExpressionFingerprint(canonicalizer?.expression(rendered.trim()) ?? rendered)) const parts = [ // Introspection unwraps Nullable(T) into type=T plus nullable=true, and // ClickHouse spaces the type its own way (`Decimal(10, 2)`). `type=${columnTypeFingerprint(column)}`, `default=${normalizedDefault}`, `defaultKind=${column.defaultKind ?? 'DEFAULT'}`, `comment=${column.comment?.trim() ?? ''}`, `codec=${columnCodecFingerprint(column)}`, ] return parts.join('|') } function renderIndexTypeFingerprint(index: SkipIndexDefinition): string { switch (index.type) { case 'text': return textIndexFingerprint(index) case 'vector_similarity': return renderVectorIndexType(index) case 'raw': return normalizeSQLFragment(index.rawType) case 'minmax': return 'minmax' case 'set': return `set(${index.maxRows})` case 'bloom_filter': return index.falsePositiveRate !== undefined ? `bloom_filter(${index.falsePositiveRate})` : 'bloom_filter' case 'tokenbf_v1': return `tokenbf_v1(${index.sizeBytes}, ${index.hashFunctions}, ${index.randomSeed})` case 'ngrambf_v1': return `ngrambf_v1(${index.ngramSize}, ${index.sizeBytes}, ${index.hashFunctions}, ${index.randomSeed})` } } // chkit renders `INDEX name (expr)`. Stock ClickHouse drops the parentheses // that enclose the whole expression, ObsessionDB keeps one pair (#512), and a // schema may write more (`((s))`). Peel every such pair, reading the SQL with // the shared lexer so `(a) + (b)` and the parentheses inside a string, quoted // name or heredoc (`$$)$$`) stay intact. function indexExpressionBase(index: SkipIndexDefinition): string { let expression = normalizeSQLFragment(index.expression) for (;;) { const tokens = tokenizeSQL(expression).filter((token) => !isTrivia(token)) const first = tokens[0] const last = tokens.at(-1) if (first?.text !== '(' || last?.text !== ')') return expression let depth = 0 const encloses = tokens.every((token, i) => { if (token.text === '(') depth++ else if (token.text === ')') depth-- return depth > 0 || i === tokens.length - 1 }) if (!encloses) return expression expression = expression.slice(first.end, last.start).trim() } } // ClickHouse re-formats a text index expression when it stores it, e.g. // `NOT a AND b` comes back as `(NOT a) AND b`, so the expression goes through // the canonicalizer like any other index expression. It is read with the text // index lexer rather than normalizeSQLFragment, which would collapse the spaces // inside its string literals. function textIndexExpressionBase(index: TextSkipIndex): string { return canonicalizeTextIndex(index).expression } function normalizeIndexShape(index: SkipIndexDefinition, canonicalizer?: SqlCanonicalizer): string { if (index.type === 'text') { const expression = canonicalizer?.expression(textIndexExpressionBase(index)) return textIndexFingerprint(expression == null ? index : { ...index, expression }) } return [ `expr=${canonicalizeExpression(indexExpressionBase(index), canonicalizer)}`, // A raw type is compared as ClickHouse formats it, so a structured index on // one side and the same type written raw on the other compare equal. `type=${canonicalizeExpression(renderIndexTypeFingerprint(index), canonicalizer)}`, `granularity=${index.type === 'vector_similarity' ? vectorIndexGranularity(index) : index.granularity}`, ].join('|') } // ClickHouse re-formats a constraint expression when it stores it, e.g. // `s IN ('a','b') AND (id+1)*2 > 0` comes back as // `(s IN ('a', 'b')) AND (((id + 1) * 2) > 0)`, so both sides go through the // canonicalizer. function normalizeConstraintShape(constraint: TableConstraintDefinition, canonicalizer?: SqlCanonicalizer): string { const expression = canonicalizeExpression(normalizeSQLFragment(constraintExpression(constraint)), canonicalizer) return `${constraintKind(constraint)} ${expression}` } function normalizeProjectionShape( projection: ProjectionDefinition, canonicalizer?: SqlCanonicalizer ): string { if (isIndexProjection(projection)) { return [ `index=${normalizeProjectionIndex(projection.index)}`, `type=${projection.type.trim()}`, ].join('|') } const base = normalizeSQLFragment(projection.query) return `query=${canonicalizer?.query(base) ?? base}` } // Key and partition clauses are compared as SQL: the schema's keys as chkit // renders them, the live clauses as ClickHouse reports them. Comments are // removed while quoted names still carry their backticks. Then each side is // compared by its tokens, where a name matches however ClickHouse re-quotes it // and keeps its commas and spaces: `` `a, b` `` is one column, not `a` and `b` // (#558). One pair of parentheses around the whole clause is dropped. A // canonicalizer sees each element while its names are still quoted, since // unquoted, `user--id` would read as `user` followed by a comment. function normalizeClause(value: string | undefined, canonicalizer?: SqlCanonicalizer): string { if (!value) return '' const sql = normalizeSQLFragment(value) const canonical = canonicalizer ? clauseElements(sql) .map((element) => canonicalizeExpression(element, canonicalizer)) .join(', ') : sql const tokens = keyClauseFingerprint(canonical) // Tokens are joined by single spaces, and only a `)` token ends in ` )`. return tokens.match(/^\( (.+) \)$/)?.[1] ?? tokens } /** The elements of a key/partition clause, canonicalized one by one so a * function expression (`cityHash64(a,b)`) matches ClickHouse's spelling. */ function clauseElements(sql: string): string[] { const wrapped = sql.match(/^\((.*)\)$/) return splitTopLevelComma(wrapped?.[1] ?? sql) } /** The key/partition clauses compared for a table, schema side vs live side. */ function tableClauses(expected: TableDefinition, actual: ActualTableShape) { // ClickHouse derives PRIMARY KEY from ORDER BY when it is omitted, then omits // it from SHOW CREATE — so a table with only ORDER BY reports no primary key. // Mirror that on both sides (as canonical.ts does for the schema), else every // such table drifts forever (#194). // Render expected keys as chkit emits them so declared column names (which may // contain commas or backticks) are compared as single identifiers. const columnNames = new Set(expected.columns.map((column) => column.name)) return { primaryKey: [ renderKeyClauseColumns( expected.primaryKey.length > 0 ? expected.primaryKey : expected.orderBy, columnNames ), actual.primaryKey ?? actual.orderBy, ], orderBy: [renderKeyClauseColumns(expected.orderBy, columnNames), actual.orderBy], uniqueKey: [renderKeyClauseColumns(expected.uniqueKey ?? [], columnNames), actual.uniqueKey], partitionBy: [expected.partitionBy, actual.partitionBy], } satisfies Record } // Keywords the server rewrites in engine arguments: `is null` reads back as // `IS NULL`, `TRUE` as `true`. A bare `true`, `false` or `null` is always a literal. const ENGINE_LITERAL_KEYWORDS = new Set(['null', 'true', 'false']) const ENGINE_OPERATOR_KEYWORDS = new Set(['and', 'or', 'not', 'is', 'in', 'like', 'ilike', 'distinct', 'from', 'global']) // The operator keywords that can open an expression (`NOT x`, `count(DISTINCT x)`); // the others always follow an operand. const ENGINE_PREFIX_KEYWORDS = new Set(['not', 'distinct']) // Names the server keeps quoted because they read back as a literal when bare // (writeProbablyQuotedStringImpl): `true` is a Bool, `` `true` `` a column. const ENGINE_LITERAL_NAMES = new Set(['null', 'true', 'false', 'inf', 'infinity', 'nan']) // Keywords the server quotes as names from some version on: 26.3 writes a // `cube` column bare, later versions `` `cube` ``. const ENGINE_KEYWORD_NAMES = new Set(['distinct', 'all', 'some', 'table', 'select', 'cube', 'rollup', 'recursive']) const BARE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ /** * Column names and string literals in engine arguments are case-sensitive, so * they keep their case (#673). Function names (`RAND()` reads back as `rand()`) * and operator keywords do not, and whitespace between tokens is insignificant. * An operator keyword where an operand belongs (`if(And > 1, 1, 0)`) can only be * a column. A quoted name compares as the server writes it back (#679). */ function normalizeEngine(value: string | undefined): string { if (!value) return '' const tokens = tokenizeSQL(coreNormalizeEngine(normalizeSQLFragment(value))) .filter((token) => !isTrivia(token)) .map((token, index, all) => unquoteEngineName(token, all[index - 1], all[index + 1])) return tokens .map((token, index) => { if (token.kind !== 'identifier') return token.text const lower = token.text.toLowerCase() const previous = tokens[index - 1] const next = tokens[index + 1] const keyword = ENGINE_LITERAL_KEYWORDS.has(lower) || isOperatorKeyword(lower, previous, next) return next?.text === '(' || keyword ? lower : token.text }) .join(' ') } /** * The server writes a quoted name bare when the quotes are not needed: `Ver` * for `` `Ver` `` or `"Ver"`, and `Null` for an engine or function name, which * the server itself writes as `` `Null` ``. A name that needs its quotes keeps * them, in backticks, so different names never compare equal. An unquoted name * stays a quoted identifier, so it keeps its case even where a keyword could be. */ function unquoteEngineName(token: SQLToken, previous: SQLToken | undefined, next: SQLToken | undefined): SQLToken { const name = token.kind === 'quoted_identifier' ? identifierName(token) : undefined if (name === undefined || !BARE_NAME.test(name)) { return name === undefined ? token : { ...token, text: `\`${name.replaceAll('\\', '\\\\').replaceAll('`', '\\`')}\`` } } if (next?.text === '(') return { ...token, kind: 'identifier', text: name } const lower = name.toLowerCase() const keepsQuotes = ENGINE_LITERAL_NAMES.has(lower) || (ENGINE_KEYWORD_NAMES.has(lower) && (endsOperand(previous) || startsOperand(next))) return keepsQuotes ? { ...token, text: `\`${name}\`` } : { ...token, text: name } } function isOperatorKeyword(lower: string, previous: SQLToken | undefined, next: SQLToken | undefined): boolean { if (!ENGINE_OPERATOR_KEYWORDS.has(lower)) return false return endsOperand(previous) || (ENGINE_PREFIX_KEYWORDS.has(lower) && startsOperand(next)) } function endsOperand(token: SQLToken | undefined): boolean { return token !== undefined && (isValueToken(token) || token.text === ')' || token.text === ']') } function startsOperand(token: SQLToken | undefined): boolean { return token !== undefined && (isValueToken(token) || token.text === '(') } function isValueToken(token: SQLToken): boolean { return ['identifier', 'quoted_identifier', 'number', 'string'].includes(token.kind) } /** * ObsessionDB and ClickHouse Cloud store a `Replicated*MergeTree` table as * `Shared*MergeTree`, without the Keeper path and replica name (#669). */ function enginesMatch(expected: string | undefined, actual: string | undefined): boolean { if (normalizeEngine(expected) === normalizeEngine(actual)) return true if (!expected || !actual || !actual.trim().startsWith('Shared')) return false const shared = replicatedEngineAsShared(expected) return shared !== undefined && normalizeEngine(shared) === normalizeEngine(actual) } /** * Every SQL fragment `compareTableShape` will look up in a `SqlCanonicalizer`, * at the exact granularity it looks them up (whole expressions for column * defaults and index/ttl, per-element for key/partition clauses, whole query * for SELECT projections). * The drift command collects these across all compared tables, formats them in * one round-trip, and hands back a map-backed canonicalizer. */ export function collectTableSqlFragments( expected: TableDefinition, actual: ActualTableShape ): { expressions: string[]; queries: string[] } { const expressions: string[] = [] const queries: string[] = [] for (const column of [...expected.columns, ...liveColumns(actual)]) { const sql = columnDefaultSql(column) if (sql !== undefined && literalDefaultFingerprint(sql) === undefined) expressions.push(sql.trim()) } for (const index of [...(expected.indexes ?? []), ...actual.indexes]) { expressions.push(index.type === 'text' ? textIndexExpressionBase(index) : indexExpressionBase(index)) } for (const index of [...(expected.indexes ?? []), ...actual.indexes]) { if (index.type !== 'text') expressions.push(renderIndexTypeFingerprint(index)) } for (const constraint of [...(expected.constraints ?? []), ...(actual.constraints ?? [])]) { expressions.push(normalizeSQLFragment(constraintExpression(constraint))) } for (const ttl of [expected.ttl, actual.ttl]) { if (ttl) expressions.push(normalizeSQLFragment(ttl)) } for (const clause of Object.values(tableClauses(expected, actual)).flat()) { if (clause) expressions.push(...clauseElements(normalizeSQLFragment(clause))) } for (const projection of [...(expected.projections ?? []), ...actual.projections]) { if (!isIndexProjection(projection)) queries.push(normalizeSQLFragment(projection.query)) } return { expressions, queries } } export function compareTableShape( expected: TableDefinition, actual: ActualTableShape, canonicalizer?: SqlCanonicalizer, /** `clickhouse.indexGranularity`, for a live table that does not show index_granularity. */ indexGranularity: number = DEFAULT_INDEX_GRANULARITY ): TableDriftDetail | null { const columnDiff = diffByName( expected.columns, liveColumns(actual), (column: ColumnDefinition) => column.name, (column: ColumnDefinition) => normalizeColumnShape(column, canonicalizer) ) const missingColumns = columnDiff.missing const extraColumns = columnDiff.extra const changedColumns = columnDiff.changed const kafka = isKafkaEngine(expected.engine) const expectedSettings = kafka ? Object.fromEntries(Object.entries(expected.settings ?? {}).map(([key, value]) => [key, kafkaSettingFingerprint(value)])) : expected.settings ?? {} const actualSettings = kafka ? Object.fromEntries(Object.entries(parseKafkaSettings(actual.settings)).map(([key, value]) => [key, kafkaSettingFingerprint(value)])) : withDefaultIndexGranularity(actual.engine ?? expected.engine, actual.settings, indexGranularity) ?? {} const settingDiffs = diffSettings(expectedSettings, actualSettings) const expectedIndexes = new Map( (expected.indexes ?? []).map((idx) => [idx.name, normalizeIndexShape(idx, canonicalizer)]) ) const actualIndexes = new Map( actual.indexes.map((idx) => [idx.name, normalizeIndexShape(idx, canonicalizer)]) ) const indexDiffs = diffNamedShapeMaps(expectedIndexes, actualIndexes) const expectedTTL = canonicalizeExpression( expected.ttl ? normalizeSQLFragment(expected.ttl) : '', canonicalizer ) const actualTTL = canonicalizeExpression( actual.ttl ? normalizeSQLFragment(actual.ttl) : '', canonicalizer ) const ttlMismatch = expectedTTL !== actualTTL const engineMismatch = !enginesMatch(expected.engine, actual.engine) const clauses = tableClauses(expected, actual) const expectedPrimaryKey = normalizeClause(clauses.primaryKey[0], canonicalizer) const actualPrimaryKey = normalizeClause(clauses.primaryKey[1], canonicalizer) const primaryKeyMismatch = expectedPrimaryKey !== actualPrimaryKey const expectedOrderBy = normalizeClause(clauses.orderBy[0], canonicalizer) const actualOrderBy = normalizeClause(clauses.orderBy[1], canonicalizer) const orderByMismatch = expectedOrderBy !== actualOrderBy const expectedUniqueKey = normalizeClause(clauses.uniqueKey[0], canonicalizer) const actualUniqueKey = normalizeClause(clauses.uniqueKey[1], canonicalizer) const uniqueKeyMismatch = expectedUniqueKey !== actualUniqueKey const expectedPartitionBy = normalizeClause(clauses.partitionBy[0], canonicalizer) const actualPartitionBy = normalizeClause(clauses.partitionBy[1], canonicalizer) const partitionByMismatch = expectedPartitionBy !== actualPartitionBy const expectedProjections = new Map( (expected.projections ?? []).map((projection) => [ projection.name, normalizeProjectionShape(projection, canonicalizer), ]) ) const actualProjections = new Map( actual.projections.map((projection) => [ projection.name, normalizeProjectionShape(projection, canonicalizer), ]) ) const projectionDiffs = diffNamedShapeMaps(expectedProjections, actualProjections) const constraintDiffs = diffNamedShapeMaps( new Map((expected.constraints ?? []).map((item) => [item.name, normalizeConstraintShape(item, canonicalizer)])), new Map((actual.constraints ?? []).map((item) => [item.name, normalizeConstraintShape(item, canonicalizer)])) ) const reasonCodes: TableDriftReasonCode[] = [] if (missingColumns.length > 0) reasonCodes.push('missing_column') if (extraColumns.length > 0) reasonCodes.push('extra_column') if (changedColumns.length > 0) reasonCodes.push('changed_column') if (settingDiffs.length > 0) reasonCodes.push('setting_mismatch') if (indexDiffs.length > 0) reasonCodes.push('index_mismatch') if (ttlMismatch) reasonCodes.push('ttl_mismatch') if (engineMismatch) reasonCodes.push('engine_mismatch') if (primaryKeyMismatch) reasonCodes.push('primary_key_mismatch') if (orderByMismatch) reasonCodes.push('order_by_mismatch') if (uniqueKeyMismatch) reasonCodes.push('unique_key_mismatch') if (partitionByMismatch) reasonCodes.push('partition_by_mismatch') if (projectionDiffs.length > 0) reasonCodes.push('projection_mismatch') if (constraintDiffs.length > 0) reasonCodes.push('constraint_mismatch') if (reasonCodes.length === 0) return null return { table: `${expected.database}.${expected.name}`, reasonCodes, missingColumns: missingColumns.sort((a, b) => compareCodePoints(a, b)), extraColumns: extraColumns.sort((a, b) => compareCodePoints(a, b)), changedColumns: changedColumns.sort((a, b) => compareCodePoints(a, b)), settingDiffs, indexDiffs, ttlMismatch, engineMismatch, primaryKeyMismatch, orderByMismatch, uniqueKeyMismatch, partitionByMismatch, projectionDiffs, constraintDiffs, } } /** The view and materialized view queries `compareViewShape` will look up. */ export function collectViewSqlQueries( expected: ViewDefinition | MaterializedViewDefinition, actual: ActualViewShape ): string[] { // Formatting the schema's query would log its secret in `system.query_log`. if (actual.query.includes(HIDDEN_SECRET)) return [] return [normalizeSQLFragment(expected.as), normalizeSQLFragment(actual.query)] } /** * Compares a view or materialized view query with the live one, and a * materialized view's `TO` target. ClickHouse stores the query reformatted, so * the queries are compared only as its formatter renders them: when either side * can't be formatted, the query is not compared, rather than reporting drift * on a query that may be the same. Nor is a query in which ClickHouse replaced * a secret (a table function's password) with `'[HIDDEN]'`: it never matches * the schema, and the schema's side would print the secret. */ export function compareViewShape( expected: ViewDefinition | MaterializedViewDefinition, actual: ActualViewShape, currentDatabase: string, canonicalizer?: SqlCanonicalizer ): ObjectDriftDetail[] { const object = `${expected.database}.${expected.name}` const drift: ObjectDriftDetail[] = [] if (canonicalizer && !actual.query.includes(HIDDEN_SECRET)) { const expectedQuery = canonicalizer.query(normalizeSQLFragment(expected.as)) const actualQuery = canonicalizer.query(normalizeSQLFragment(actual.query)) if (expectedQuery && actualQuery) { const expectedShape = stripDatabaseQualifier(expectedQuery, currentDatabase) const actualShape = stripDatabaseQualifier(actualQuery, currentDatabase) if (expectedShape !== actualShape) { drift.push({ code: 'query_mismatch', object, expected: expectedShape, actual: actualShape }) } } } if (expected.kind === 'materialized_view') { const expectedTo = `${expected.to.database}.${expected.to.name}` // A live materialized view with an inner table has no `TO`. const actualTo = actual.to ? `${actual.to.database}.${actual.to.name}` : '' if (expectedTo !== actualTo) { drift.push({ code: 'target_mismatch', object, expected: expectedTo, actual: actualTo }) } } return drift } /** * Removes `.` in front of names. ClickHouse qualifies every table * name in a view's query with the database the view was created from, so a * schema's `FROM events` is stored as `FROM analytics.events`, and the * dictionary name in `dictGet('users', …)` as `'analytics.users'`. Both sides * drop that qualifier, which names the same object as no qualifier. */ function stripDatabaseQualifier(sql: string, database: string): string { const tokens = tokenizeSQL(sql) const qualifiedLiteral = `'${database}.` let out = '' for (let i = 0; i < tokens.length; i++) { const token = tokens[i] if (!token) continue const callee = tokens[i - 2] const dictionaryName = token.kind === 'string' && token.text.startsWith(qualifiedLiteral) && tokens[i - 1]?.text === '(' && callee !== undefined && /^dict/i.test(identifierName(callee) ?? '') if (dictionaryName) { out += `'${token.text.slice(qualifiedLiteral.length)}` continue } const next = tokens[i + 2] const qualifier = identifierName(token) === database && tokens[i - 1]?.text !== '.' && tokens[i + 1]?.text === '.' && next !== undefined && identifierName(next) !== undefined if (qualifier) { i += 1 continue } out += token.text } return out } /** The clauses `compareDictionaryShape` reads from both formatted statements, by drift code. */ const DICTIONARY_CLAUSES: ReadonlyArray<[ObjectDriftReasonCode, (query: string) => string]> = [ ['structure_mismatch', dictionaryStructure], ['layout_mismatch', (query) => parseLayoutFromCreateDictionaryQuery(query) ?? ''], ['lifetime_mismatch', (query) => parseLifetimeFromCreateDictionaryQuery(query) ?? ''], ['dictionary_setting_mismatch', dictionarySettings], ] /** * Source keys whose whole value is a secret: the keys ClickHouse hides, and the * keys newer ClickHouse versions hide but 26.3 stores in clear. Drift hides * them on both sides, so `expected` never shows one. */ const SECRET_SOURCE_KEYS = new Set([ 'PASSWORD', 'HEADERS', 'HEADER', 'CONNECTION_STRING', 'DATASOURCE', 'OAUTH_TOKEN', 'SSL_CA_PEM', 'SSL_CERT_PEM', 'SSL_KEY_PEM', 'SSL_KEY_PASSPHRASE', 'SSLROOTCERT_PEM', 'SSLCERT_PEM', 'SSLKEY_PEM', ]) /** * The user info of a URL. ClickHouse 26.3 hides only the password of a MongoDB * `URI` and stores an HTTP `URL` in clear; drift hides the user info of every * URL on both sides. */ const URL_USERINFO = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/?#]+@/ const URL_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\// /** * Query parameters whose value is a secret, as ClickHouse after 26.3 hides * them in a URL: the name, percent-decoded and in lower case, contains one of * these words, or is `sig`. ClickHouse 26.3 stores them in clear. */ const SECRET_PARAMETER_WORDS = ['secret', 'password', 'passwd', 'token', 'credential', 'signature', 'key'] /** The C escapes ClickHouse reads in a quoted string, by the letter after the backslash. */ const QUOTED_STRING_ESCAPES: Record = { a: '\x07', b: '\b', e: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', 0: '\0', } /** ClickHouse drops the backslash before a control character (code 0-31). */ const LAST_CONTROL_CHAR = 31 /** The characters ClickHouse escapes when it writes a quoted string, and the letter it writes after the backslash. */ const QUOTED_STRING_LETTERS: Record = { '\b': 'b', '\f': 'f', '\n': 'n', '\r': 'r', '\t': 't', '\0': '0', '\\': '\\', "'": "'", } /** The two statements `compareDictionaryShape` formats, and the live `SOURCE` body it compares. */ export interface DictionarySqlQueries { /** The schema's statement, with `SOURCE(NULL())` and no comment. */ expected: string /** The live statement, with `SOURCE(NULL())` and no comment. */ actual: string actualSource: string } /** A `SOURCE` key and its value: a literal, or a group of pairs in parentheses. */ interface SourcePair { key: string value: string | SourcePair[] } /** * The dictionary statements `compareDictionaryShape` formats, or undefined when * the live statement has no single top-level `SOURCE` or can't be read whole. * Then nothing of it reaches the formatter, which logs its input in * `system.query_log`, and the dictionary is not compared. */ export function collectDictionarySqlQueries( expected: DictionaryDefinition, actual: ActualDictionaryShape ): DictionarySqlQueries | undefined { const actualSource = parseSourceFromCreateDictionaryQuery(actual.createQuery) const actualQuery = replaceSourceInCreateDictionaryQuery(actual.createQuery, 'NULL()') if (actualSource === undefined || actualQuery === undefined) return undefined const { comment: _comment, ...definition } = expected return { expected: renderDictionarySQL({ ...definition, source: 'NULL()' }).replace(/;$/, ''), actual: withoutComment(actualQuery), actualSource, } } /** * Compares a dictionary with the live one, clause by clause. `queries` is what * `collectDictionarySqlQueries` returned for the pair. * * The attributes, primary key and `RANGE` (together the structure), `LAYOUT`, * `LIFETIME` and `SETTINGS` are compared as ClickHouse's formatter renders * them, as view queries are: when either statement can't be formatted, they * are not compared. Both statements reach the formatter with `SOURCE(NULL())`, * because the formatter shows secrets and logs its input in `system.query_log`. * * `SOURCE` is compared locally, with its keys in any order. Both sides are * rendered as ClickHouse stores a source, with secret values replaced by * `[HIDDEN]`, so `expected` never shows a schema secret and a change to a * secret alone is not drift. `SOURCE` is not compared when ClickHouse hid a * value that drift does not hide, or when a value is a function call, which * ClickHouse stores evaluated. When the live `SOURCE` can't be parsed, the * dictionary is not compared. */ export function compareDictionaryShape( expected: DictionaryDefinition, queries: DictionarySqlQueries | undefined, canonicalizer?: SqlCanonicalizer ): ObjectDriftDetail[] { const object = `${expected.database}.${expected.name}` if (queries === undefined) { debug('drift', `${object}: live SOURCE not parsed, dictionary not compared`) return [] } const { actualSource } = queries const drift: ObjectDriftDetail[] = [] const expectedSource = normalizeDictionarySource(expected.source) const actualSourceShape = normalizeDictionarySource(actualSource) const unhiddenMasks = normalizeDictionarySource(actualSource.replaceAll('[HIDDEN]', 'x')) if (!expectedSource || !actualSourceShape) { debug('drift', `${object}: SOURCE not compared, it holds a function call or another shape`) } else if (actualSourceShape.sorted !== unhiddenMasks?.sorted) { debug('drift', `${object}: SOURCE not compared, ClickHouse hid a value drift does not hide`) } else if (expectedSource.sorted !== actualSourceShape.sorted) { drift.push({ code: 'source_mismatch', object, expected: expectedSource.text, actual: actualSourceShape.text }) } const expectedFormatted = canonicalizer?.query(queries.expected) const actualFormatted = canonicalizer?.query(queries.actual) if (!expectedFormatted || !actualFormatted) { debug('drift', `${object}: dictionary clauses not compared, the server could not format them`) return drift } for (const [code, read] of DICTIONARY_CLAUSES) { const expectedClause = read(expectedFormatted) const actualClause = read(actualFormatted) if (expectedClause !== actualClause) drift.push({ code, object, expected: expectedClause, actual: actualClause }) } return drift } function dictionaryStructure(query: string): string { const attributes = parseAttributeListTextFromCreateDictionaryQuery(query) ?? '' const primaryKey = parseDictionaryPrimaryKeyFromCreateDictionaryQuery(query).join(', ') const range = parseDictionaryRangeFromCreateDictionaryQuery(query) return `(${attributes}) PRIMARY KEY ${primaryKey}${range ? ` RANGE(MIN ${range.min} MAX ${range.max})` : ''}` } /** Sorted by name: the snapshot sorts dictionary settings, ClickHouse keeps them as written. */ function dictionarySettings(query: string): string { const settings = parseDictionarySettingsFromCreateDictionaryQuery(query) ?? {} return Object.keys(settings) .sort(compareCodePoints) .map((key) => { const value = settings[key] ?? '' return `${key} = ${typeof value === 'string' ? stringLiteral(value) : value}` }) .join(', ') } /** * A dictionary `SOURCE` body as ClickHouse stores it (`text`): keys and the * source name in upper case, strings quoted with backslashes, and secret values * replaced by `[HIDDEN]`. `sorted` is the same with the pairs of each group in * sorted order, for comparing: ClickHouse keeps the order as written. * Undefined when the source is not a list of `KEY value` pairs, or a value is a * function call. */ function normalizeDictionarySource(source: string): { text: string; sorted: string } | undefined { const tokens = tokenizeSQL(source).filter((token) => !isTrivia(token)) const parsed = parseSourcePairs(source, tokens, 0) if (!parsed || parsed.end !== tokens.length) return undefined return { text: renderSourcePairs(parsed.pairs, false), sorted: renderSourcePairs(parsed.pairs, true) } } /** The pairs from `tokens[start]` up to the `)` that closes their group, or the end. */ function parseSourcePairs( source: string, tokens: SQLToken[], start: number ): { pairs: SourcePair[]; end: number } | undefined { const pairs: SourcePair[] = [] let i = start while (i < tokens.length && tokens[i]?.text !== ')') { const keyToken = tokens[i] const valueToken = tokens[i + 1] if (keyToken?.kind !== 'identifier' || !valueToken || valueToken.text === ')') return undefined const key = keyToken.text.toUpperCase() if (valueToken.text === '(') { const closeAt = findMatchingParen(source, valueToken.start) const close = tokens.findIndex((token) => token.start === closeAt) if (close === -1) return undefined if (SECRET_SOURCE_KEYS.has(key)) { pairs.push({ key, value: "('[HIDDEN]')" }) } else { const group = parseSourcePairs(source, tokens, i + 2) if (!group || group.end !== close) return undefined pairs.push({ key, value: group.pairs }) } i = close + 1 continue } // A signed number, such as `PRIORITY -1`, stored without the space. const signed = (valueToken.text === '-' || valueToken.text === '+') && tokens[i + 2]?.kind === 'number' const valueEnd = signed ? i + 2 : i + 1 // A function call, such as `DB currentDatabase()`: ClickHouse stores its result. if (tokens[valueEnd + 1]?.text === '(') return undefined const value = signed ? `${valueToken.text === '-' ? '-' : ''}${tokens[i + 2]?.text ?? ''}` : sourceValueText(valueToken) pairs.push({ key, value: SECRET_SOURCE_KEYS.has(key) ? HIDDEN_SECRET : value }) i = valueEnd + 1 } return { pairs, end: i } } /** `NAME(` for the source name, `KEY (` for a nested group, as ClickHouse prints them. */ function renderSourcePairs(pairs: SourcePair[], sorted: boolean, nested = false): string { const rendered = pairs.map(({ key, value }) => typeof value === 'string' ? `${key} ${value}` : `${key}${nested ? ' ' : ''}(${renderSourcePairs(value, sorted, true)})` ) return (sorted ? rendered.sort(compareCodePoints) : rendered).join(' ') } function sourceValueText(token: SQLToken): string { if (token.kind !== 'string' || !token.terminated) return token.text const value = token.text.startsWith("'") ? readQuotedString(token.text) : stringLiteralValue(token) return value === undefined ? token.text : writeQuotedString(maskUrlCredentials(value)) } /** * The value of a `'...'` literal, decoded as ClickHouse reads it: `\n`, `\t` * and the other C escapes, `\xHH`, and a doubled quote. A backslash before a * character that needs no escape stays, so `'a\%'` is `a\%`. */ function readQuotedString(text: string): string { const body = text.slice(1, -1) let out = '' for (let i = 0; i < body.length; i++) { const char = body[i] ?? '' if (char === "'" && body[i + 1] === "'") { out += "'" i += 1 } else if (char !== '\\' || i + 1 === body.length) { out += char } else if (body[i + 1] === 'x' && /^[0-9a-fA-F]{2}$/.test(body.slice(i + 2, i + 4))) { out += String.fromCharCode(Number.parseInt(body.slice(i + 2, i + 4), 16)) i += 3 } else { const next = body[i + 1] ?? '' const decoded = QUOTED_STRING_ESCAPES[next] ?? next const kept = !'\\\'"`/='.includes(decoded) && decoded.charCodeAt(0) > LAST_CONTROL_CHAR // `\N` reads as nothing. if (next !== 'N') out += kept ? `\\${decoded}` : decoded i += 1 } } return out } /** A `'...'` literal as ClickHouse writes it. */ function writeQuotedString(value: string): string { return `'${value.replace(/[\b\f\n\r\t\0\\']/g, (char) => `\\${QUOTED_STRING_LETTERS[char] ?? char}`)}'` } /** A URL with its user info and its secret query parameter values replaced by `[HIDDEN]`. */ function maskUrlCredentials(value: string): string { if (!URL_SCHEME.test(value)) return value const url = value.replace(URL_USERINFO, '$1[HIDDEN]@') const question = url.indexOf('?') if (question === -1) return url const parameters = url .slice(question + 1) .split('&') .map((parameter) => { const equals = parameter.indexOf('=') if (equals === -1 || !isSecretParameterName(parameter.slice(0, equals))) return parameter return `${parameter.slice(0, equals)}=[HIDDEN]` }) return `${url.slice(0, question + 1)}${parameters.join('&')}` } function isSecretParameterName(rawName: string): boolean { const name = rawName .replace(/\+/g, ' ') .replace(/%([0-9a-fA-F]{2})/g, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16))) .toLowerCase() return name === 'sig' || SECRET_PARAMETER_WORDS.some((word) => name.includes(word)) } /** The statement without its trailing `COMMENT '...'`: its text could look like a clause to the parsers. */ function withoutComment(query: string): string { const tokens = tokenizeSQL(query).filter((token) => !isTrivia(token)) const keyword = tokens.at(-2) const comment = tokens.at(-1) const hasComment = keyword?.kind === 'identifier' && keyword.text.toUpperCase() === 'COMMENT' && comment?.kind === 'string' return hasComment ? query.slice(0, keyword.start).trimEnd() : query }