@altimateai/altimate-core
Version:
Type-check your SQL. No database required.
1,128 lines (938 loc) • 36.6 kB
TypeScript
// ── altimate-core TypeScript type definitions ────────────────────────
// These interfaces mirror the JSON shapes returned by altimate-core.
// All field names are snake_case (Rust default serialization).
// ── Shared / Utility ──────────────────────────────────────────────────
export interface SourceLocation {
line: number
column: number
}
// ── Validation ────────────────────────────────────────────────────────
export type ErrorCode = 'E000' | 'E001' | 'E002' | 'E003' | 'E004' | 'E005' | 'E006' | 'E099'
export type ErrorKind =
| { type: 'SyntaxError' }
| { type: 'TableNotFound'; table: string }
| { type: 'ColumnNotFound'; table: string | null; column: string }
| { type: 'TypeMismatch'; expected: string; found: string }
| { type: 'AmbiguousColumn'; column: string; candidates: string[] }
| { type: 'InvalidJoin'; reason: string }
| { type: 'UnsupportedDialectFeature'; feature: string; dialect: string }
| { type: 'Other'; detail: string }
export type SuggestionKind =
| { type: 'DidYouMean'; name: string }
| { type: 'AddQualification'; qualified: string }
| { type: 'UseAlternative'; alternative: string }
export interface Suggestion {
kind: SuggestionKind
message: string
confidence: number
}
export interface ValidationError {
code: ErrorCode
kind: ErrorKind
message: string
location: SourceLocation | null
suggestions: Suggestion[]
}
export interface ValidationWarning {
code: string
message: string
location: SourceLocation | null
}
export type Complexity = 'low' | 'medium' | 'high'
export interface QueryMetadata {
tables_referenced: string[]
join_count: number
has_aggregation: boolean
has_subquery: boolean
complexity: Complexity
}
export interface ValidationResult {
valid: boolean
errors: ValidationError[]
warnings: ValidationWarning[]
metadata: QueryMetadata
}
// ── Explanation ───────────────────────────────────────────────────────
export type JoinKind =
| 'inner' | 'left' | 'right' | 'full' | 'cross'
| 'left_semi' | 'left_anti' | 'right_semi' | 'right_anti'
export interface SortKey {
column: string
direction: 'asc' | 'desc'
nulls_first: boolean
}
export type PlanOperation =
| { type: 'table_scan'; table: string; columns_read: string[]; filters: string[] }
| { type: 'join'; join_type: JoinKind; left: string; right: string; condition: string }
| { type: 'filter'; predicate: string }
| { type: 'aggregate'; group_by: string[]; functions: string[] }
| { type: 'sort'; order_by: SortKey[] }
| { type: 'limit'; limit?: number; offset?: number }
| { type: 'projection'; columns: string[] }
| { type: 'window'; function: string; partition_by: string[]; order_by: string[] }
| { type: 'subquery'; alias: string; inner_steps: PlanStep[] }
| { type: 'union'; all: boolean; branches: number }
| { type: 'distinct' }
| { type: 'empty_relation' }
export interface PlanStep {
step: number
operation: PlanOperation
notes?: string
}
export interface ColumnRef {
table: string
column: string
}
export type ColumnSource =
| { type: 'direct_ref'; table: string; column: string }
| { type: 'aggregation'; function: string }
| { type: 'expression'; expr: string }
| { type: 'window_function'; function: string }
| { type: 'literal'; value: string }
export interface OutputColumn {
alias: string
source: ColumnSource
}
export interface JoinEdge {
left_table: string
right_table: string
join_type: JoinKind
on_columns: [string, string][]
}
export interface QueryLineage {
tables: string[]
columns_read: ColumnRef[]
columns_output: OutputColumn[]
join_graph: JoinEdge[]
}
export type QueryComplexity = 'low' | 'moderate' | 'high' | 'extreme'
export type RiskSeverity = 'info' | 'warning' | 'critical'
export interface RiskFlag {
severity: RiskSeverity
flag: string
detail: string
}
export type SuggestionType =
| 'add_filter' | 'add_limit' | 'avoid_cross_join' | 'remove_select_star'
| 'use_specific_columns' | 'remove_redundant_distinct' | 'consider_index'
export type SuggestionPriority = 'low' | 'medium' | 'high'
export interface OptimizationSuggestion {
kind: SuggestionType
message: string
priority: SuggestionPriority
}
export interface CostSignals {
complexity: QueryComplexity
complexity_score: number
join_count: number
has_aggregation: boolean
has_subquery: boolean
has_window_function: boolean
has_limit: boolean
has_cross_join: boolean
uses_select_star: boolean
has_distinct: boolean
has_union: boolean
table_count: number
filter_count: number
unfiltered_scans: string[]
risk_flags: RiskFlag[]
}
export interface QueryExplanation {
summary: string
plan_steps: PlanStep[]
lineage: QueryLineage
cost_signals: CostSignals
suggestions: OptimizationSuggestion[]
}
export interface ValidationSummary {
error_count: number
warning_count: number
errors: ValidationError[]
warnings: ValidationWarning[]
}
export interface AnalysisMetadata {
dialect: string
plan_node_count: number
analysis_time_ms: number
}
export interface ExplanationResult {
valid: boolean
explanation?: QueryExplanation
validation: ValidationSummary
metadata: AnalysisMetadata
}
// ── Fix ───────────────────────────────────────────────────────────────
export type FixActionType =
| 'replace_table' | 'replace_column' | 'qualify_column'
| 'remove_alias' | 'add_alias' | 'use_alternative'
export interface FixAction {
action: FixActionType
original: string
replacement: string
confidence: number
explanation: string
location?: SourceLocation
}
export interface UnfixableError {
error: ValidationError
reason: string
}
export interface FixResult {
original_sql: string
fixed: boolean
fixed_sql: string
fixes_applied: FixAction[]
unfixable_errors: UnfixableError[]
post_fix_valid: boolean
iterations: number
fix_time_ms: number
}
// ── Policy / Guardrails ───────────────────────────────────────────────
export type PolicyCategory = 'cost_control' | 'data_protection' | 'query_patterns' | 'tag_rules' | 'custom'
export type ViolationSeverity = 'error' | 'warning' | 'info'
export type ViolationDetail =
| { type: 'blocked_column'; table: string; column: string }
| { type: 'blocked_table'; table: string }
| { type: 'exceeded_limit'; metric: string; limit: number; actual: number }
| { type: 'blocked_statement'; statement: string }
| { type: 'blocked_pattern'; pattern: string }
| { type: 'tag_violation'; tag: string; table: string; column: string }
| { type: 'custom_rule'; detail: string }
export interface PolicyViolation {
rule: string
category: PolicyCategory
severity: ViolationSeverity
message: string
remediation?: string
detail: ViolationDetail
}
export interface PolicyWarning {
rule: string
category: PolicyCategory
message: string
}
export interface AuditEntry {
timestamp: string
sql_hash: string
allowed: boolean
violation_count: number
warning_count: number
policies_checked: number
evaluation_time_ms: number
}
export interface PolicyResult {
allowed: boolean
violations: PolicyViolation[]
warnings: PolicyWarning[]
policies_evaluated: number
audit: AuditEntry
}
// ── Lint ──────────────────────────────────────────────────────────────
export type LintSeverity = 'error' | 'warning' | 'info'
export interface LintFinding {
code: string
rule: string
severity: LintSeverity
message: string
suggestion?: string
line?: number
column?: number
}
export interface LintResult {
sql: string
findings: LintFinding[]
error_count: number
warning_count: number
clean: boolean
}
// ── Safety ────────────────────────────────────────────────────────────
export type SafetyRule =
| 'multi_statement' | 'union_injection' | 'comment_injection' | 'transaction_escape'
| 'stacked_queries' | 'tautology_attack' | 'sleep_attack' | 'info_schema_probe'
| 'string_concat_predicate' | 'encoding_bypass'
export type SafetySeverity = 'low' | 'medium' | 'high' | 'critical'
export interface ThreatFinding {
rule: SafetyRule
severity: SafetySeverity
message: string
detail: string
location?: [number, number]
matched_pattern: string
}
export interface SafetyScanResult {
safe: boolean
threats: ThreatFinding[]
risk_score: number
statement_count: number
statement_types: string[]
}
// ── PII ───────────────────────────────────────────────────────────────
export type PiiClassification =
| 'Email' | 'Phone' | 'SSN' | 'Name' | 'Address'
| 'Financial' | 'Health' | 'DateOfBirth' | 'IPAddress'
| { Custom: string } | 'None'
export type PiiRiskLevel = 'None' | 'Low' | 'Medium' | 'High'
export interface PiiColumnResult {
table: string
column: string
classification: PiiClassification
confidence: number
detection_method: string
suggested_masking: string | null
}
export interface PiiReport {
columns: PiiColumnResult[]
pii_count: number
total_columns: number
risk_level: PiiRiskLevel
}
export interface PiiColumnAccess {
table: string
column: string
query_targets: string[]
classification: PiiClassification
suggested_masking: string | null
}
export interface PiiQueryResult {
accesses_pii: boolean
pii_columns: PiiColumnAccess[]
suggested_alternatives: string[]
risk_level: PiiRiskLevel
}
// ── Semantic ──────────────────────────────────────────────────────────
export type SemanticSeverity = 'error' | 'warning' | 'info'
export interface SemanticFinding {
rule: string
severity: SemanticSeverity
message: string
explanation: string
suggestion?: string
confidence: number
}
export interface SemanticResult {
valid: boolean
semantic_score: number
findings: SemanticFinding[]
passed_checks: string[]
validation_errors: string[]
}
// ── Equivalence ───────────────────────────────────────────────────────
export type DiffSeverity = 'structural' | 'semantic' | 'minor'
export interface EquivalenceDiff {
aspect: string
description: string
severity: DiffSeverity
}
export interface EquivalenceResult {
equivalent: boolean
confidence: number
differences: EquivalenceDiff[]
output_compatible: boolean
decidable: boolean
validation_errors: string[]
}
// ── Correction ────────────────────────────────────────────────────────
export type CorrectionStatus = 'already_valid' | 'fixed' | 'partial_fix' | 'unfixable'
export type IterationResult = 'fixed' | 'still_invalid' | 'new_errors' | 'skipped'
export interface CorrectionIteration {
iteration: number
input_sql: string
validation_errors: string[]
fix_applied?: string
fix_description?: string
result: IterationResult
}
export interface QualityScore {
syntax_valid: boolean
lint_score: number
safety_score: number
complexity_score: number
overall: number
}
export interface CorrectionResult {
status: CorrectionStatus
original_sql: string
corrected_sql?: string
iterations: CorrectionIteration[]
final_validation?: any
final_score: QualityScore
total_time_ms: number
}
// ── Evaluation / Observability ────────────────────────────────────────
export type Grade = 'A' | 'B' | 'C' | 'D' | 'F'
export interface QualityScorecard {
syntax: number
style: number
safety: number
complexity: number
overall: number
}
export interface EvalResult {
sql: string
scores: QualityScorecard
validation?: any
lint?: any
safety?: any
explain?: any
overall_grade: Grade
total_time_ms: number
}
// ── Polyglot ──────────────────────────────────────────────────────────
export interface TranspileResult {
original_sql: string
source_dialect: string
target_dialect: string
transpiled_sql: string[]
success: boolean
error?: string
}
export interface FormatResult {
original_sql: string
formatted_sql: string
dialect: string
success: boolean
error?: string
}
export interface ExtractResult {
tables: string[]
columns: string[]
functions: string[]
has_subqueries: boolean
has_aggregation: boolean
has_window_functions: boolean
node_count: number
}
export interface DiffEntry {
change_type: string
description: string
}
export interface CompareResult {
identical: boolean
diff_count: number
diffs: DiffEntry[]
}
export type StatementCategory = 'query' | 'dml' | 'ddl' | 'dcl' | 'tcl' | 'other'
export interface StatementInfo {
/** Statement type, e.g. "SELECT", "INSERT", "CREATE TABLE" */
statement_type: string
/** Broad category of the statement */
category: StatementCategory
}
export interface StatementTypesResult {
/** One entry per parsed statement */
statements: StatementInfo[]
/** Total number of statements found */
statement_count: number
/** Deduplicated statement types found, e.g. ["SELECT", "DELETE"] */
types: string[]
/** Deduplicated categories found, e.g. ["query", "dml"] */
categories: StatementCategory[]
}
// ── Completion ────────────────────────────────────────────────────────
export type CompletionKind = 'table' | 'column' | 'function' | 'keyword' | 'alias' | 'join_condition' | 'schema'
export interface CompletionItem {
label: string
kind: CompletionKind
detail: string
documentation?: string
score: number
}
export interface CompletionResult {
cursor_offset: number
context: string
items: CompletionItem[]
}
// ── Rewrite ───────────────────────────────────────────────────────────
export interface RewriteSuggestion {
rule: string
explanation: string
rewritten_sql: string
improvement: string
confidence: number
}
export interface IndexSuggestion {
table: string
columns: string[]
reason: string
ddl: string
}
export interface RewriteResult {
original_sql: string
suggestions: RewriteSuggestion[]
index_suggestions: IndexSuggestion[]
}
// ── Test Generation ───────────────────────────────────────────────────
export type TestExpectation = 'returns_rows' | 'returns_empty' | 'should_error' | { row_count: number }
export interface TestInput {
column: string
value: string
data_type: string
}
export interface TestCase {
name: string
category: string
description: string
inputs: TestInput[]
expected: TestExpectation
}
export interface TestGenResult {
sql: string
test_cases: TestCase[]
columns_analyzed: string[]
tables_referenced: string[]
}
// ── Migration ─────────────────────────────────────────────────────────
export type MigrationRisk = 'safe' | 'caution' | 'dangerous' | 'destructive'
export interface MigrationFinding {
risk: MigrationRisk
operation: string
message: string
mitigation?: string
rollback_sql?: string
}
export interface MigrationResult {
sql: string
overall_risk: MigrationRisk
findings: MigrationFinding[]
safe: boolean
rollback_sql?: string
}
// ── dbt ───────────────────────────────────────────────────────────────
export interface DbtSourceRef {
source_name: string
table_name: string
}
export interface DbtModel {
name: string
path: string
sql: string
raw_sql: string
materialization?: string
description?: string
refs: string[]
sources: DbtSourceRef[]
}
export interface DbtProject {
name: string
models: DbtModel[]
build_order: string[]
warnings: string[]
}
// ── Lineage ───────────────────────────────────────────────────────────
export type LineageType = 'direct' | 'indirect'
export type LensClassification = 'Original' | 'Alias' | 'Transformation' | 'Not sure' | 'Non select'
export interface LensStep {
expression: string
step_type: string
}
export interface LineageEntry {
source: string
target: string
lineage_type: LineageType
lens_type: LensClassification
lens_code: LensStep[]
}
export interface CompleteLineageResult {
column_dict: Record<string, string[]>
column_lineage: LineageEntry[]
source_tables: string[]
errors: string[]
default_database: string | null
default_schema: string | null
}
export interface LineageColumnRef {
table: string
column: string
}
export interface LineageEdge {
source: LineageColumnRef
target: LineageColumnRef
transform_type: string
}
export interface LineageQueryInfo {
source_tables: string[]
target_tables: string[]
edges: LineageEdge[]
output_columns: string[]
}
export interface ImpactEntry {
source: LineageColumnRef
affected: LineageColumnRef[]
}
export interface LineageResult {
queries: LineageQueryInfo[]
dependency_order: string[]
impact_map: ImpactEntry[]
}
// ── Context ───────────────────────────────────────────────────────────
export type DisclosureLevel = 'fingerprint' | 'table_list' | 'column_names' | 'full_relevant' | 'full'
export interface ContextResult {
compressed_schema: string
level_used: DisclosureLevel
estimated_tokens: number
tables_included: number
tables_total: number
compression_ratio: number
fingerprint: string
}
// ── Schema Diff ───────────────────────────────────────────────────────
export type SchemaChange =
| { type: 'table_added'; table: string }
| { type: 'table_removed'; table: string }
| { type: 'column_added'; table: string; column: string; data_type: string }
| { type: 'column_removed'; table: string; column: string }
| { type: 'column_type_changed'; table: string; column: string; old_type: string; new_type: string }
| { type: 'nullability_changed'; table: string; column: string; old_nullable: boolean; new_nullable: boolean }
export interface SchemaDiff {
changes: SchemaChange[]
has_breaking_changes: boolean
summary: string
}
// ── Schema Definition (pruned) ────────────────────────────────────────
export interface McvEntry {
value: string
frequency: number
}
export interface ColumnStatistics {
n_distinct?: number
null_fraction?: number
min_value?: string
max_value?: string
most_common_values?: McvEntry[]
avg_bytes?: number
compression_ratio?: number
}
export interface ForeignKeyRef {
table: string
columns: string[]
}
export interface ForeignKeyDef {
columns: string[]
references: ForeignKeyRef
}
export interface TableStatistics {
row_count?: number
avg_row_bytes?: number
partitioned?: boolean
partition_columns?: string[]
correlated_columns?: string[][]
partition_count?: number
total_bytes?: number
historical_scan_median?: number
}
export interface ColumnDef {
name: string
type: string
nullable: boolean
description?: string
tags?: string[]
synonyms?: string[]
statistics?: ColumnStatistics
}
export interface TableDef {
description?: string
database?: string
schema?: string
columns: ColumnDef[]
primary_key?: string[]
foreign_keys?: ForeignKeyDef[]
statistics?: TableStatistics
clustering_keys?: string[]
}
export interface SchemaDefinition {
version: string
dialect: string
database: string | null
schema_name: string | null
tables: Record<string, TableDef>
glossary?: any
}
// ── Introspection ─────────────────────────────────────────────────────
export interface IntrospectionSql {
database_type: string
columns_query: string
primary_keys_query: string
foreign_keys_query: string
}
// ── Glossary ──────────────────────────────────────────────────────────
export interface ColumnReference {
table: string
column: string
}
export type MatchSource = 'ExactTerm' | 'Synonym' | 'Description' | 'FuzzyName' | 'ColumnSynonym'
export interface GlossaryMatch {
term: string
matched_column: ColumnReference | null
matched_definition: string | null
confidence: number
source: MatchSource
}
/**
* Cooperative DataParity state machine — emits SQL tasks, never touches databases.
*
* Create with a JSON spec, then loop: `start()` → execute SQL → `step(responses)` → repeat.
*
* The session holds mutable state between calls and must not be shared across threads.
*/
export declare class DataParitySession {
/**
* Create a new DataParity session from a JSON spec string.
*
* The spec must conform to `SessionSpec`:
* ```json
* {
* "table1": { "table": "source_table", "database": "db", "schema": "schema" },
* "table2": { "table": "target_table" },
* "dialect1": "Postgres",
* "dialect2": "Snowflake",
* "config": {
* "algorithm": "auto",
* "key_columns": ["id"],
* "extra_columns": ["name", "email"],
* "numeric_tolerance": null,
* "timestamp_tolerance_ms": null
* }
* }
* ```
*/
constructor(specJson: string)
/**
* Begin the comparison. Returns the first action as a JSON string.
*
* Returns one of:
* - `{ "type": "ExecuteSql", "tasks": [{ "id", "table_side", "sql", "expected_shape" }] }`
* - `{ "type": "Done", "outcome": { ... } }`
* - `{ "type": "Error", "message": "..." }`
*/
start(): string
/**
* Process SQL responses and return the next action as a JSON string.
*
* `responses_json` must be a JSON array of `SqlResponse` objects:
* ```json
* [
* { "id": "fp1_1", "rows": [["42", "abc123"]] },
* { "id": "fp2_1", "rows": [["42", "abc123"]] }
* ]
* ```
*
* Each element of `rows` is an array of nullable string values (one per column).
*/
step(responsesJson: string): string
}
export type ReladiffSessionNode = DataParitySession
/**
* Schema definition for SQL validation.
*
* Load from YAML, JSON, file, or DDL. Pass to validation functions.
*/
export declare class Schema {
/** Load schema from a YAML string. */
static fromYaml(yamlStr: string): Schema
/** Load schema from a JSON string. */
static fromJson(jsonStr: string): Schema
/** Load schema from a YAML or JSON file (auto-detected by extension). */
static fromFile(path: string): Schema
/** Load schema from a YAML file. */
static fromYamlFile(path: string): Schema
/** Parse DDL statements into a schema. */
static fromDdl(ddl: string, dialect?: string | undefined | null): Schema
/** Return all table names in the schema. */
tableNames(): Array<string>
/** Return column names for a specific table, or null if table not found. */
columnNames(table: string): Array<string> | null
/** Serialize the schema to a JSON object. */
toJson(): SchemaDefinition
/** Serialize the schema to a JSON string. */
toString(): string
/** Number of tables in the schema. */
get length(): number
}
/** Analyze migration safety (data loss, type narrowing, missing defaults). */
export declare function analyzeMigration(sql: string, schema: Schema): MigrationResult
/** Analyze SQL for anti-pattern tags. */
export declare function analyzeTags(sql: string, dialect: string, skipTags?: Array<string> | undefined | null): any
/**
* Check two SQL queries for semantic equivalence.
*
* `dialect` is an optional parsing-dialect hint (e.g. `"duckdb"`, `"snowflake"`,
* `"bigquery"`, `"postgres"`) that overrides the dialect declared on the schema.
* Pass it when comparing compiled warehouse SQL whose schema carries no dialect, so
* dialect-specific syntax parses and the pair is decidable instead of abstaining.
*/
export declare function checkEquivalence(sqlA: string, sqlB: string, schema: Schema, dialect?: string | undefined | null): Promise<EquivalenceResult>
/** Check SQL against policy guardrails. `policyJson` is a JSON string of PolicyConfig. */
export declare function checkPolicy(sql: string, schema: Schema, policyJson: string): Promise<PolicyResult>
/** Check if a query accesses PII columns. */
export declare function checkQueryPii(sql: string, schema: Schema): PiiQueryResult
/** Run semantic validation rules (cartesian products, wrong JOINs, NULL misuse). */
export declare function checkSemantics(sql: string, schema: Schema): Promise<SemanticResult>
/** Classify schema columns for PII exposure. */
export declare function classifyPii(schema: Schema): PiiReport
/**
* Compute column-level lineage for a SQL query.
*
* Returns an object with `column_dict` (output->sources mapping),
* `column_lineage` (detailed edge list), `tier`, and `depth`.
*
* Pass `defaultDatabase` and `defaultSchema` to qualify unqualified table
* references (important for Snowflake lineage matching).
*
* The `depth` parameter controls how much detail is returned:
* - `"basic"`: direct source→target edges only
* - `"deep"`: includes transformation metadata
* - `"full"` (default): everything including indirect edges
*/
export declare function columnLineage(sql: string, dialect?: string | undefined | null, schema?: Schema | undefined | null, defaultDatabase?: string | undefined | null, defaultSchema?: string | undefined | null, depth?: string | undefined | null): CompleteLineageResult
/** Compare two SQL queries structurally. */
export declare function compareQueries(leftSql: string, rightSql: string, dialect?: string | undefined | null): CompareResult
/** SQL completion engine: suggest tables, columns, functions, keywords at cursor position. */
export declare function complete(sql: string, cursorPos: number, schema: Schema): CompletionResult
/** Iterative correction protocol: propose-verify-refine loop. */
export declare function correct(sql: string, schema: Schema): Promise<CorrectionResult>
/** Diff two model versions' configs (the `*_change` rules, e.g. materialization flip). */
export declare function dbtConfigDiff(baseSql: string, headSql: string): string
/**
* dbt config/Jinja lint over a RAW model (parses `{{ config() }}` via minijinja).
* Returns JSON array of LintFindings (DBT001 incremental-no-guard, DBT002
* incremental-no-unique-key, DBT003 microbatch-lookahead, DBT004 contract, DBT005 var-no-default).
*/
export declare function dbtConfigLint(sql: string): string
/**
* Compute diff-aware column lineage between two SQL queries.
*
* Returns an object with `added_columns`, `removed_columns`,
* `modified_columns`, `affected_downstream`, `before`, and `after`.
*/
export declare function diffLineage(beforeSql: string, afterSql: string, dialect?: string | undefined | null, schema?: Schema | undefined | null, defaultDatabase?: string | undefined | null, defaultSchema?: string | undefined | null, depth?: string | undefined | null): DiffLineageResult
/** Diff two schemas with breaking change detection. */
export declare function diffSchemas(oldSchema: Schema, newSchema: Schema): SchemaDiff
/** SQL quality scoring and grading (A-F scale). */
export declare function evaluate(sql: string, schema: Schema): Promise<EvalResult>
/** Explain a SQL query: plan steps, column lineage, cost signals. */
export declare function explain(sql: string, schema: Schema): Promise<ExplanationResult>
/** Export schema as CREATE TABLE DDL statements. */
export declare function exportDdl(schema: Schema): string
/**
* Extract a model's grain key (final-SELECT GROUP BY + dedup PARTITION BY) from
* its compiled SQL, for grain-vs-declared-PK mismatch detection in PR review.
* Returns JSON: `{ "group_by": [...], "dedup_partition": [...] }`.
*/
export declare function extractGrain(sql: string): string
/** Extract metadata (tables, columns, functions) from SQL. */
export declare function extractMetadata(sql: string, dialect?: string | undefined | null): ExtractResult
/** Extract the output column names from a SQL SELECT list. */
export declare function extractOutputColumns(sql: string, dialect?: string | undefined | null): string[]
/**
* Per-upstream WHERE-filter columns of a model's SQL, for cross-model sibling
* filter-consistency. Returns JSON `{ "<upstream_table>": ["<filter col>", …] }`.
*/
export declare function extractSourceFilters(sql: string): string
/** Auto-fix SQL errors using fuzzy matching and iterative re-validation. */
export declare function fix(sql: string, schema: Schema, maxIterations?: number | undefined | null): Promise<FixResult>
/** Flush pending telemetry and shut down the background worker. */
export declare function flushSdk(): void
/** Format / pretty-print SQL for a dialect. */
export declare function formatSql(sql: string, dialect?: string | undefined | null): FormatResult
/** Generate test cases for a SQL query (boundary values, NULLs, edge cases). */
export declare function generateTests(sql: string, schema: Schema): TestGenResult
/**
* Classify the statement type of each SQL statement using full AST parsing.
*
* Unlike simple first-keyword detection, this parses a real AST and correctly
* handles CTEs (`WITH … SELECT` → `SELECT`), set operations (`UNION`,
* `INTERSECT`, `EXCEPT`), and all DDL / DML / DCL / TCL forms.
*/
export declare function getStatementTypes(sql: string, dialect?: string | undefined | null): StatementTypesResult
/** Import DDL into a Schema. */
export declare function importDdl(ddl: string, dialect?: string | undefined | null): Schema
/** Initialize the SDK with credentials. */
export declare function initSdk(apiKey: string, tenant: string, backendUrl: string, reportFailures: boolean, telemetry?: boolean | undefined | null): void
/** Generate INFORMATION_SCHEMA introspection queries for a database. */
export declare function introspectionSql(dbType: string, database: string, schemaName?: string | undefined | null): IntrospectionSql
/** Quick boolean check: is this SQL safe from injection? */
export declare function isSafe(sql: string): boolean
/** Lint SQL for anti-patterns (SELECT *, missing WHERE, etc.). */
export declare function lint(sql: string, schema: Schema): LintResult
/**
* Lint `new_sql` and return ONLY findings introduced relative to `base_sql`.
*
* Pre-existing findings (present in `base_sql`) are removed via multiset
* subtraction keyed on `(code, normalised_message)`, so line/column shifts
* from reformatting do not cause false positives.
*
* `schema_context` — optional JSON string of a `SchemaDefinition` (same
* format accepted by `Schema.fromJson`). Pass `null`/`undefined` to use a
* dialect-agnostic empty schema.
*
* Returns a `LintResult` JSON object — same shape as `lint()`.
*/
export declare function lintDiff(newSql: string, baseSql: string, schemaContext?: string | undefined | null): LintResult
/** Optimize schema for context window (5-level progressive disclosure). */
export declare function optimizeContext(schema: Schema): ContextResult
/** Optimize schema for a specific query (prune to relevant tables/columns). */
export declare function optimizeForQuery(sql: string, schema: Schema): ContextResult
/** Parse a dbt project directory. */
export declare function parseDbtProject(projectDir: string): DbtProject
/** Prune schema to only tables/columns referenced by a SQL query. */
export declare function pruneSchema(sql: string, schema: Schema): SchemaDefinition
/** Reset SDK state. For testing only. */
export declare function resetSdk(): void
/** Resolve a business term to schema elements via fuzzy matching. */
export declare function resolveTerm(term: string, schema: Schema): GlossaryMatch
/**
* Parse raw LLM output from the AI reviewer into a JSON string of findings.
*
* `text` — raw model response (may contain `<think>` blocks, markdown fences, etc.)
* `valid_files` — the set of file paths that appeared in the diff; findings for any
* other path are dropped (the model hallucinated a path).
*
* Returns a JSON-serialized `Vec<AiReviewFinding>` — an array of objects, or `"[]"` if
* nothing could be parsed. Matches the JSON-string convention used by `DataParitySession`
* (`start()` / `step()` return strings) and by `exportDdl`.
*/
export declare function reviewAiParse(text: string, validFiles: Array<string>): string
/**
* Return the AI reviewer system prompt string.
*
* The prompt is compiled into the binary from `altimate_core::review::AI_REVIEW_SYSTEM_PROMPT`.
* Callers can embed this directly in LLM API calls without bundling any TypeScript assets.
*/
export declare function reviewAiSystemPrompt(): string
/**
* Scan added diff lines for lexical portability issues.
*
* `added_lines` — the `+` lines from a SQL diff (without the leading `+`).
*
* Returns a JSON-serialized `Vec<LexicalFinding>` — an array of objects, or
* `"[]"` if no issues are found. Each element has the shape:
* `{"code":"LX01"|"LX02","rule":"...","severity":"info","message":"...","line":"..."}`.
*
* Results are deduplicated: the same reserved word or operator id across
* multiple lines appears at most once in the output.
*/
export declare function reviewLexicalScan(addedLines: Array<string>): string
/**
* AST base-vs-head structural diff — the `*_change` SQL rules (DISTINCT/UNION flip,
* GROUP BY grain, surrogate-key change, COALESCE removed, predicate removed, type narrowing).
*/
export declare function reviewStructuralDiff(baseSql: string, headSql: string): string
/** Suggest query rewrites and optimizations. */
export declare function rewrite(sql: string, schema: Schema): RewriteResult
/** Scan SQL for injection threats (10 detection rules). */
export declare function scanSql(sql: string): SafetyScanResult
/** Compute a SHA-256 fingerprint of the schema (for caching/change detection). */
export declare function schemaFingerprint(schema: Schema): string
/**
* Track column-level lineage across multiple queries.
*
* The `depth` parameter mirrors `column_lineage`: `"basic"`, `"deep"`, or `"full"` (default).
* Accepted and validated for API consistency; depth-level filtering for multi-query tracking
* will be applied in a future update once the core engine exposes it.
*/
export declare function trackLineage(queries: Array<string>, schema: Schema, depth?: string | undefined | null): LineageResult
/** Transpile SQL from one dialect to another. */
export declare function transpile(sql: string, source: string, target: string): TranspileResult
/** Validate SQL against a schema. Returns an object with `valid`, `errors`, `warnings`. */
export declare function validate(sql: string, schema: Schema): Promise<ValidationResult>