import { clickhouseType } from './clickhouse-type.js' import type { ChxConfigFn, ChxConfigInput, ChxResolvedConfig, ChxUserClickHouseConfig, ChxUserConfig, ColumnInput, DictionaryDefinition, KafkaTableInput, KeylessTableInput, MaterializedViewDefinition, SchemaDefinition, TableColumns, TableDefinition, TableInput, ValidationIssue, ViewDefinition, } from './model-types.js' import { DEFAULT_INDEX_GRANULARITY } from './table-settings.js' export * from './model-types.js' export class ChxValidationError extends Error { readonly issues: ValidationIssue[] constructor(issues: ValidationIssue[]) { super( `Schema validation failed with ${issues.length} issue${issues.length === 1 ? '' : 's'}` ) this.name = 'ChxValidationError' this.issues = issues } } export function defineConfig(config: T): T export function defineConfig(config: ChxConfigFn): ChxConfigFn export function defineConfig(config: ChxConfigInput): ChxConfigInput { return config } // A cluster name is interpolated into `ON CLUSTER ''`, so constrain it to // the characters legal in a `remote_servers` key (an XML element name: letters, // digits, `_`, `-`, `.`) or a `{macro}` — injection-safe inside the single // quotes, while still failing fast on typos like quotes or whitespace. const CLUSTER_NAME_PATTERN = /^([A-Za-z_][A-Za-z0-9_.-]*|\{[A-Za-z_][A-Za-z0-9_]*\})$/ function assertValidClusterName(name: string): string { if (!CLUSTER_NAME_PATTERN.test(name)) { throw new Error( `Invalid clickhouse.cluster "${name}". Expected a cluster name (e.g. "my_cluster", "prod-eu-1") or a macro (e.g. "{cluster}").`, ) } return name } export function resolveConfig(config: ChxUserConfig): ChxResolvedConfig { const outDir = config.outDir ?? './chkit' const migrationsDir = config.migrationsDir ?? joinPath(outDir, 'migrations') const metaDir = config.metaDir ?? joinPath(outDir, 'meta') const schemaGlobs = config.schema === undefined ? [] : Array.isArray(config.schema) ? config.schema : [config.schema] if (config.entry !== undefined && schemaGlobs.length > 0) { throw new Error('Config fields "entry" and "schema" are mutually exclusive. Use one project entry module or schema globs, not both.') } return { // In entry mode the entry module is the only schema source: its exported // definitions are collected exactly like any other schema file. schema: config.entry !== undefined ? [config.entry] : schemaGlobs, entry: config.entry, outDir, migrationsDir, metaDir, plugins: config.plugins ?? [], check: { failOnPending: config.check?.failOnPending ?? true, failOnChecksumMismatch: config.check?.failOnChecksumMismatch ?? true, failOnDrift: config.check?.failOnDrift ?? true, failOnExtraObjects: config.check?.failOnExtraObjects ?? false, }, safety: { allowDestructive: config.safety?.allowDestructive ?? false, }, clickhouse: config.clickhouse ? { url: config.clickhouse.url, username: config.clickhouse.username ?? 'default', password: config.clickhouse.password ?? '', database: config.clickhouse.database ?? 'default', secure: resolveSecure(config.clickhouse), cluster: config.clickhouse.cluster ? assertValidClusterName(config.clickhouse.cluster) : undefined, indexGranularity: assertValidIndexGranularity(config.clickhouse.indexGranularity), } : undefined, } } /** The `index_granularity` chkit gives a MergeTree table that does not declare it. */ export function configuredIndexGranularity(config: { clickhouse?: { indexGranularity?: number } }): number { return config.clickhouse?.indexGranularity ?? DEFAULT_INDEX_GRANULARITY } function assertValidIndexGranularity(value: number | undefined): number { if (value === undefined) return DEFAULT_INDEX_GRANULARITY if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { throw new Error(`Invalid clickhouse.indexGranularity ${JSON.stringify(value)}. Expected a positive integer, the server's MergeTree index_granularity default (8192 unless the server configures another).`) } return value } // The client takes the protocol, and without a port the scheme's default port, // from the URL, so `secure` can only confirm the scheme. A contradicting value is // an error instead of a silent downgrade to plain HTTP or an ignored setting. function resolveSecure(clickhouse: ChxUserClickHouseConfig): boolean { const scheme = /^(https?):/i.exec(clickhouse.url)?.[1]?.toLowerCase() if (scheme === undefined) return clickhouse.secure ?? false const fromUrl = scheme === 'https' if (clickhouse.secure !== undefined && clickhouse.secure !== fromUrl) { throw new Error( `clickhouse.secure is ${clickhouse.secure} but clickhouse.url uses ${scheme}://. The URL scheme sets the protocol: remove secure or change the URL to ${clickhouse.secure ? 'https' : 'http'}://.`, ) } return fromUrl } // POSIX `path.join` that keeps a leading `//` (a Windows UNC root), written out // because importing `node:path` here breaks browser bundles of `@chkit/core`. function joinPath(dir: string, name: string): string { const root = /^\/\/[^/]/.test(dir) ? '//' : dir.startsWith('/') ? '/' : '' const absolute = root !== '' const segments: string[] = [] for (const segment of `${dir}/${name}`.split('/')) { if (segment === '' || segment === '.') continue if (segment !== '..') segments.push(segment) else if (segments.length > 0 && segments.at(-1) !== '..') segments.pop() else if (!absolute) segments.push(segment) } return `${root}${segments.join('/')}` } /** Defines a table. A column's `t` type renders as its ClickHouse type string. */ export function table(input: KafkaTableInput): TableDefinition & TableColumns export function table(input: KeylessTableInput): TableDefinition & TableColumns export function table(input: TableInput): TableDefinition & TableColumns export function table(input: KafkaTableInput | KeylessTableInput | TableInput): TableDefinition & TableColumns { const definition: TableDefinition = { ...input, columns: input.columns.map((column) => ({ ...column, type: typeof column.type === 'string' ? column.type : clickhouseType(column.type), })), primaryKey: input.primaryKey ?? input.orderBy ?? [], orderBy: input.orderBy ?? [], kind: 'table', } const column = (name: string) => { const type = input.columns.find((candidate) => candidate.name === name)?.type if (type === undefined || typeof type === 'string') { throw new Error(`${input.database}.${input.name} has no column "${name}" with a t type`) } return type } return Object.defineProperty(definition, 'column', { value: column }) as TableDefinition & TableColumns } export function view(input: Omit): ViewDefinition { return { ...input, kind: 'view' } } export function materializedView( input: Omit ): MaterializedViewDefinition { return { ...input, kind: 'materialized_view' } } export function dictionary( input: Omit ): DictionaryDefinition { return { ...input, kind: 'dictionary' } } export function schema(...definitions: SchemaDefinition[]): SchemaDefinition[] { return definitions } export function isSchemaDefinition(value: unknown): value is SchemaDefinition { if (!value || typeof value !== 'object') return false const kind = (value as { kind?: string }).kind return ( kind === 'table' || kind === 'view' || kind === 'materialized_view' || kind === 'dictionary' ) }