Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

28.2 KB
Raw Blame
import { requiresClickhouseIdentifierQuote, requiresDamengIdentifierQuote, requiresMysqlIdentifierQuote, requiresOracleIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
import { tokenIsIdentifier, tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";
import type { SqlSemanticToken } from "@/lib/sql/semantic/types";
import { formatSqlForDisplay, sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { DEFAULT_SQL_FORMATTER_SETTINGS, type SqlFormatterSettings } from "@/lib/sql/sqlFormatterConfig";
import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
import { compactDdlSql } from "@/lib/sql/ddlCompact";
import { formatStarRocksDdlForDisplay } from "@/lib/sql/starrocksDdlDisplay";
import { dropsSchemaQualifier, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
import type { DatabaseType } from "@/types/database";

const SIMPLE_SQLSERVER_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
const CREATE_TABLE_MODIFIERS = new Set(["external", "global", "local", "materialized", "or", "replace", "temp", "temporary", "transient", "unlogged", "volatile"]);
const TABLE_CONSTRAINT_NAMES = new Set(["check", "constraint", "exclude", "foreign", "fulltext", "index", "key", "period", "primary", "spatial", "unique"]);

type DdlColumnAlignment = {
  lineIndex: number;
  nameEnd: number;
};

type DdlColumnAttributePositions = {
  nullable?: number;
  default?: number;
  identity?: number;
  onUpdate?: number;
  unique?: number;
  references?: number;
  comment?: number;
};

function canRenderUnquoted(identifier: string, dialect: SqlFormatDialect): boolean {
  switch (dialect) {
    case "mysql":
      return !requiresMysqlIdentifierQuote(identifier);
    case "clickhouse":
      return !requiresClickhouseIdentifierQuote(identifier);
    case "postgres":
    case "sqlite":
    case "duckdb":
    case "generic":
      return !requiresPostgresIdentifierQuote(identifier);
    case "dameng":
      return !requiresDamengIdentifierQuote(identifier);
    case "oracle":
      return !requiresOracleIdentifierQuote(identifier);
    case "sqlserver":
      return SIMPLE_SQLSERVER_IDENTIFIER.test(identifier) && !requiresMysqlIdentifierQuote(identifier.toLowerCase());
    default:
      return false;
  }
}

/**
 * Resolve the dialect used to read and rewrite DDL text. Callers that only
 * know the connection's syntax-highlighting dialect (which collapses every
 * Oracle-like database onto MySQL) must not have that value decide identifier
 * quoting rules: a case-sensitive Oracle/Dameng name such as `"cName"` would
 * lose its quotes. The effective database type wins, the highlighting dialect
 * stays as the fallback for unmapped types.
 */
export function ddlFormatDialectFor(options: { formatDialect?: SqlFormatDialect; databaseType?: DatabaseType; highlightDialect?: SqlFormatDialect }): SqlFormatDialect {
  if (options.formatDialect) return options.formatDialect;
  const fromDatabaseType = options.databaseType ? sqlFormatDialectForDbType(options.databaseType) : undefined;
  if (fromDatabaseType && fromDatabaseType !== "generic") return fromDatabaseType;
  return options.highlightDialect ?? fromDatabaseType ?? "generic";
}

/** Removes dialect identifier quotes from safe names while preserving strings, comments, and unsafe names. */
export function omitDdlIdentifierQuotes(sql: string, dialect: SqlFormatDialect): string {
  const tokens = tokenizeSqlSemantic(sql, dialect === "sqlserver" ? "sqlserver" : dialect);
  const replacements: Array<{ start: number; end: number; value: string }> = [];

  for (const token of tokens) {
    if (token.kind !== "quoted_identifier") continue;
    const identifier = unquoteSqlSemanticIdentifier(token);
    if (canRenderUnquoted(identifier, dialect)) replacements.push({ start: token.span.start, end: token.span.end, value: identifier });
  }

  let result = sql;
  for (let index = replacements.length - 1; index >= 0; index -= 1) {
    const replacement = replacements[index]!;
    result = `${result.slice(0, replacement.start)}${replacement.value}${result.slice(replacement.end)}`;
  }
  return result;
}

const SIMPLE_ORACLE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$#]*$/;

export interface GeneratedDdlIdentifierQuoteOptions {
  /**
   * Set by structure editors whose edited table already stores a lowercase or
   * mixed-case identifier. Oracle folds bare identifiers to uppercase, so
   * unquoting `"cName"` turns the statement into `CNAME` — a different column,
   * which fails with ORA-00904 or silently creates a differently-cased column.
   * Preserving the case keeps quotes on every name that would change identity
   * while plain names keep the folding behaviour requested in #8997.
   */
  preserveCaseSensitiveIdentifiers?: boolean;
}

/**
 * Applies the identifier-quoting preference to SQL generated by a structure
 * editor. Oracle folds bare identifiers to uppercase, so safe quoted names
 * are uppercased before their quotes are removed. Dameng keeps its stricter
 * case-sensitive identifier rules through omitDdlIdentifierQuotes instead.
 */
export function formatGeneratedDdlIdentifierQuotes(sql: string, dialect: SqlFormatDialect, quoteIdentifiers: boolean, options: GeneratedDdlIdentifierQuoteOptions = {}): string {
  if (quoteIdentifiers) return sql;
  if (dialect !== "oracle") return omitDdlIdentifierQuotes(sql, dialect);

  const preserveCaseSensitive = options.preserveCaseSensitiveIdentifiers === true;
  const tokens = tokenizeSqlSemantic(sql, dialect);
  const replacements: Array<{ start: number; end: number; value: string }> = [];

  for (const token of tokens) {
    if (token.kind !== "quoted_identifier") continue;
    const identifier = unquoteSqlSemanticIdentifier(token);
    if (!SIMPLE_ORACLE_IDENTIFIER.test(identifier) || requiresOracleIdentifierQuote(identifier.toUpperCase())) continue;
    if (preserveCaseSensitive && identifier !== identifier.toUpperCase()) continue;
    replacements.push({ start: token.span.start, end: token.span.end, value: identifier.toUpperCase() });
  }

  let result = sql;
  for (let index = replacements.length - 1; index >= 0; index -= 1) {
    const replacement = replacements[index]!;
    result = `${result.slice(0, replacement.start)}${replacement.value}${result.slice(replacement.end)}`;
  }
  return result;
}

interface DdlSpan {
  start: number;
  end: number;
}

/** Object keywords that can follow `CREATE` once its modifiers are consumed. */
const DDL_CREATE_OBJECT_WORDS = new Set(["table", "view", "index"]);

/**
 * Modifiers that may appear between `CREATE` and the object keyword. Anything
 * outside this set (`function`, `procedure`, `sequence`, ...) is treated as an
 * object kind we do not rewrite, which keeps unrelated DDL untouched.
 */
const DDL_CREATE_MODIFIER_WORDS = new Set(["global", "local", "materialized", "or", "replace", "temporary", "temp", "unlogged", "unique", "clustered", "nonclustered", "columnstore", "fulltext", "spatial", "external"]);

const DDL_ALTER_OBJECT_WORDS = new Set(["table", "view", "index"]);
const DDL_DROP_OBJECT_WORDS = new Set(["table", "view", "index"]);
const DDL_COMMENT_OBJECT_WORDS = new Set(["table", "view", "index", "materialized"]);

/** Skips an optional keyword sequence, returning the original index when it does not match. */
function skipDdlWords(tokens: readonly SqlSemanticToken[], index: number, end: number, words: readonly string[]): number {
  let cursor = index;
  for (const word of words) {
    const token = tokens[cursor];
    if (cursor >= end || !token || token.kind !== "word" || token.normalized !== word) return index;
    cursor += 1;
  }
  return cursor;
}

/** Token indexes of every identifier part of the qualified name starting at `start`. */
function readDdlQualifiedName(tokens: readonly SqlSemanticToken[], start: number, end: number): number[] | undefined {
  if (start >= end || !tokenIsIdentifier(tokens[start])) return undefined;
  const parts = [start];
  let cursor = start + 1;
  while (cursor + 1 < end && tokens[cursor]!.text === "." && tokenIsIdentifier(tokens[cursor + 1])) {
    parts.push(cursor + 1);
    cursor += 2;
  }
  return parts;
}

function findDdlKeyword(tokens: readonly SqlSemanticToken[], start: number, end: number, word: string): number {
  for (let cursor = start; cursor < end; cursor += 1) {
    const token = tokens[cursor]!;
    if (token.depth === 0 && token.kind === "word" && token.normalized === word) return cursor;
  }
  return -1;
}

/**
 * Records the span covering the qualifier chain of a qualified name, keeping
 * only the trailing `keep` parts (`SYSTEM.TEST` with `keep: 1` removes `SYSTEM.`).
 */
function collectDdlQualifierRemoval(tokens: readonly SqlSemanticToken[], parts: readonly number[], keep: number, out: DdlSpan[]): void {
  const firstKept = parts.length - keep;
  if (firstKept <= 0) return;
  out.push({ start: tokens[parts[0]!]!.span.start, end: tokens[parts[firstKept]!]!.span.start });
}

interface DdlNameTarget {
  /** Token indexes of every identifier part of the qualified name. */
  parts: number[];
  /**
   * Trailing parts that must survive a rewrite. `COMMENT ON COLUMN t.c` keeps
   * two (`t.c`), everything else keeps the bare object name.
   */
  keep: number;
  /**
   * Whether a leading database segment may be *inserted*. Index names are
   * scoped to their table (`CREATE INDEX db.idx` is invalid on MySQL and
   * SQL Server), so they stay untouched when the preference is enabled.
   */
  qualifiable: boolean;
}

/** Every qualified name a DDL statement addresses, in source order. */
function collectDdlStatementNameTargets(tokens: readonly SqlSemanticToken[], from: number, to: number, out: DdlNameTarget[]): void {
  let index = from;
  while (index < to && tokens[index]!.kind === "comment") index += 1;
  const head = tokens[index];
  if (!head || head.kind !== "word") return;

  if (head.normalized === "create") {
    let cursor = index + 1;
    while (cursor < to) {
      const token = tokens[cursor]!;
      if (token.kind !== "word") return;
      if (DDL_CREATE_OBJECT_WORDS.has(token.normalized)) break;
      if (!DDL_CREATE_MODIFIER_WORDS.has(token.normalized)) return;
      cursor += 1;
    }
    const objectWord = tokens[cursor];
    if (!objectWord) return;
    cursor = skipDdlWords(tokens, cursor + 1, to, ["if", "not", "exists"]);
    const nameParts = readDdlQualifiedName(tokens, cursor, to);
    if (!nameParts) return;
    out.push({ parts: nameParts, keep: 1, qualifiable: objectWord.normalized !== "index" });
    if (objectWord.normalized === "index") {
      const onIndex = findDdlKeyword(tokens, nameParts[nameParts.length - 1]! + 1, to, "on");
      if (onIndex < 0) return;
      const tableParts = readDdlQualifiedName(tokens, onIndex + 1, to);
      if (tableParts) out.push({ parts: tableParts, keep: 1, qualifiable: true });
    }
    return;
  }

  if (head.normalized === "alter") {
    const objectWord = tokens[index + 1];
    if (!objectWord || objectWord.kind !== "word" || !DDL_ALTER_OBJECT_WORDS.has(objectWord.normalized)) return;
    const nameParts = readDdlQualifiedName(tokens, skipDdlWords(tokens, index + 2, to, ["if", "exists"]), to);
    if (nameParts) out.push({ parts: nameParts, keep: 1, qualifiable: objectWord.normalized !== "index" });
    return;
  }

  if (head.normalized === "drop") {
    const objectWord = tokens[index + 1];
    if (!objectWord || objectWord.kind !== "word" || !DDL_DROP_OBJECT_WORDS.has(objectWord.normalized)) return;
    let cursor = skipDdlWords(tokens, index + 2, to, ["if", "exists"]);
    for (;;) {
      const nameParts = readDdlQualifiedName(tokens, cursor, to);
      if (!nameParts) return;
      out.push({ parts: nameParts, keep: 1, qualifiable: objectWord.normalized !== "index" });
      cursor = nameParts[nameParts.length - 1]! + 1;
      if (tokens[cursor]?.text !== ",") return;
      cursor += 1;
    }
  }

  if (head.normalized === "truncate") {
    let cursor = index + 1;
    if (tokens[cursor]?.kind === "word" && ["table", "only"].includes(tokens[cursor]!.normalized)) cursor += 1;
    const nameParts = readDdlQualifiedName(tokens, cursor, to);
    if (nameParts) out.push({ parts: nameParts, keep: 1, qualifiable: true });
    return;
  }

  if (head.normalized === "comment") {
    if (tokens[index + 1]?.normalized !== "on") return;
    const objectWord = tokens[index + 2];
    if (!objectWord || objectWord.kind !== "word") return;
    const isColumn = objectWord.normalized === "column";
    if (!isColumn && !DDL_COMMENT_OBJECT_WORDS.has(objectWord.normalized)) return;
    const nameParts = readDdlQualifiedName(tokens, index + 3, to);
    // `COMMENT ON COLUMN t.c` keeps `t.c`, so only the schema qualifier goes.
    if (nameParts) out.push({ parts: nameParts, keep: isColumn ? 2 : 1, qualifiable: false });
  }
}

/** Every qualified name addressed by the DDL statements in `sql`, in source order. */
function ddlStatementNameTargets(sql: string, dialect: SqlFormatDialect): { targets: DdlNameTarget[]; tokens: readonly SqlSemanticToken[] } | undefined {
  const tokens = tokenizeSqlSemantic(sql, dialect === "sqlserver" ? "sqlserver" : dialect);
  if (tokens.some((token) => token.closed === false)) return undefined;
  const targets: DdlNameTarget[] = [];
  let statementStart = 0;
  for (let index = 0; index <= tokens.length; index += 1) {
    const token = tokens[index];
    if (token && !(token.kind === "punctuation" && token.text === ";" && token.depth === 0)) continue;
    collectDdlStatementNameTargets(tokens, statementStart, index, targets);
    statementStart = index + 1;
  }
  return { targets, tokens };
}

function collectDdlStatementQualifierRemovals(tokens: readonly SqlSemanticToken[], from: number, to: number, out: DdlSpan[]): void {
  const targets: DdlNameTarget[] = [];
  collectDdlStatementNameTargets(tokens, from, to, targets);
  for (const target of targets) collectDdlQualifierRemoval(tokens, target.parts, target.keep, out);
}

function applyDdlSpans(sql: string, spans: readonly { start: number; end: number; text?: string }[]): string {
  const ordered = [...spans].sort((left, right) => left.start - right.start);
  let result = sql;
  for (let index = ordered.length - 1; index >= 0; index -= 1) {
    const span = ordered[index]!;
    result = `${result.slice(0, span.start)}${span.text ?? ""}${result.slice(span.end)}`;
  }
  return result;
}

/** Engines whose fully qualified table name is `database.table`. */
const DDL_DATABASE_PREFIXED_TYPES = new Set<DatabaseType>(["mysql", "goldendb", "clickhouse"]);
/** Engines whose fully qualified table name is `database.schema.table`. */
const DDL_DATABASE_SCHEMA_PREFIXED_TYPES = new Set<DatabaseType>(["sqlserver"]);

/**
 * Number of parts a fully qualified target name has on this engine, or
 * `undefined` when the engine cannot take a leading database segment (then the
 * DDL stays untouched in both directions).
 */
function ddlQualifiedPartCount(databaseType: DatabaseType | undefined, catalog?: string): number | undefined {
  if (databaseType === undefined) return undefined;
  if (DDL_DATABASE_SCHEMA_PREFIXED_TYPES.has(databaseType)) return 3;
  if (DDL_DATABASE_PREFIXED_TYPES.has(databaseType)) return 2;
  if (databaseType === "doris" || databaseType === "starrocks") {
    // An external catalog already supplies the leading segment
    // (`catalog.database.table`), so the DDL must not grow a second one.
    const external = catalog?.trim();
    return !external || external === "internal" ? 2 : undefined;
  }
  return undefined;
}

/**
 * Applies the "Include database name in generated SQL" preference to the target
 * object of DDL statements (`CREATE/ALTER/DROP TABLE`, `CREATE INDEX ... ON`,
 * `COMMENT ON ...`, `TRUNCATE TABLE`), the same way generated SELECT and
 * copy-as-INSERT SQL honor it.
 *
 * With the preference off the schema/database qualifier is dropped (#9421).
 * With it on, engines whose server never returns the database — MySQL's
 * `SHOW CREATE TABLE` cannot include it — and SQL Server, whose generated DDL
 * stops at `schema.table`, get the leading `database` segment inserted, so a
 * SQL Server table reads `[dbx].[dbo].[t]` (#9262). Databases whose objects
 * cannot be addressed without their qualifier keep it, mirroring
 * `dropsSchemaQualifier`.
 */
export function applyDdlDatabaseQualifier(sql: string, dialect: SqlFormatDialect, databaseType: DatabaseType | undefined, includeDatabaseName: boolean, database?: string, catalog?: string): string {
  if (includeDatabaseName) {
    const qualifiedParts = ddlQualifiedPartCount(databaseType, catalog);
    const databaseName = database?.trim();
    if (qualifiedParts === undefined || !databaseName) return sql;
    const parsed = ddlStatementNameTargets(sql, dialect);
    if (!parsed) return sql;
    const prefix = `${quoteTableIdentifier(databaseType, databaseName)}.`;
    const insertions: Array<DdlSpan & { text: string }> = [];
    for (const target of parsed.targets) {
      // Only a table-like target can be completed: adding a segment to a bare
      // or half-qualified name would invent a namespace the DDL never named,
      // and a `COMMENT ON COLUMN t.c` target is not a database-addressable
      // object.
      if (!target.qualifiable || target.keep !== 1 || target.parts.length !== qualifiedParts - 1) continue;
      const at = parsed.tokens[target.parts[0]!]!.span.start;
      insertions.push({ start: at, end: at, text: prefix });
    }
    if (insertions.length === 0) return sql;
    return applyDdlSpans(sql, insertions);
  }

  if (!dropsSchemaQualifier(databaseType, includeDatabaseName, catalog)) return sql;
  const tokens = tokenizeSqlSemantic(sql, dialect === "sqlserver" ? "sqlserver" : dialect);
  if (tokens.some((token) => token.closed === false)) return sql;

  const removals: DdlSpan[] = [];
  let statementStart = 0;
  for (let index = 0; index <= tokens.length; index += 1) {
    const token = tokens[index];
    if (token && !(token.kind === "punctuation" && token.text === ";" && token.depth === 0)) continue;
    collectDdlStatementQualifierRemovals(tokens, statementStart, index, removals);
    statementStart = index + 1;
  }
  if (removals.length === 0) return sql;

  return applyDdlSpans(sql, removals);
}

function findLineIndex(lineStarts: number[], position: number): number {
  for (let index = lineStarts.length - 1; index >= 0; index -= 1) {
    if (lineStarts[index]! <= position) return index;
  }
  return 0;
}

function findCreateTableBody(sql: string, dialect: SqlFormatDialect): { start: number; end: number } | undefined {
  const tokens = tokenizeSqlSemantic(sql, dialect);
  const createIndex = tokens.findIndex((token) => token.kind === "word" && token.normalized === "create");
  if (createIndex < 0) return undefined;

  let tableIndex = createIndex + 1;
  while (tableIndex < tokens.length && tokens[tableIndex]?.kind === "word" && CREATE_TABLE_MODIFIERS.has(tokens[tableIndex]!.normalized)) tableIndex += 1;
  if (tokens[tableIndex]?.kind !== "word" || tokens[tableIndex]?.normalized !== "table") return undefined;

  let openingIndex = -1;
  for (let index = tableIndex + 1; index < tokens.length; index += 1) {
    const token = tokens[index]!;
    if (token.depth === 0 && token.kind === "punctuation" && token.text === ";") break;
    if (token.depth === 0 && token.kind === "word" && token.normalized === "as") break;
    if (token.depth === 0 && token.kind === "punctuation" && token.text === "(") {
      openingIndex = index;
      break;
    }
  }
  if (openingIndex < 0) return undefined;
  const opening = tokens[openingIndex]!;
  const closing = tokens.find((token, index) => index > openingIndex && token.kind === "punctuation" && token.text === ")" && token.depth === opening.depth);
  if (!closing) return undefined;
  return { start: opening.span.end, end: closing.span.start };
}

function readColumnAlignment(line: string, lineIndex: number, dialect: SqlFormatDialect): DdlColumnAlignment | undefined {
  const tokens = tokenizeSqlSemantic(line, dialect);
  const name = tokens[0];
  const dataType = tokens[1];
  if (!tokenIsIdentifier(name) || !tokenIsIdentifier(dataType) || TABLE_CONSTRAINT_NAMES.has(name.normalized)) return undefined;
  return { lineIndex, nameEnd: name.span.end };
}

function findColumnAttributePositions(line: string, dialect: SqlFormatDialect): DdlColumnAttributePositions {
  const tokens = tokenizeSqlSemantic(line, dialect);
  const name = tokens[0];
  const dataType = tokens[1];
  if (!tokenIsIdentifier(name) || !tokenIsIdentifier(dataType)) return {};

  const words = tokens.filter((token) => token.kind === "word" && token.depth === 0 && token.span.start >= dataType.span.end);
  const findWord = (value: string) => words.find((token) => token.normalized === value);
  const defaultToken = findWord("default");
  let nullableToken = words.find((token, index) => token.normalized === "not" && words[index + 1]?.normalized === "null");
  if (!nullableToken) {
    nullableToken = words.find((token) => token.normalized === "null" && (!defaultToken || token.span.start < defaultToken.span.start));
  }

  const identityToken = words.find((token) => token.normalized === "auto_increment" || token.normalized === "identity");
  const onToken = words.find((token, index) => token.normalized === "on" && words[index + 1]?.normalized === "update");
  const uniqueToken = findWord("unique");
  const referencesToken = findWord("references");
  const commentToken = findWord("comment");

  return {
    ...(nullableToken ? { nullable: nullableToken.span.start } : {}),
    ...(defaultToken ? { default: defaultToken.span.start } : {}),
    ...(identityToken ? { identity: identityToken.span.start } : {}),
    ...(onToken ? { onUpdate: onToken.span.start } : {}),
    ...(uniqueToken ? { unique: uniqueToken.span.start } : {}),
    ...(referencesToken ? { references: referencesToken.span.start } : {}),
    ...(commentToken ? { comment: commentToken.span.start } : {}),
  };
}

export function uppercaseDdlColumnTypes(sql: string, dialect: SqlFormatDialect): string {
  const body = findCreateTableBody(sql, dialect);
  if (!body) return sql;

  const lines = sql.split("\n");
  const lineStarts: number[] = [];
  let offset = 0;
  for (const line of lines) {
    lineStarts.push(offset);
    offset += line.length + 1;
  }

  const firstBodyLine = findLineIndex(lineStarts, body.start) + 1;
  const lastBodyLine = findLineIndex(lineStarts, body.end);
  for (let lineIndex = firstBodyLine; lineIndex < lastBodyLine; lineIndex += 1) {
    const line = lines[lineIndex]!;
    if (!readColumnAlignment(line, lineIndex, dialect)) continue;

    const tokens = tokenizeSqlSemantic(line, dialect);
    const dataType = tokens[1];
    if (dataType?.kind !== "word") continue;

    const attributePositions = findColumnAttributePositions(line, dialect);
    const attributeStart = Math.min(line.length, ...Object.values(attributePositions).filter((position): position is number => position !== undefined));
    const typeWords = tokens.filter((token) => token.kind === "word" && token.span.start >= dataType.span.start && token.span.start < attributeStart);
    for (let tokenIndex = typeWords.length - 1; tokenIndex >= 0; tokenIndex -= 1) {
      const token = typeWords[tokenIndex]!;
      const upper = token.text.toUpperCase();
      if (token.text === upper) continue;
      lines[lineIndex] = `${lines[lineIndex]!.slice(0, token.span.start)}${upper}${lines[lineIndex]!.slice(token.span.end)}`;
    }
  }

  return lines.join("\n");
}

function alignColumnAttribute(lines: string[], columns: DdlColumnAlignment[], attribute: keyof DdlColumnAttributePositions, dialect: SqlFormatDialect) {
  const positions = columns.map(({ lineIndex }) => findColumnAttributePositions(lines[lineIndex]!, dialect)[attribute]);
  const target = Math.max(-1, ...positions.filter((position): position is number => position !== undefined));
  if (target < 0) return;

  columns.forEach(({ lineIndex }, index) => {
    const position = positions[index];
    if (position === undefined || position >= target) return;
    lines[lineIndex] = `${lines[lineIndex]!.slice(0, position)}${" ".repeat(target - position)}${lines[lineIndex]!.slice(position)}`;
  });
}

export function alignDdlColumnDefinitions(sql: string, dialect: SqlFormatDialect): string {
  const body = findCreateTableBody(sql, dialect);
  if (!body) return sql;

  const lines = sql.split("\n");
  const lineStarts: number[] = [];
  let offset = 0;
  for (const line of lines) {
    lineStarts.push(offset);
    offset += line.length + 1;
  }

  const firstBodyLine = findLineIndex(lineStarts, body.start) + 1;
  const lastBodyLine = findLineIndex(lineStarts, body.end);
  const columns: DdlColumnAlignment[] = [];
  for (let lineIndex = firstBodyLine; lineIndex < lastBodyLine; lineIndex += 1) {
    const column = readColumnAlignment(lines[lineIndex]!, lineIndex, dialect);
    if (column) columns.push(column);
  }
  if (columns.length < 2) return sql;

  const maxNameWidth = Math.max(
    ...columns.map(({ lineIndex, nameEnd }) => {
      const line = lines[lineIndex]!;
      const indentWidth = line.length - line.trimStart().length;
      return nameEnd - indentWidth;
    }),
  );
  for (const { lineIndex, nameEnd } of columns) {
    const line = lines[lineIndex]!;
    const indentWidth = line.length - line.trimStart().length;
    const name = line.slice(indentWidth, nameEnd);
    lines[lineIndex] = `${line.slice(0, indentWidth)}${name.padEnd(maxNameWidth + 2)}${line.slice(nameEnd).trimStart()}`;
  }

  const initialPositions = columns.map(({ lineIndex }) => findColumnAttributePositions(lines[lineIndex]!, dialect));
  const defaultBeforeNullable = initialPositions.filter((positions) => positions.default !== undefined && positions.nullable !== undefined && positions.default < positions.nullable).length;
  const nullableBeforeDefault = initialPositions.filter((positions) => positions.default !== undefined && positions.nullable !== undefined && positions.nullable < positions.default).length;
  const attributeOrder: Array<keyof DdlColumnAttributePositions> = defaultBeforeNullable > nullableBeforeDefault ? ["default", "nullable", "identity", "onUpdate", "unique", "references", "comment"] : ["nullable", "default", "identity", "onUpdate", "unique", "references", "comment"];
  for (const attribute of attributeOrder) alignColumnAttribute(lines, columns, attribute, dialect);

  return lines.join("\n");
}

export interface DdlDisplayFormatOptions {
  dialect: SqlFormatDialect;
  /** Effective type from effectiveDatabaseTypeForConnection, including MySQL driver profiles. */
  databaseType?: DatabaseType;
  database?: string;
  catalog?: string;
  includeDatabaseName: boolean;
  quoteIdentifiers: boolean;
  /**
   * Storage-clause filtering for surfaces that bake the text once (DDL viewer
   * tabs store plain SQL). The dialog and the structure editor keep it off and
   * re-filter on read instead, so toggling the preference updates them without
   * reloading the DDL.
   */
  excludeDdlStorage?: boolean;
  compactDdlSql?: boolean;
}

/**
 * Shared preference tail of the read-only DDL display pipeline: applies the
 * database-name qualifier, the identifier-quoting preference, and the column
 * type casing/alignment to already-formatted DDL. Use {@link formatDdlForDisplay}
 * unless the input is formatted separately.
 */
export function applyDdlDisplayPreferences(sql: string, options: DdlDisplayFormatOptions): string {
  const qualified = applyDdlDatabaseQualifier(sql, options.dialect, options.databaseType, options.includeDatabaseName, options.database, options.catalog);
  const quoted = options.quoteIdentifiers ? qualified : omitDdlIdentifierQuotes(qualified, options.dialect);
  const aligned = options.databaseType === "starrocks" ? formatStarRocksDdlForDisplay(quoted) : alignDdlColumnDefinitions(uppercaseDdlColumnTypes(quoted, options.dialect), options.dialect);
  const filtered = options.excludeDdlStorage ? applyDdlStoragePreference(aligned, options.databaseType) : aligned;
  return options.compactDdlSql ? compactDdlSql(filtered, options.databaseType) : filtered;
}

/**
 * Canonical read-only DDL display pipeline shared by the DDL dialog, DDL viewer
 * tabs, and the structure editor's DDL tab: format the statement, apply the
 * SQL-editor preferences, and align the column definitions. Callers feed the
 * result of the object DDL fetch straight through it.
 */
export async function formatDdlForDisplay(ddl: string, options: DdlDisplayFormatOptions, formatter: Partial<SqlFormatterSettings> = DEFAULT_SQL_FORMATTER_SETTINGS): Promise<string> {
  return applyDdlDisplayPreferences(options.databaseType === "starrocks" ? ddl : await formatSqlForDisplay(ddl, options.dialect, formatter), options);
}