import { canonicalizeDefinitions, isIndexProjection, isRawCodec, parseColumnDefault, type ColumnCodec, type ColumnCodecSpec, type ColumnDefaultValue, type ColumnDefinition, type DictionaryAttribute, type DictionaryDefinition, type MaterializedViewDefinition, type MaterializedViewRefresh, type ProjectionDefinition, type SchemaDefinition, type SkipIndexDefinition, type TableConstraintDefinition, type TableDefinition, type ViewDefinition, compareCodePoints, READONLY_MERGE_TREE_SETTINGS, supportsSortOrder, } from '@chkit/core' export interface RenderSchemaOptions { /** `database.name` of the tables ObsessionDB stores as `Shared*`. */ sharedTables?: ReadonlySet /** Comment lines written under the import, without the `// ` prefix. Defaults to pull's own header. */ header?: readonly string[] } const PULL_HEADER = ['Pulled from live ClickHouse metadata via chkit plugin pull schema'] const READONLY_SETTING_COMMENT = 'read-only: a change recreates the table (DROP + CREATE, or --cutover)' const OBSESSIONDB_STORAGE_POLICY_COMMENT = 'set by ObsessionDB on every Shared table; it cannot change' /** Why a pulled setting cannot be altered in place, written next to it (#466). */ function tableSettingComment(key: string, shared: boolean): string | undefined { if (READONLY_MERGE_TREE_SETTINGS.includes(key)) return READONLY_SETTING_COMMENT if (key === 'storage_policy' && shared) return OBSESSIONDB_STORAGE_POLICY_COMMENT return undefined } export function renderSchemaFile(definitions: SchemaDefinition[], options: RenderSchemaOptions = {}): string { const canonical = canonicalizeDefinitions(definitions) const declarationNames = new Map() const lines: string[] = [ renderImportStatement(canonical), '', // Every line terminator JavaScript knows starts a new comment line, so header text can never become code. ...(options.header ?? PULL_HEADER).flatMap((line) => line.split(/\r\n|[\r\n\u2028\u2029]/)).map((line) => (line ? `// ${line}` : '//')), '', ] const references: string[] = [] for (const definition of canonical) { const variableName = resolveTableVariableName(definition.database, definition.name, declarationNames) references.push(variableName) lines.push(...renderDefinition(definition, variableName, options)) lines.push('') } lines.push(`export default schema(${references.join(', ')})`) return `${lines.join('\n')}\n` } function renderImportStatement(canonical: SchemaDefinition[]): string { const hasTable = canonical.some((definition) => definition.kind === 'table') const hasView = canonical.some((definition) => definition.kind === 'view') const hasMaterializedView = canonical.some((definition) => definition.kind === 'materialized_view') const hasDictionary = canonical.some((definition) => definition.kind === 'dictionary') const hasRawCodec = canonical.some( (definition) => definition.kind === 'table' && definition.columns.some((column) => column.codec && codecContainsRaw(column.codec)) ) const imports = ['schema'] if (hasTable) imports.push('table') if (hasView) imports.push('view') if (hasMaterializedView) imports.push('materializedView') if (hasDictionary) imports.push('dictionary') if (hasRawCodec) imports.push('codec') return `import { ${imports.join(', ')} } from '@chkit/core'` } function renderDefinition(definition: SchemaDefinition, variableName: string, options: RenderSchemaOptions): string[] { switch (definition.kind) { case 'table': return renderTableDefinition(definition, variableName, options.sharedTables?.has(`${definition.database}.${definition.name}`) ?? false) case 'view': return renderViewDefinition(definition, variableName) case 'dictionary': return renderDictionaryDefinition(definition, variableName) default: return renderMaterializedViewDefinition(definition, variableName) } } function renderTableDefinition(definition: TableDefinition, variableName: string, shared: boolean): string[] { const lines = renderDeclarationHeader('table', variableName, definition.database, definition.name) lines.push(` engine: ${renderString(definition.engine)},`) lines.push(' columns: [') for (const column of definition.columns) { lines.push(` ${renderColumn(column)},`) } lines.push(' ],') // Distributed, Memory, Kafka and other engines without sort order take no keys. if (supportsSortOrder(definition.engine)) { lines.push(` primaryKey: ${renderStringArray(definition.primaryKey)},`) lines.push(` orderBy: ${renderStringArray(definition.orderBy)},`) } if (definition.uniqueKey && definition.uniqueKey.length > 0) { lines.push(` uniqueKey: ${renderStringArray(definition.uniqueKey)},`) } if (definition.partitionBy) { lines.push(` partitionBy: ${renderString(definition.partitionBy)},`) } if (definition.ttl) { lines.push(` ttl: ${renderString(definition.ttl)},`) } if (definition.settings && Object.keys(definition.settings).length > 0) { lines.push(...renderSettingsLines(definition.settings, ' ', (key) => tableSettingComment(key, shared))) } if (definition.indexes && definition.indexes.length > 0) { lines.push(...renderIndexLines(definition.indexes)) } if (definition.projections && definition.projections.length > 0) { lines.push(...renderProjectionLines(definition.projections)) } if (definition.constraints && definition.constraints.length > 0) { lines.push(...renderConstraintLines(definition.constraints)) } lines.push(...renderCommentLines(definition.comment)) lines.push('})') return lines } function renderViewDefinition(definition: ViewDefinition, variableName: string): string[] { const lines = renderDeclarationHeader('view', variableName, definition.database, definition.name) lines.push(` as: ${renderString(definition.as)},`) lines.push(...renderCommentLines(definition.comment)) lines.push('})') return lines } function renderMaterializedViewDefinition( definition: MaterializedViewDefinition, variableName: string ): string[] { const lines = renderDeclarationHeader('materializedView', variableName, definition.database, definition.name) lines.push(` to: { database: ${renderString(definition.to.database)}, name: ${renderString(definition.to.name)} },`) if (definition.refresh) { lines.push(...renderRefreshLines(definition.refresh)) } lines.push(` as: ${renderString(definition.as)},`) lines.push(...renderCommentLines(definition.comment)) lines.push('})') return lines } const HIDDEN_SECRET_NOTE = "// NOTE: password redacted by ClickHouse — replace '[HIDDEN]' with your credential (e.g. process.env.X)." function renderDictionaryDefinition(definition: DictionaryDefinition, variableName: string): string[] { const lines: string[] = [] if (definition.source.includes('[HIDDEN]')) { lines.push(HIDDEN_SECRET_NOTE) } lines.push(...renderDeclarationHeader('dictionary', variableName, definition.database, definition.name)) lines.push(' attributes: [') for (const attribute of definition.attributes) { lines.push(` ${renderDictionaryAttribute(attribute)},`) } lines.push(' ],') lines.push(` primaryKey: ${renderStringArray(definition.primaryKey)},`) lines.push(` source: ${renderString(definition.source)},`) lines.push(` layout: ${renderString(definition.layout)},`) lines.push(` lifetime: ${renderString(definition.lifetime)},`) if (definition.range) { lines.push( ` range: { min: ${renderString(definition.range.min)}, max: ${renderString(definition.range.max)} },` ) } if (definition.settings && Object.keys(definition.settings).length > 0) { lines.push(...renderSettingsLines(definition.settings, ' ')) } lines.push(...renderCommentLines(definition.comment)) lines.push('})') return lines } function renderCommentLines(comment: string | undefined): string[] { return comment ? [` comment: ${renderString(comment)},`] : [] } function renderDictionaryAttribute(attribute: DictionaryAttribute): string { const parts: string[] = [`name: ${renderString(attribute.name)}`, `type: ${renderString(attribute.type)}`] if (attribute.expression !== undefined) { parts.push(`expression: ${renderString(attribute.expression)}`) } else if (attribute.default !== undefined) { parts.push(`default: ${renderLiteral(attribute.default)}`) } if (attribute.hierarchical) parts.push('hierarchical: true') if (attribute.bidirectional) parts.push('bidirectional: true') if (attribute.injective) parts.push('injective: true') if (attribute.isObjectId) parts.push('isObjectId: true') return `{ ${parts.join(', ')} }` } function renderDeclarationHeader( factory: string, variableName: string, database: string, name: string ): string[] { return [ `const ${variableName} = ${factory}({`, ` database: ${renderString(database)},`, ` name: ${renderString(name)},`, ] } function renderColumn(column: ColumnDefinition): string { const parts: string[] = [ `name: ${renderString(column.name)}`, `type: ${renderString(column.type)}`, ] if (column.nullable) parts.push('nullable: true') if (column.defaultKind && column.defaultKind !== 'DEFAULT') parts.push(`defaultKind: ${renderString(column.defaultKind)}`) if (column.default !== undefined) parts.push(`default: ${renderColumnDefault(column.default)}`) if (column.comment) parts.push(`comment: ${renderString(column.comment)}`) if (column.codec) parts.push(`codec: ${renderCodecSource(column.codec)}`) return `{ ${parts.join(', ')} }` } /** Expression defaults (canonical `fn:` strings) are written in the documented `{ expression }` form. */ function renderColumnDefault(value: ColumnDefaultValue): string { const parsed = parseColumnDefault(value) if (parsed.kind === 'expression') return `{ expression: ${renderString(parsed.sql)} }` return renderLiteral(parsed.value) } function renderIndexLines(indexes: SkipIndexDefinition[]): string[] { const lines: string[] = [' indexes: ['] for (const index of indexes) { lines.push(` ${renderIndex(index)},`) } lines.push(' ],') return lines } function renderIndex(index: SkipIndexDefinition): string { const parts = [ `name: ${renderString(index.name)}`, `expression: ${renderString(index.expression)}`, `type: ${renderString(index.type)}`, ] switch (index.type) { case 'text': for (const field of ['tokenizer', 'preprocessor', 'postprocessor', 'supportPhraseSearch', 'dictionaryBlockSize', 'dictionaryBlockFrontcodingCompression', 'postingListBlockSize', 'postingListCodec'] as const) { const value = index[field] if (value !== undefined) parts.push(`${field}: ${typeof value === 'string' ? renderString(value) : value}`) } break case 'vector_similarity': for (const field of ['method', 'distanceFunction', 'dimensions', 'quantization', 'hnswMaxConnectionsPerLayer', 'hnswCandidateListSizeForConstruction'] as const) { const value = index[field] if (value !== undefined) parts.push(`${field}: ${typeof value === 'string' ? renderString(value) : value}`) } break case 'raw': parts.push(`rawType: ${renderString(index.rawType)}`) break case 'minmax': break case 'set': parts.push(`maxRows: ${index.maxRows}`) break case 'bloom_filter': if (index.falsePositiveRate !== undefined) { parts.push(`falsePositiveRate: ${index.falsePositiveRate}`) } break case 'tokenbf_v1': parts.push( `sizeBytes: ${index.sizeBytes}`, `hashFunctions: ${index.hashFunctions}`, `randomSeed: ${index.randomSeed}` ) break case 'ngrambf_v1': parts.push( `ngramSize: ${index.ngramSize}`, `sizeBytes: ${index.sizeBytes}`, `hashFunctions: ${index.hashFunctions}`, `randomSeed: ${index.randomSeed}` ) break } if (index.type !== 'text' && index.granularity !== undefined) parts.push(`granularity: ${index.granularity}`) return `{ ${parts.join(', ')} }` } function renderConstraintLines(constraints: TableConstraintDefinition[]): string[] { const lines: string[] = [' constraints: ['] for (const constraint of constraints) { const body = constraint.check !== undefined ? `check: ${renderString(constraint.check)}` : `assume: ${renderString(constraint.assume ?? '')}` lines.push(` { name: ${renderString(constraint.name)}, ${body} },`) } lines.push(' ],') return lines } function renderProjectionLines(projections: ProjectionDefinition[]): string[] { const lines: string[] = [' projections: ['] for (const projection of projections) { const fields = isIndexProjection(projection) ? `index: ${renderString(projection.index)}, type: ${renderString(projection.type)}` : `query: ${renderString(projection.query)}` lines.push(` { name: ${renderString(projection.name)}, ${fields} },`) } lines.push(' ],') return lines } function renderRefreshLines(refresh: MaterializedViewRefresh): string[] { const lines: string[] = [] lines.push(' refresh: {') if (refresh.every) lines.push(` every: ${renderString(refresh.every)},`) if (refresh.after) lines.push(` after: ${renderString(refresh.after)},`) if (refresh.offset) lines.push(` offset: ${renderString(refresh.offset)},`) if (refresh.randomize) lines.push(` randomize: ${renderString(refresh.randomize)},`) if (refresh.dependsOn && refresh.dependsOn.length > 0) { lines.push(' dependsOn: [') for (const dep of refresh.dependsOn) { lines.push(` { database: ${renderString(dep.database)}, name: ${renderString(dep.name)} },`) } lines.push(' ],') } if (refresh.settings && Object.keys(refresh.settings).length > 0) { lines.push(...renderSettingsLines(refresh.settings, ' ')) } if (refresh.append) lines.push(' append: true,') if (refresh.empty) lines.push(' empty: true,') lines.push(' },') return lines } function renderSettingsLines( settings: Record, indent: string, comment: (key: string) => string | undefined = () => undefined ): string[] { const lines: string[] = [`${indent}settings: {`] for (const key of Object.keys(settings).sort(compareCodePoints)) { const value = settings[key] if (value === undefined) continue const note = comment(key) lines.push(`${indent} ${renderKey(key)}: ${renderLiteral(value)},${note ? ` // ${note}` : ''}`) } lines.push(`${indent}},`) return lines } function resolveTableVariableName( database: string, name: string, counts: Map ): string { const base = sanitizeIdentifier(`${database}_${name}`) const current = counts.get(base) ?? 0 const next = current + 1 counts.set(base, next) return next === 1 ? base : `${base}_${next}` } function sanitizeIdentifier(value: string): string { const sanitized = value.replace(/[^a-zA-Z0-9_]/g, '_').replace(/_+/g, '_').replace(/^_+|_+$/g, '') if (sanitized.length === 0) return 'table_ref' if (/^[0-9]/.test(sanitized)) return `table_${sanitized}` return sanitized } function renderString(value: string): string { return JSON.stringify(value) } function renderStringArray(values: string[]): string { return `[${values.map((value) => renderString(value)).join(', ')}]` } function renderLiteral(value: string | number | boolean): string { if (typeof value === 'string') return renderString(value) return String(value) } function renderKey(value: string): string { if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(value)) return value return renderString(value) } function codecContainsRaw(spec: ColumnCodecSpec): boolean { const steps = Array.isArray(spec) ? spec : [spec] return steps.some((step) => isRawCodec(step)) } function renderCodecStepSource(step: ColumnCodec): string { if (isRawCodec(step)) return `codec.raw(${renderString(step.expression)})` const parts: string[] = [`kind: ${renderString(step.kind)}`] if (step.kind === 'ZSTD' || step.kind === 'LZ4HC') { if (step.level !== undefined) parts.push(`level: ${step.level}`) if (step.kind === 'ZSTD' && step.windowLog !== undefined) parts.push(`windowLog: ${step.windowLog}`) } else if (step.kind === 'Delta' || step.kind === 'DoubleDelta' || step.kind === 'Gorilla') { if (step.size !== undefined) parts.push(`size: ${step.size}`) } else if (step.kind === 'T64') { if (step.mode !== undefined) parts.push(`mode: ${renderString(step.mode)}`) } else if (step.kind === 'FPC') { if (step.level !== undefined) parts.push(`level: ${step.level}`) if (step.floatSize !== undefined) parts.push(`floatSize: ${step.floatSize}`) } return `{ ${parts.join(', ')} }` } function renderCodecSource(spec: ColumnCodecSpec): string { const steps = Array.isArray(spec) ? spec : [spec] const [first] = steps if (steps.length === 1 && first) return renderCodecStepSource(first) return `[${steps.map(renderCodecStepSource).join(', ')}]` }