From b2abb106bf0dde23503b5e2ae02bd38821bc6094 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 7 Mar 2026 18:26:12 +0100 Subject: [PATCH 1/9] Add diff command, grants support, type normalization, and CSV catalog queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add `diff` command: compares SQL files in routines_dir against database catalog, reports missing/different/extra routines with full signatures and clickable file paths - Add optional grants/ACL tracking (`[project].grants` config toggle): parses GRANT/REVOKE statements, compares with pg_catalog ACL entries - Add type alias normalization (int→integer, varchar→character varying, etc.) to prevent false positives when comparing parsed vs catalog types - Migrate catalog queries from pipe-delimited to `psql --csv` for safe parsing of bodies containing pipes/newlines - Add `ignore_body_whitespace` config option to skip formatting-only diffs - Fix test DB safety: only read from test.env, never process.env - Fix RETURNS TABLE/SETOF rows default (1000 vs 0 for scalar) - Group project settings in config dashboard under "Project Settings" Co-Authored-By: Claude Opus 4.6 --- package.json | 2 +- src/cli.ts | 5 + src/commands/config.ts | 28 ++- src/commands/diff.ts | 215 +++++++++++++++++ src/commands/exec.ts | 124 ++++++++++ src/commands/sync.test.ts | 20 ++ src/commands/sync.ts | 14 +- src/config.ts | 56 +++++ src/parser/catalog-tests/grants.test.ts | 104 +++++++++ src/parser/catalog.ts | 77 ++++--- src/parser/compare.ts | 120 +++++++++- .../parser-tests/normalize-type.test.ts | 216 ++++++++++++++++++ .../parser-tests/routine-body-hash.test.ts | 35 ++- .../parser-tests/routine-grants.test.ts | 173 ++++++++++++++ src/parser/routine.ts | 48 +++- src/test/db.ts | 15 +- 16 files changed, 1190 insertions(+), 62 deletions(-) create mode 100644 src/commands/diff.ts create mode 100644 src/parser/catalog-tests/grants.test.ts create mode 100644 src/parser/parser-tests/normalize-type.test.ts create mode 100644 src/parser/parser-tests/routine-grants.test.ts diff --git a/package.json b/package.json index 4323656..1fc9d73 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pgdev", - "version": "0.0.13", + "version": "0.0.14", "author": "vbilopav", "repository": { "type": "git", diff --git a/src/cli.ts b/src/cli.ts index 1bfb9b5..82d3ec3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -9,6 +9,7 @@ import { runCommand } from "./commands/run.ts"; import { configCommand } from "./commands/config.ts"; import { execCommand, psqlCommand, runPsqlQuery, resolveConnection } from "./commands/exec.ts"; import { syncCommand } from "./commands/sync.ts"; +import { diffCommand } from "./commands/diff.ts"; import { loadConfig, ensureConfigFile, isSharedConnection, type PgdevConfig } from "./config.ts"; import { readJsonConfig } from "./utils/json.ts"; import { resolveEnvVars, loadEnvFile } from "./utils/env.ts"; @@ -429,6 +430,7 @@ ${pc.bold("Usage:")} ${pc.bold("Commands:")} config Configure tools, NpgsqlRest, environment, and project init, setup Alias for config + diff Compare project routines with database exec Execute SQL command via psql psql Open interactive psql session sync Dump database schema to migrations directory @@ -498,6 +500,9 @@ export async function run(): Promise { case "psql": await psqlCommand(config); break; + case "diff": + await diffCommand(config); + break; case "sync": await syncCommand(config); break; diff --git a/src/commands/config.ts b/src/commands/config.ts index 29ed2a1..9f8ae23 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -1,7 +1,7 @@ import { $ } from "bun"; import { statSync, readdirSync, mkdirSync } from "node:fs"; import { resolve, dirname } from "node:path"; -import { loadConfig, type PgdevConfig, updateConfig, updateConfigArraySync, removeConfigKey, isSharedConnection } from "../config.ts"; +import { loadConfig, type PgdevConfig, updateConfig, updateConfigBool, updateConfigArraySync, removeConfigKey, isSharedConnection } from "../config.ts"; import { success, error, pc, formatCmd, spinner } from "../utils/terminal.ts"; import { ask, askConfirm, askValue, askPath, askDashboard, askMultiSelect } from "../utils/prompt.ts"; import { readJsonConfig, writeJsonConfig } from "../utils/json.ts"; @@ -2145,6 +2145,7 @@ async function editProjectDirectories(config: PgdevConfig): Promise { if (choice.type === "item") { lastSelected = choice.key; + const key = choice.key as "routines_dir" | "migrations_dir" | "tests_dir"; const labels: Record = { routines_dir: "Routines directory", @@ -2187,6 +2188,11 @@ export async function configCommand(config: PgdevConfig): Promise { value: environmentStatus(currentConfig), help: "Env file and database connection for pgdev tools.", }, + ], + }, + { + title: "Project Settings", + items: [ { key: "project", label: "Project directories", @@ -2199,6 +2205,18 @@ export async function configCommand(config: PgdevConfig): Promise { value: schemasStatus(currentConfig.project.schemas), help: "Select database schemas used by this project.\nEmpty means all non-system schemas.", }, + { + key: "grants", + label: "Track grants", + value: currentConfig.project.grants ? "yes" : "no", + help: "Track GRANT/REVOKE statements for routines.\nWhen enabled, pgdev parses and compares routine permissions,\nand sync includes ACL entries in dumped SQL files.", + }, + { + key: "ignore_body_whitespace", + label: "Ignore body whitespace", + value: currentConfig.project.ignore_body_whitespace ? "yes" : "no", + help: "Ignore whitespace differences in routine bodies when comparing.\nWhen enabled, formatting-only changes (indentation, line breaks) are not reported as differences.", + }, ], }, ]; @@ -2222,6 +2240,14 @@ export async function configCommand(config: PgdevConfig): Promise { await editProjectDirectories(currentConfig); } else if (choice.key === "schemas") { lastStatus = await handleSchemas(currentConfig); + } else if (choice.key === "grants") { + const newValue = !currentConfig.project.grants; + await updateConfigBool("project", "grants", newValue); + lastStatus = `grants = ${newValue}`; + } else if (choice.key === "ignore_body_whitespace") { + const newValue = !currentConfig.project.ignore_body_whitespace; + await updateConfigBool("project", "ignore_body_whitespace", newValue); + lastStatus = `ignore_body_whitespace = ${newValue}`; } currentConfig = await loadConfig(); diff --git a/src/commands/diff.ts b/src/commands/diff.ts new file mode 100644 index 0000000..48bdeda --- /dev/null +++ b/src/commands/diff.ts @@ -0,0 +1,215 @@ +import { resolve } from "node:path"; +import { readdirSync, statSync } from "node:fs"; +import type { PgdevConfig } from "../config.ts"; +import { pc, spinner } from "../utils/terminal.ts"; +import { parseRoutines, type ParsedRoutine } from "../parser/routine.ts"; +import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; +import { routinesDiffer, commentsDiffer, grantsDiffer, type DiffOptions } from "../parser/compare.ts"; + +/** + * Match key uses schema.name only. Overloaded functions (same name, different + * params) are grouped and matched by parameter count. + */ +function groupKey(schema: string, name: string): string { + return `${schema}.${name}`; +} + +/** Display key includes full parameter signature (name + type). */ +function parsedGroupKey(r: ParsedRoutine, defaultSchema: string): string { + return groupKey(r.schema ?? defaultSchema, r.name); +} + +function catalogGroupKey(r: CatalogRoutine): string { + return groupKey(r.schema, r.name); +} + +function parsedDisplayKey(r: ParsedRoutine, defaultSchema: string): string { + const schema = r.schema ?? defaultSchema; + const params = r.parameters.map((p) => p.name ? `${p.name} ${p.type.toLowerCase()}` : p.type.toLowerCase()); + return `${schema}.${r.name}(${params.join(", ")})`; +} + +function catalogDisplayKey(r: CatalogRoutine): string { + const params = r.parameters.map((p) => p.name ? `${p.name} ${p.type}` : p.type); + return `${r.schema}.${r.name}(${params.join(", ")})`; +} + +/** Recursively find all .sql files in a directory. */ +function findSqlFiles(dir: string): string[] { + const results: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = resolve(dir, entry.name); + if (entry.isDirectory()) { + results.push(...findSqlFiles(full)); + } else if (entry.isFile() && entry.name.endsWith(".sql")) { + results.push(full); + } + } + return results.sort(); +} + +export async function diffCommand(config: PgdevConfig): Promise { + const { routines_dir, schemas, grants, ignore_body_whitespace } = config.project; + + if (!routines_dir) { + console.error(pc.red("routines_dir is not configured. Run pgdev config to set it.")); + process.exit(1); + } + + if (schemas.length === 0) { + console.error(pc.red("No schemas configured. Run pgdev config to set project schemas.")); + process.exit(1); + } + + const fullDir = resolve(process.cwd(), routines_dir); + let isDir = false; + try { isDir = statSync(fullDir).isDirectory(); } catch {} + if (!isDir) { + console.error(pc.red(`Routines directory not found: ${routines_dir}`)); + process.exit(1); + } + + // Parse all SQL files + const s = spinner("Parsing SQL files..."); + const sqlFiles = findSqlFiles(fullDir); + if (sqlFiles.length === 0) { + s.stop(); + console.log(pc.yellow("No .sql files found in " + routines_dir)); + return; + } + + const defaultSchema = schemas[0]; + + // Collect parsed routines grouped by schema.name + const parsedGroups = new Map(); + let totalParsed = 0; + + for (const file of sqlFiles) { + const content = await Bun.file(file).text(); + const routines = parseRoutines(content, { grants }); + const relPath = file.slice(process.cwd().length + 1); + for (const r of routines) { + const gk = parsedGroupKey(r, defaultSchema); + const dk = parsedDisplayKey(r, defaultSchema); + let group = parsedGroups.get(gk); + if (!group) { group = []; parsedGroups.set(gk, group); } + group.push({ routine: r, file: relPath, display: dk }); + totalParsed++; + } + } + s.update("Fetching catalog metadata..."); + + // Fetch catalog + let catalog: CatalogRoutine[]; + try { + catalog = await fetchCatalogMetadata(config); + } catch (err) { + s.stop(); + console.error(pc.red(err instanceof Error ? err.message : String(err))); + process.exit(1); + } + s.stop(); + + // Group catalog routines by schema.name + const catalogGroups = new Map(); + for (const c of catalog) { + const gk = catalogGroupKey(c); + const dk = catalogDisplayKey(c); + let group = catalogGroups.get(gk); + if (!group) { group = []; catalogGroups.set(gk, group); } + group.push({ routine: c, display: dk }); + } + + // Compare — match by schema.name, then by param count for overloads + const needCreating: { display: string; file: string }[] = []; + const needUpdating: { display: string; file: string; changes: string[] }[] = []; + const needDropping: string[] = []; + const matchedCatalogKeys = new Set(); + + for (const [gk, parsedList] of parsedGroups) { + const catList = catalogGroups.get(gk); + if (!catList) { + for (const p of parsedList) needCreating.push({ display: p.display, file: p.file }); + continue; + } + + matchedCatalogKeys.add(gk); + + // Match each parsed routine to a catalog routine by param count + const usedCat = new Set(); + for (const p of parsedList) { + const paramCount = p.routine.parameters.length; + const catIdx = catList.findIndex((c, i) => !usedCat.has(i) && c.routine.parameters.length === paramCount); + if (catIdx === -1) { + needCreating.push({ display: p.display, file: p.file }); + continue; + } + usedCat.add(catIdx); + const cat = catList[catIdx].routine; + + const changes: string[] = []; + const diffOpts: DiffOptions = { ignoreBodyWhitespace: ignore_body_whitespace }; + if (routinesDiffer(p.routine, cat, diffOpts)) changes.push("definition"); + if (commentsDiffer(p.routine, cat)) changes.push("comment"); + if (grants && grantsDiffer(p.routine, cat)) changes.push("grants"); + + if (changes.length > 0) { + needUpdating.push({ display: p.display, file: p.file, changes }); + } + } + + // Unmatched catalog routines in this group + for (let i = 0; i < catList.length; i++) { + if (!usedCat.has(i)) needDropping.push(catList[i].display); + } + } + + // Catalog routines with no parsed group at all + for (const [gk, catList] of catalogGroups) { + if (!matchedCatalogKeys.has(gk)) { + for (const c of catList) needDropping.push(c.display); + } + } + + // Report + const unchanged = totalParsed - needCreating.length - needUpdating.length; + + if (needCreating.length === 0 && needUpdating.length === 0 && needDropping.length === 0) { + console.log(pc.green(`All ${totalParsed} routines match the database.`)); + return; + } + + console.log(); + + if (needCreating.length > 0) { + console.log(pc.bold(`Missing in database (${needCreating.length}):`)); + for (const { display, file } of needCreating) { + console.log(` ${pc.green("+")} ${display} ${pc.dim(file)}`); + } + console.log(); + } + + if (needUpdating.length > 0) { + console.log(pc.bold(`Different from database (${needUpdating.length}):`)); + for (const { display, file, changes } of needUpdating) { + console.log(` ${pc.yellow("~")} ${display} ${pc.dim(file)}`); + } + console.log(); + } + + if (needDropping.length > 0) { + console.log(pc.bold(`Only in database (${needDropping.length}):`)); + for (const key of needDropping) { + console.log(` ${pc.red("-")} ${key}`); + } + console.log(); + } + + // Summary + const parts: string[] = []; + if (unchanged > 0) parts.push(`${unchanged} unchanged`); + if (needCreating.length > 0) parts.push(pc.green(`${needCreating.length} to create`)); + if (needUpdating.length > 0) parts.push(pc.yellow(`${needUpdating.length} to update`)); + if (needDropping.length > 0) parts.push(pc.red(`${needDropping.length} to drop`)); + console.log(parts.join(", ")); +} diff --git a/src/commands/exec.ts b/src/commands/exec.ts index ddaa0e7..680c8da 100644 --- a/src/commands/exec.ts +++ b/src/commands/exec.ts @@ -146,6 +146,130 @@ export async function runPsqlQuery(config: PgdevConfig, sql: string): Promise[]; cmd: string } | { ok: false; error: string; cmd: string }; + +export async function runPsqlCsvQuery(config: PgdevConfig, sql: string): Promise { + const fields = await resolveConnection(config); + if (typeof fields === "string") return { ok: false, error: fields, cmd: "" }; + if (!fields.database) return { ok: false, error: "No database specified in connection.", cmd: "" }; + + const psqlParts = splitCommand(config.tools.psql); + const cmd = [ + ...psqlParts, + "-h", fields.host, + "-p", fields.port, + "-d", fields.database, + "-U", fields.username, + "--csv", + "-c", sql, + ]; + + const cmdStr = formatCmd(cmd); + + try { + const proc = Bun.spawn(cmd, { + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + env: { ...process.env, PGPASSWORD: fields.password }, + }); + const stdout = await new Response(proc.stdout).text(); + const exitCode = await proc.exited; + if (exitCode !== 0) { + const stderr = await new Response(proc.stderr).text(); + return { ok: false, error: stderr.trim() || "psql exited with code " + exitCode, cmd: cmdStr }; + } + const rows = parseCsvOutput(stdout.trim()); + return { ok: true, rows, cmd: cmdStr }; + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err), cmd: cmdStr }; + } +} + +/** Parse psql --csv output into array of records. Handles quoted fields with commas/newlines. */ +function parseCsvOutput(output: string): Record[] { + if (!output) return []; + + const lines = parseCsvLines(output); + if (lines.length < 2) return []; + + const headers = lines[0]; + return lines.slice(1).map((fields) => { + const row: Record = {}; + for (let i = 0; i < headers.length; i++) { + row[headers[i]] = fields[i] ?? ""; + } + return row; + }); +} + +/** Split CSV text into rows of fields, handling quoted fields with embedded newlines/commas. */ +function parseCsvLines(text: string): string[][] { + const rows: string[][] = []; + let i = 0; + + while (i < text.length) { + const { fields, nextPos } = parseCsvRow(text, i); + rows.push(fields); + i = nextPos; + } + + return rows; +} + +function parseCsvRow(text: string, start: number): { fields: string[]; nextPos: number } { + const fields: string[] = []; + let i = start; + + while (i <= text.length) { + if (i === text.length || text[i] === "\n") { + fields.push(""); + i++; + break; + } + + if (text[i] === '"') { + // Quoted field + let value = ""; + i++; // skip opening quote + while (i < text.length) { + if (text[i] === '"') { + if (i + 1 < text.length && text[i + 1] === '"') { + value += '"'; + i += 2; + } else { + i++; // skip closing quote + break; + } + } else { + value += text[i]; + i++; + } + } + fields.push(value); + } else { + // Unquoted field + let value = ""; + while (i < text.length && text[i] !== "," && text[i] !== "\n") { + value += text[i]; + i++; + } + fields.push(value); + } + + if (i < text.length && text[i] === ",") { + i++; // skip comma + continue; + } + if (i < text.length && text[i] === "\n") { + i++; // skip newline + } + break; + } + + return { fields, nextPos: i }; +} + export async function execCommand(config: PgdevConfig, sql: string): Promise { const { cmd, env } = await buildPsqlArgs(config); cmd.push("-c", sql); diff --git a/src/commands/sync.test.ts b/src/commands/sync.test.ts index 1727f08..b8d4ccd 100644 --- a/src/commands/sync.test.ts +++ b/src/commands/sync.test.ts @@ -69,6 +69,26 @@ describe("parseRoutineGroups", () => { expect(allNames).not.toContain("products"); }); + test("excludes ACL lines by default (grants=false)", () => { + const tocWithAcl = ` +1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb +5800; 0 0 ACL inventory FUNCTION get_product(_product_id integer) shopdb +`; + const result = parseRoutineGroups(tocWithAcl); + expect(result[0].tocLines.length).toBe(1); + expect(result[0].tocLines[0]).toContain("FUNCTION"); + }); + + test("includes ACL lines when grants=true", () => { + const tocWithAcl = ` +1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb +5800; 0 0 ACL inventory FUNCTION get_product(_product_id integer) shopdb +`; + const result = parseRoutineGroups(tocWithAcl, true); + expect(result[0].tocLines.length).toBe(2); + expect(result[0].tocLines[1]).toContain("ACL"); + }); + test("returns empty array for TOC with no routines", () => { const empty = parseRoutineGroups(`; ; Archive header diff --git a/src/commands/sync.ts b/src/commands/sync.ts index aee5d0d..94315d9 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -23,7 +23,7 @@ interface RoutineGroup { tocLines: string[]; } -export function parseRoutineGroups(tocOutput: string): RoutineGroup[] { +export function parseRoutineGroups(tocOutput: string, includeGrants = false): RoutineGroup[] { const groups = new Map(); const groupOrder: string[] = []; @@ -51,10 +51,12 @@ export function parseRoutineGroups(tocOutput: string): RoutineGroup[] { } // ACL on routine: "5800; 0 0 ACL mathmodule FUNCTION auth_login(...) legendea" - const aclMatch = line.match(/^\d+;\s+0\s+0\s+ACL\s+\S+\s+(?:FUNCTION|PROCEDURE)\s+(\S+)\(/); - if (aclMatch) { - const name = aclMatch[1]; - groups.get(name)?.push(line); + if (includeGrants) { + const aclMatch = line.match(/^\d+;\s+0\s+0\s+ACL\s+\S+\s+(?:FUNCTION|PROCEDURE)\s+(\S+)\(/); + if (aclMatch) { + const name = aclMatch[1]; + groups.get(name)?.push(line); + } } } @@ -175,7 +177,7 @@ export async function syncCommand(config: PgdevConfig): Promise { const fullRoutinesDir = resolve(process.cwd(), routinesDir); mkdirSync(fullRoutinesDir, { recursive: true }); - const routineGroups = parseRoutineGroups(listStdout); + const routineGroups = parseRoutineGroups(listStdout, config.project.grants); if (routineGroups.length > 0) { const routineTocFile = resolve(tmpdir(), `pgdev-routine-toc-${Date.now()}.list`); diff --git a/src/config.ts b/src/config.ts index a0f5aff..45326c9 100644 --- a/src/config.ts +++ b/src/config.ts @@ -28,6 +28,8 @@ export interface ProjectConfig { migrations_dir: string; tests_dir: string; schemas: string[]; + grants: boolean; + ignore_body_whitespace: boolean; } export interface PgdevConfig { @@ -66,6 +68,8 @@ const defaults: PgdevConfig = { migrations_dir: "", tests_dir: "", schemas: [], + grants: false, + ignore_body_whitespace: false, }, verbose: true, }; @@ -137,6 +141,52 @@ export async function updateConfig(section: string, key: string, value: string): await Bun.write(path, content); } +export async function updateConfigBool(section: string, key: string, value: boolean): Promise { + const path = `${process.cwd()}/pgdev.toml`; + const file = Bun.file(path); + let content = (await file.exists()) ? await file.text() : ""; + + const newLine = `${key} = ${value}`; + const keyPattern = new RegExp(`^${key}\\s*=.*$`, "m"); + + if (!section) { + const firstSectionMatch = content.match(/^\[/m); + const topLevelEnd = firstSectionMatch?.index ?? content.length; + const topLevel = content.slice(0, topLevelEnd); + + if (keyPattern.test(topLevel)) { + content = topLevel.replace(keyPattern, newLine) + content.slice(topLevelEnd); + } else { + const suffix = topLevel.endsWith("\n") || topLevel === "" ? "" : "\n"; + content = topLevel + suffix + newLine + "\n" + content.slice(topLevelEnd); + } + } else { + const sectionHeader = `[${section}]`; + const sectionIndex = content.indexOf(sectionHeader); + if (sectionIndex !== -1) { + const afterSection = content.slice(sectionIndex + sectionHeader.length); + const nextSectionMatch = afterSection.match(/\n\[/); + const sectionEnd = nextSectionMatch + ? sectionIndex + sectionHeader.length + nextSectionMatch.index! + : content.length; + const sectionContent = content.slice(sectionIndex, sectionEnd); + + if (keyPattern.test(sectionContent)) { + const updated = sectionContent.replace(keyPattern, newLine); + content = content.slice(0, sectionIndex) + updated + content.slice(sectionEnd); + } else { + const insertPos = sectionIndex + sectionHeader.length; + content = content.slice(0, insertPos) + `\n${newLine}` + content.slice(insertPos); + } + } else { + const suffix = content.endsWith("\n") || content === "" ? "" : "\n"; + content += `${suffix}\n${sectionHeader}\n${newLine}\n`; + } + } + + await Bun.write(path, content); +} + function applyArrayUpdate(content: string, section: string, key: string, values: string[]): string { const tomlValue = values.length === 0 ? "[]" @@ -276,6 +326,8 @@ const EXPECTED_KEYS: { section: string; key: string; raw: string }[] = [ { section: "project", key: "migrations_dir", raw: 'migrations_dir = ""' }, { section: "project", key: "tests_dir", raw: 'tests_dir = ""' }, { section: "project", key: "schemas", raw: "schemas = []" }, + { section: "project", key: "grants", raw: "# Track GRANT/REVOKE statements for routines\ngrants = false" }, + { section: "project", key: "ignore_body_whitespace", raw: "# Ignore whitespace differences in routine bodies when comparing\nignore_body_whitespace = false" }, ]; const SECTION_COMMENTS: Record = { @@ -406,6 +458,10 @@ migrations_dir = "" tests_dir = "" # Schemas used by this project (empty = all non-system schemas) schemas = [] +# Track GRANT/REVOKE statements for routines +grants = false +# Ignore whitespace differences in routine bodies when comparing +ignore_body_whitespace = false `; await Bun.write(path, content); diff --git a/src/parser/catalog-tests/grants.test.ts b/src/parser/catalog-tests/grants.test.ts new file mode 100644 index 0000000..22378e6 --- /dev/null +++ b/src/parser/catalog-tests/grants.test.ts @@ -0,0 +1,104 @@ +import { beforeAll, describe, test, expect } from "bun:test"; +import { query } from "../../test/db.ts"; +import { parseRoutines } from "../routine.ts"; +import { catalogMetadataQuery, parseCatalogRows, type CatalogRow } from "../catalog.ts"; +import { grantsDiffer, grantsToAcl } from "../compare.ts"; + +const SETUP_SQL = ` +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'pgdev_test_role') THEN + CREATE ROLE pgdev_test_role; + END IF; +END $$; +`; + +const SQL = ` +CREATE FUNCTION test_schema.grant_fn() RETURNS text + LANGUAGE sql AS $$ SELECT 'granted'; $$; + +REVOKE ALL ON FUNCTION test_schema.grant_fn() FROM PUBLIC; +GRANT EXECUTE ON FUNCTION test_schema.grant_fn() TO pgdev_test_role; +`; + +const SQL_NO_GRANTS = ` +CREATE FUNCTION test_schema.no_grant_fn() RETURNS int + LANGUAGE sql AS $$ SELECT 1; $$; +`; + +beforeAll(async () => { + await query(SETUP_SQL); + await query(SQL); + await query(SQL_NO_GRANTS); +}); + +describe("grants — catalog integration", () => { + test("catalog has ACL for function with grants", async () => { + const rows = await query(catalogMetadataQuery(["test_schema"])); + const catalog = parseCatalogRows(rows); + const match = catalog.find((c) => c.name === "grant_fn")!; + + expect(match.acl).not.toBeNull(); + expect(match.acl!.length).toBeGreaterThan(0); + // Should contain the test role grant + const hasTestRole = match.acl!.some((a) => a.includes("pgdev_test_role")); + expect(hasTestRole).toBe(true); + }); + + test("catalog has null ACL for function with default permissions", async () => { + const rows = await query(catalogMetadataQuery(["test_schema"])); + const catalog = parseCatalogRows(rows); + const match = catalog.find((c) => c.name === "no_grant_fn")!; + + // Default permissions — proacl is NULL + expect(match.acl).toBeNull(); + }); + + test("grantsDiffer returns false when grants match", async () => { + const parsed = parseRoutines(SQL, { grants: true }); + const pGrantFn = parsed.find((r) => r.name === "grant_fn")!; + const rows = await query(catalogMetadataQuery(["test_schema"])); + const catalog = parseCatalogRows(rows); + const cGrantFn = catalog.find((c) => c.name === "grant_fn")!; + + expect(grantsDiffer(pGrantFn, cGrantFn)).toBe(false); + }); + + test("grantsDiffer returns false for no-grant function (both sides default)", async () => { + const parsed = parseRoutines(SQL_NO_GRANTS, { grants: true }); + const pNoGrant = parsed.find((r) => r.name === "no_grant_fn")!; + const rows = await query(catalogMetadataQuery(["test_schema"])); + const catalog = parseCatalogRows(rows); + const cNoGrant = catalog.find((c) => c.name === "no_grant_fn")!; + + expect(grantsDiffer(pNoGrant, cNoGrant)).toBe(false); + }); + + test("grantsDiffer detects when file has grants but db does not", async () => { + const rows = await query(catalogMetadataQuery(["test_schema"])); + const catalog = parseCatalogRows(rows); + const cNoGrant = catalog.find((c) => c.name === "no_grant_fn")!; + + const altSql = ` +CREATE FUNCTION test_schema.no_grant_fn() RETURNS int + LANGUAGE sql AS $$ SELECT 1; $$; + +REVOKE ALL ON FUNCTION test_schema.no_grant_fn() FROM PUBLIC; +GRANT EXECUTE ON FUNCTION test_schema.no_grant_fn() TO pgdev_test_role; +`; + const [pAlt] = parseRoutines(altSql, { grants: true }); + expect(grantsDiffer(pAlt, cNoGrant)).toBe(true); + }); + + test("grantsDiffer detects when db has grants but file does not", async () => { + const rows = await query(catalogMetadataQuery(["test_schema"])); + const catalog = parseCatalogRows(rows); + const cGrantFn = catalog.find((c) => c.name === "grant_fn")!; + + const altSql = ` +CREATE FUNCTION test_schema.grant_fn() RETURNS text + LANGUAGE sql AS $$ SELECT 'granted'; $$; +`; + const [pAlt] = parseRoutines(altSql, { grants: true }); + expect(grantsDiffer(pAlt, cGrantFn)).toBe(true); + }); +}); diff --git a/src/parser/catalog.ts b/src/parser/catalog.ts index 3dfa200..7234267 100644 --- a/src/parser/catalog.ts +++ b/src/parser/catalog.ts @@ -1,5 +1,5 @@ import { type PgdevConfig } from "../config.ts"; -import { runPsqlQuery } from "../commands/exec.ts"; +import { runPsqlCsvQuery } from "../commands/exec.ts"; export interface CatalogRoutine { schema: string; @@ -18,6 +18,7 @@ export interface CatalogRoutine { rows: number; config: string[]; comment: string | null; + acl: string[] | null; } /** Raw row shape returned by catalogMetadataQuery(). */ @@ -42,6 +43,7 @@ export interface CatalogRow { rows: number; config: string[] | null; comment: string | null; + acl: string[] | null; } const VOLATILITY_MAP: Record = { @@ -78,7 +80,8 @@ export function catalogMetadataQuery(schemas: string[]): string { " p.procost::real AS cost,", " p.prorows::real AS rows,", " p.proconfig AS config,", - " obj_description(p.oid, 'pg_proc') AS comment", + " obj_description(p.oid, 'pg_proc') AS comment,", + " p.proacl AS acl", "FROM pg_proc p", "JOIN pg_namespace n ON n.oid = p.pronamespace", "JOIN pg_language l ON l.oid = p.prolang", @@ -112,6 +115,7 @@ export function parseCatalogRows(rows: CatalogRow[]): CatalogRoutine[] { rows: row.rows, config: row.config ?? [], comment: row.comment ?? null, + acl: row.acl ?? null, }; map.set(row.routine_oid, routine); } @@ -141,53 +145,56 @@ export function normalizeBody(body: string): string { .trim(); } +/** Normalize body ignoring all whitespace: lowercase, strip non-printable, remove all whitespace. */ +export function normalizeBodyNoWhitespace(body: string): string { + return body + .toLowerCase() + .replace(/[^\x20-\x7e]/g, "") + .replace(/\s/g, "") + .trim(); +} + /** Hash a normalized body string (SHA-256, hex). */ -export function bodyHash(body: string): string { +export function bodyHash(body: string, ignoreWhitespace = false): string { const hasher = new Bun.CryptoHasher("sha256"); - hasher.update(normalizeBody(body)); + hasher.update(ignoreWhitespace ? normalizeBodyNoWhitespace(body) : normalizeBody(body)); return hasher.digest("hex"); } -/** Production execution via psql. */ +/** Production execution via psql (CSV mode for safe parsing of bodies containing pipes/newlines). */ export async function fetchCatalogMetadata(config: PgdevConfig): Promise { const schemas = config.project.schemas; if (schemas.length === 0) return []; const sql = catalogMetadataQuery(schemas); - const result = await runPsqlQuery(config, sql); + const result = await runPsqlCsvQuery(config, sql); if (!result.ok) { throw new Error(`Catalog query failed: ${result.error}`); } - const rows: CatalogRow[] = result.rows.map((line) => { - const [ - schema, name, type, oid, ord, paramName, paramType, - returnType, returnSetof, body, language, volatility, - strict, securityDefiner, parallel, leakproof, cost, rows, config, comment, - ] = line.split("|"); - return { - schema, - name, - type, - routine_oid: Number(oid), - param_ord: ord ? Number(ord) : null, - param_name: paramName || null, - param_type: paramType || null, - return_type: returnType || null, - return_setof: returnSetof === "t", - body: body || null, - language, - volatility, - strict: strict === "t", - security_definer: securityDefiner === "t", - parallel, - leakproof: leakproof === "t", - cost: Number(cost), - rows: Number(rows), - config: parsePgArray(config), - comment: comment || null, - }; - }); + const rows: CatalogRow[] = result.rows.map((r) => ({ + schema: r.schema, + name: r.name, + type: r.type, + routine_oid: Number(r.routine_oid), + param_ord: r.param_ord ? Number(r.param_ord) : null, + param_name: r.param_name || null, + param_type: r.param_type || null, + return_type: r.return_type || null, + return_setof: r.return_setof === "t", + body: r.body || null, + language: r.language, + volatility: r.volatility, + strict: r.strict === "t", + security_definer: r.security_definer === "t", + parallel: r.parallel, + leakproof: r.leakproof === "t", + cost: Number(r.cost), + rows: Number(r.rows), + config: parsePgArray(r.config), + comment: r.comment || null, + acl: r.acl ? parsePgArray(r.acl) : null, + })); return parseCatalogRows(rows); } diff --git a/src/parser/compare.ts b/src/parser/compare.ts index 944c8b0..574e79f 100644 --- a/src/parser/compare.ts +++ b/src/parser/compare.ts @@ -1,7 +1,37 @@ -import type { ParsedRoutine } from "./routine.ts"; +import type { ParsedRoutine, RoutineGrant } from "./routine.ts"; import type { CatalogRoutine } from "./catalog.ts"; import { bodyHash } from "./catalog.ts"; +/** + * Map of common PostgreSQL type aliases to their canonical names + * (as returned by format_type()). + */ +const TYPE_ALIASES: Record = { + int: "integer", + int4: "integer", + int2: "smallint", + int8: "bigint", + float4: "real", + float8: "double precision", + bool: "boolean", + varchar: "character varying", + char: "character", + timestamptz: "timestamp with time zone", + timetz: "time with time zone", + serial: "integer", + serial4: "integer", + bigserial: "bigint", + serial8: "bigint", + smallserial: "smallint", + serial2: "smallint", +}; + +/** Normalize a SQL type to its canonical form (as returned by format_type). */ +export function normalizeType(type: string): string { + const lower = type.toLowerCase().trim(); + return TYPE_ALIASES[lower] ?? lower; +} + /** * PostgreSQL default values for routine attributes when not explicitly specified. */ @@ -73,8 +103,8 @@ export function attributesToCatalog(parsed: ParsedRoutine): ExpectedAttributes { const costAttr = attrs.find((a) => /^COST\s/i.test(a)); const cost = costAttr ? Number(costAttr.split(/\s+/)[1]) : PG_DEFAULTS.cost; - // Rows — default depends on whether function returns SETOF - const isSetof = parsed.returns?.setof ?? false; + // Rows — default depends on whether function returns SETOF (RETURNS TABLE is also setof) + const isSetof = (parsed.returns?.setof ?? false) || parsed.returns?.table != null; const rowsAttr = attrs.find((a) => /^ROWS\s/i.test(a)); const rows = rowsAttr ? Number(rowsAttr.split(/\s+/)[1]) @@ -101,7 +131,11 @@ export function attributesToCatalog(parsed: ParsedRoutine): ExpectedAttributes { * Compare a parsed routine (from SQL file) with a catalog routine (from pg_catalog). * Returns true if they differ and the database needs updating. */ -export function routinesDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): boolean { +export interface DiffOptions { + ignoreBodyWhitespace?: boolean; +} + +export function routinesDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine, options?: DiffOptions): boolean { // Type if (parsed.type !== catalog.type) return true; @@ -109,7 +143,7 @@ export function routinesDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): if (parsed.parameters.length !== catalog.parameters.length) return true; for (let i = 0; i < parsed.parameters.length; i++) { if (parsed.parameters[i].name !== catalog.parameters[i].name) return true; - if (parsed.parameters[i].type.toLowerCase() !== catalog.parameters[i].type.toLowerCase()) + if (normalizeType(parsed.parameters[i].type) !== normalizeType(catalog.parameters[i].type)) return true; } @@ -117,7 +151,7 @@ export function routinesDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): if (returnsDiffer(parsed, catalog)) return true; // Body - if (bodyDiffers(parsed.body, catalog.body)) return true; + if (bodyDiffers(parsed.body, catalog.body, options?.ignoreBodyWhitespace)) return true; // Attributes if (attributesDiffer(parsed, catalog)) return true; @@ -136,6 +170,74 @@ export function commentsDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): return pc !== cc; } +/** + * Convert parsed GRANT/REVOKE statements into a set of PostgreSQL ACL entries. + * pg_dump always outputs REVOKE ALL first, then explicit GRANTs, producing + * a deterministic final state. We replay the statements in order. + * + * ACL entry format: "grantee=privs/grantor" where: + * - X = EXECUTE + * - empty grantee = PUBLIC + * - * suffix = WITH GRANT OPTION + */ +export function grantsToAcl(grants: RoutineGrant[], owner: string): string[] { + // Track who has EXECUTE. Start empty (pg_dump always begins with REVOKE ALL) + const acl = new Map(); + + for (const g of grants) { + const grantee = g.grantee.toUpperCase() === "PUBLIC" ? "" : g.grantee; + if (g.isGrant) { + acl.set(grantee, true); + } else { + // REVOKE + if (g.grantee.toUpperCase() === "PUBLIC" && g.privilege === "ALL") { + // REVOKE ALL FROM PUBLIC — clear PUBLIC + acl.delete(""); + } else { + acl.delete(grantee); + } + } + } + + return [...acl.keys()] + .sort() + .map((grantee) => `${grantee}=X/${owner}`); +} + +/** + * Compare grants/ACLs between a parsed routine and a catalog routine. + * Returns true if they differ. Separate from routinesDiffer because + * grant changes use GRANT/REVOKE statements (no routine re-creation needed). + */ +export function grantsDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): boolean { + // If no grants parsed and catalog has null ACL, they match (default permissions) + if (parsed.grants.length === 0 && catalog.acl == null) return false; + + // If parsed has no grants but catalog has explicit ACL (or vice versa) + if (parsed.grants.length === 0 && catalog.acl != null) return true; + if (parsed.grants.length > 0 && catalog.acl == null) return true; + + // Extract owner from catalog ACL (format: "grantee=privs/grantor") + const ownerMatch = catalog.acl![0]?.match(/\/(\w+)$/); + const owner = ownerMatch ? ownerMatch[1] : ""; + + // Filter out owner's self-grant from catalog ACL — the owner always retains + // EXECUTE and pg_dump includes an explicit "GRANT ... TO owner" line, but + // user-written SQL typically omits it. Compare only non-owner entries. + const ownerEntry = `${owner}=X/${owner}`; + const actual = [...(catalog.acl ?? [])] + .filter((a) => a !== ownerEntry) + .sort(); + + const expected = grantsToAcl(parsed.grants, owner); + + if (expected.length !== actual.length) return true; + for (let i = 0; i < expected.length; i++) { + if (expected[i] !== actual[i]) return true; + } + return false; +} + function returnsDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): boolean { const pr = parsed.returns; const cr = catalog.returns; @@ -153,15 +255,15 @@ function returnsDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): boolean // Scalar / SETOF type if (pr.setof !== cr.setof) return true; - if (pr.type?.toLowerCase() !== cr.type?.toLowerCase()) return true; + if (normalizeType(pr.type ?? "") !== normalizeType(cr.type ?? "")) return true; return false; } -function bodyDiffers(parsedBody: string | null, catalogBody: string | null): boolean { +function bodyDiffers(parsedBody: string | null, catalogBody: string | null, ignoreWhitespace = false): boolean { if (parsedBody == null && catalogBody == null) return false; if (parsedBody == null || catalogBody == null) return true; - return bodyHash(parsedBody) !== bodyHash(catalogBody); + return bodyHash(parsedBody, ignoreWhitespace) !== bodyHash(catalogBody, ignoreWhitespace); } function attributesDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): boolean { diff --git a/src/parser/parser-tests/normalize-type.test.ts b/src/parser/parser-tests/normalize-type.test.ts new file mode 100644 index 0000000..73e3ea3 --- /dev/null +++ b/src/parser/parser-tests/normalize-type.test.ts @@ -0,0 +1,216 @@ +import { describe, test, expect } from "bun:test"; +import { normalizeType, attributesToCatalog, routinesDiffer } from "../compare.ts"; +import { parseRoutines } from "../routine.ts"; +import type { CatalogRoutine } from "../catalog.ts"; + +describe("normalizeType", () => { + test("int → integer", () => { + expect(normalizeType("int")).toBe("integer"); + }); + + test("int4 → integer", () => { + expect(normalizeType("int4")).toBe("integer"); + }); + + test("int2 → smallint", () => { + expect(normalizeType("int2")).toBe("smallint"); + }); + + test("int8 → bigint", () => { + expect(normalizeType("int8")).toBe("bigint"); + }); + + test("float4 → real", () => { + expect(normalizeType("float4")).toBe("real"); + }); + + test("float8 → double precision", () => { + expect(normalizeType("float8")).toBe("double precision"); + }); + + test("bool → boolean", () => { + expect(normalizeType("bool")).toBe("boolean"); + }); + + test("varchar → character varying", () => { + expect(normalizeType("varchar")).toBe("character varying"); + }); + + test("char → character", () => { + expect(normalizeType("char")).toBe("character"); + }); + + test("timestamptz → timestamp with time zone", () => { + expect(normalizeType("timestamptz")).toBe("timestamp with time zone"); + }); + + test("timetz → time with time zone", () => { + expect(normalizeType("timetz")).toBe("time with time zone"); + }); + + test("serial → integer", () => { + expect(normalizeType("serial")).toBe("integer"); + }); + + test("bigserial → bigint", () => { + expect(normalizeType("bigserial")).toBe("bigint"); + }); + + test("case insensitive", () => { + expect(normalizeType("INT")).toBe("integer"); + expect(normalizeType("Bool")).toBe("boolean"); + expect(normalizeType("VARCHAR")).toBe("character varying"); + }); + + test("already canonical types pass through", () => { + expect(normalizeType("integer")).toBe("integer"); + expect(normalizeType("text")).toBe("text"); + expect(normalizeType("boolean")).toBe("boolean"); + expect(normalizeType("jsonb")).toBe("jsonb"); + expect(normalizeType("uuid")).toBe("uuid"); + }); + + test("trims whitespace", () => { + expect(normalizeType(" int ")).toBe("integer"); + }); +}); + +describe("routinesDiffer — type alias normalization", () => { + function makeCatalog(params: { name: string | null; type: string }[], returnType: string, body = " SELECT 1; "): CatalogRoutine { + return { + schema: "public", + name: "test_fn", + type: "function", + parameters: params, + returns: { setof: false, type: returnType }, + body, + language: "sql", + volatility: "volatile", + strict: false, + securityDefiner: false, + parallel: "unsafe", + leakproof: false, + cost: 100, + rows: 0, + config: [], + comment: null, + acl: null, + }; + } + + test("int param matches integer in catalog", () => { + const sql = `CREATE FUNCTION public.test_fn(_a int) RETURNS integer LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "integer" }], "integer"); + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("varchar param matches character varying in catalog", () => { + const sql = `CREATE FUNCTION public.test_fn(_a varchar) RETURNS text LANGUAGE sql AS $$ SELECT 'x'; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "character varying" }], "text", " SELECT 'x'; "); + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("bool param matches boolean in catalog", () => { + const sql = `CREATE FUNCTION public.test_fn(_a bool) RETURNS bool LANGUAGE sql AS $$ SELECT true; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "boolean" }], "boolean", " SELECT true; "); + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("timestamptz matches timestamp with time zone", () => { + const sql = `CREATE FUNCTION public.test_fn(_a timestamptz) RETURNS timestamptz LANGUAGE sql AS $$ SELECT now(); $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "timestamp with time zone" }], "timestamp with time zone", " SELECT now(); "); + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("mixed aliases — int, bool, varchar all match canonical", () => { + const sql = `CREATE FUNCTION public.test_fn(_a int, _b bool, _c varchar) RETURNS int LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "integer" }, { name: "_b", type: "boolean" }, { name: "_c", type: "character varying" }], "integer"); + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("float8 return matches double precision", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS float8 LANGUAGE sql AS $$ SELECT 1.0; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([], "double precision", " SELECT 1.0; "); + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("actually different types still detected", () => { + const sql = `CREATE FUNCTION public.test_fn(_a text) RETURNS integer LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "integer" }], "integer", " SELECT 1; "); + expect(routinesDiffer(parsed, catalog)).toBe(true); + }); + + test("RETURNS TABLE matches catalog setof record with rows=1000", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS TABLE(id integer, name text) + LANGUAGE sql AS $$ SELECT 1, 'a'; $$;`; + const [parsed] = parseRoutines(sql); + // Catalog represents RETURNS TABLE as {setof: true, type: "record"} + const catalog: CatalogRoutine = { + schema: "public", + name: "test_fn", + type: "function", + parameters: [], + returns: { setof: true, type: "record" }, + body: " SELECT 1, 'a'; ", + language: "sql", + volatility: "volatile", + strict: false, + securityDefiner: false, + parallel: "unsafe", + leakproof: false, + cost: 100, + rows: 1000, + config: [], + comment: null, + acl: null, + }; + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); + + test("RETURNS TABLE uses setof default for rows attribute", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS TABLE(id integer) + LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const expected = attributesToCatalog(parsed); + expect(expected.rows).toBe(1000); + }); + + test("RETURNS SETOF uses setof default for rows attribute", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS SETOF integer + LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const expected = attributesToCatalog(parsed); + expect(expected.rows).toBe(1000); + }); + + test("scalar return uses scalar default for rows attribute", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS integer + LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const expected = attributesToCatalog(parsed); + expect(expected.rows).toBe(0); + }); + + test("ignoreBodyWhitespace: space around punctuation not detected", () => { + const sql = `CREATE FUNCTION public.test_fn(_a int) RETURNS integer LANGUAGE sql AS $$ SELECT fn(_a, 1); $$;`; + const [parsed] = parseRoutines(sql); + // Catalog body has different spacing around parens/comma + const catalog = makeCatalog([{ name: "_a", type: "integer" }], "integer", " SELECT fn( _a,1 ); "); + expect(routinesDiffer(parsed, catalog)).toBe(true); // strict: different + expect(routinesDiffer(parsed, catalog, { ignoreBodyWhitespace: true })).toBe(false); // ignore: same + }); + + test("ignoreBodyWhitespace: actual code change still detected", () => { + const sql = `CREATE FUNCTION public.test_fn(_a int) RETURNS integer LANGUAGE sql AS $$ SELECT _a + 1; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([{ name: "_a", type: "integer" }], "integer", " SELECT _a + 2; "); + expect(routinesDiffer(parsed, catalog, { ignoreBodyWhitespace: true })).toBe(true); + }); +}); diff --git a/src/parser/parser-tests/routine-body-hash.test.ts b/src/parser/parser-tests/routine-body-hash.test.ts index ac9a41a..8128765 100644 --- a/src/parser/parser-tests/routine-body-hash.test.ts +++ b/src/parser/parser-tests/routine-body-hash.test.ts @@ -1,5 +1,5 @@ import { describe, test, expect } from "bun:test"; -import { normalizeBody, bodyHash } from "../catalog.ts"; +import { normalizeBody, normalizeBodyNoWhitespace, bodyHash } from "../catalog.ts"; describe("normalizeBody", () => { test("lowercases content", () => { @@ -48,4 +48,37 @@ describe("bodyHash", () => { const hash = bodyHash("select 1"); expect(hash).toMatch(/^[0-9a-f]{64}$/); }); + + test("ignoreWhitespace: spaces around punctuation don't matter", () => { + const a = "select fn(type, success)"; + const b = "select fn( type,success )"; + expect(bodyHash(a)).not.toBe(bodyHash(b)); // strict mode: different + expect(bodyHash(a, true)).toBe(bodyHash(b, true)); // ignore mode: same + }); + + test("ignoreWhitespace: line break inside expression doesn't matter", () => { + const a = "select fn(type, success)"; + const b = "select fn(type,\nsuccess)"; + expect(bodyHash(a, true)).toBe(bodyHash(b, true)); + }); + + test("ignoreWhitespace: actual code change still detected", () => { + const a = "select fn(type, success)"; + const b = "select fn(type, failure)"; + expect(bodyHash(a, true)).not.toBe(bodyHash(b, true)); + }); +}); + +describe("normalizeBodyNoWhitespace", () => { + test("removes all whitespace", () => { + expect(normalizeBodyNoWhitespace("select _a + _b")).toBe("select_a+_b"); + }); + + test("lowercases", () => { + expect(normalizeBodyNoWhitespace("SELECT 1")).toBe("select1"); + }); + + test("strips non-printable characters", () => { + expect(normalizeBodyNoWhitespace("select\x001")).toBe("select1"); + }); }); diff --git a/src/parser/parser-tests/routine-grants.test.ts b/src/parser/parser-tests/routine-grants.test.ts new file mode 100644 index 0000000..c7865ef --- /dev/null +++ b/src/parser/parser-tests/routine-grants.test.ts @@ -0,0 +1,173 @@ +import { describe, test, expect } from "bun:test"; +import { parseRoutines } from "../routine.ts"; +import { grantsToAcl } from "../compare.ts"; + +describe("parseRoutines — grant extraction", () => { + test("extracts GRANT EXECUTE on function", () => { + const sql = ` +CREATE FUNCTION app.greet(_name text) RETURNS text + LANGUAGE sql AS $$ SELECT 'hello ' || _name; $$; + +GRANT EXECUTE ON FUNCTION app.greet(text) TO web_user; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + expect(r.grants[0]).toEqual({ privilege: "EXECUTE", grantee: "web_user", isGrant: true }); + }); + + test("grants is empty when grants option is false (default)", () => { + const sql = ` +CREATE FUNCTION app.greet(_name text) RETURNS text + LANGUAGE sql AS $$ SELECT 'hello ' || _name; $$; + +GRANT EXECUTE ON FUNCTION app.greet(text) TO web_user; +`; + const [r] = parseRoutines(sql); + expect(r.grants).toEqual([]); + }); + + test("extracts REVOKE ALL FROM PUBLIC", () => { + const sql = ` +CREATE FUNCTION app.greet() RETURNS text + LANGUAGE sql AS $$ SELECT 'hi'; $$; + +REVOKE ALL ON FUNCTION app.greet() FROM PUBLIC; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + expect(r.grants[0]).toEqual({ privilege: "ALL", grantee: "PUBLIC", isGrant: false }); + }); + + test("extracts multiple GRANT/REVOKE statements", () => { + const sql = ` +CREATE FUNCTION app.greet() RETURNS text + LANGUAGE sql AS $$ SELECT 'hi'; $$; + +REVOKE ALL ON FUNCTION app.greet() FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app.greet() TO web_user; +GRANT EXECUTE ON FUNCTION app.greet() TO api_role; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(3); + expect(r.grants[0].isGrant).toBe(false); + expect(r.grants[1].grantee).toBe("web_user"); + expect(r.grants[2].grantee).toBe("api_role"); + }); + + test("matches by parameter types (ignores names)", () => { + const sql = ` +CREATE FUNCTION app.add(a integer, b integer) RETURNS integer + LANGUAGE sql AS $$ SELECT a + b; $$; + +GRANT EXECUTE ON FUNCTION app.add(integer, integer) TO calc_role; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + expect(r.grants[0].grantee).toBe("calc_role"); + }); + + test("handles pg_dump style with param names in GRANT", () => { + const sql = ` +CREATE FUNCTION app.add(a integer, b integer) RETURNS integer + LANGUAGE sql AS $$ SELECT a + b; $$; + +GRANT EXECUTE ON FUNCTION app.add(a integer, b integer) TO calc_role; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + expect(r.grants[0].grantee).toBe("calc_role"); + }); + + test("each routine gets its own grants", () => { + const sql = ` +CREATE FUNCTION app.one() RETURNS int + LANGUAGE sql AS $$ SELECT 1; $$; + +GRANT EXECUTE ON FUNCTION app.one() TO role_a; + +CREATE FUNCTION app.two() RETURNS int + LANGUAGE sql AS $$ SELECT 2; $$; + +GRANT EXECUTE ON FUNCTION app.two() TO role_b; +`; + const results = parseRoutines(sql, { grants: true }); + expect(results[0].grants).toHaveLength(1); + expect(results[0].grants[0].grantee).toBe("role_a"); + expect(results[1].grants).toHaveLength(1); + expect(results[1].grants[0].grantee).toBe("role_b"); + }); + + test("routine without grants has empty array when grants enabled", () => { + const sql = ` +CREATE FUNCTION app.one() RETURNS int + LANGUAGE sql AS $$ SELECT 1; $$; + +CREATE FUNCTION app.two() RETURNS int + LANGUAGE sql AS $$ SELECT 2; $$; + +GRANT EXECUTE ON FUNCTION app.two() TO role_b; +`; + const results = parseRoutines(sql, { grants: true }); + expect(results[0].grants).toEqual([]); + expect(results[1].grants).toHaveLength(1); + }); + + test("handles GRANT on procedure", () => { + const sql = ` +CREATE PROCEDURE app.cleanup() + LANGUAGE sql AS $$ SELECT 1; $$; + +GRANT EXECUTE ON PROCEDURE app.cleanup() TO admin_role; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + expect(r.grants[0].grantee).toBe("admin_role"); + }); + + test("case-insensitive GRANT/REVOKE matching", () => { + const sql = ` +CREATE FUNCTION app.greet() RETURNS text + LANGUAGE sql AS $$ SELECT 'hi'; $$; + +grant execute on function app.greet() to web_user; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + }); + + test("handles GRANT ALL PRIVILEGES", () => { + const sql = ` +CREATE FUNCTION app.greet() RETURNS text + LANGUAGE sql AS $$ SELECT 'hi'; $$; + +GRANT ALL PRIVILEGES ON FUNCTION app.greet() TO superuser; +`; + const [r] = parseRoutines(sql, { grants: true }); + expect(r.grants).toHaveLength(1); + expect(r.grants[0].privilege).toBe("ALL"); + }); +}); + +describe("grantsToAcl", () => { + test("pg_dump style: REVOKE ALL + explicit GRANTs", () => { + const grants = [ + { privilege: "ALL" as const, grantee: "PUBLIC", isGrant: false }, + { privilege: "EXECUTE" as const, grantee: "web_user", isGrant: true }, + { privilege: "EXECUTE" as const, grantee: "api_role", isGrant: true }, + ]; + const acl = grantsToAcl(grants, "postgres"); + expect(acl).toEqual(["api_role=X/postgres", "web_user=X/postgres"]); + }); + + test("GRANT to PUBLIC", () => { + const grants = [ + { privilege: "EXECUTE" as const, grantee: "PUBLIC", isGrant: true }, + ]; + const acl = grantsToAcl(grants, "owner"); + expect(acl).toEqual(["=X/owner"]); + }); + + test("empty grants produces empty ACL", () => { + expect(grantsToAcl([], "owner")).toEqual([]); + }); +}); diff --git a/src/parser/routine.ts b/src/parser/routine.ts index e83601a..96c4c41 100644 --- a/src/parser/routine.ts +++ b/src/parser/routine.ts @@ -17,6 +17,12 @@ export interface RoutineReturn { table: TableColumn[] | null; } +export interface RoutineGrant { + privilege: "EXECUTE" | "ALL"; + grantee: string; + isGrant: boolean; // true = GRANT, false = REVOKE +} + export interface ParsedRoutine { name: string; type: "function" | "procedure"; @@ -26,6 +32,7 @@ export interface ParsedRoutine { attributes: string[]; body: string | null; comment: string | null; + grants: RoutineGrant[]; } /** @@ -387,6 +394,40 @@ function parseComments(commentStripped: string): Map { return map; } +/** + * Match GRANT/REVOKE on FUNCTION/PROCEDURE. + * GRANT EXECUTE ON FUNCTION [schema.]name(params) TO role; + * REVOKE ALL ON FUNCTION [schema.]name(params) FROM role; + */ +const GRANT_REVOKE_RE = + /\b(GRANT|REVOKE)\s+(EXECUTE|ALL(?:\s+PRIVILEGES)?)\s+ON\s+(FUNCTION|PROCEDURE)\s+(?:([a-zA-Z_]\w*)\.)?([a-zA-Z_]\w*)\s*\(([^)]*)\)\s+(?:TO|FROM)\s+([^;]+?)\s*;/gi; + +function parseGrants(commentStripped: string): Map { + const map = new Map(); + let m: RegExpExecArray | null; + const re = new RegExp(GRANT_REVOKE_RE.source, GRANT_REVOKE_RE.flags); + while ((m = re.exec(commentStripped)) !== null) { + const isGrant = m[1].toUpperCase() === "GRANT"; + const privilege = m[2].toUpperCase().startsWith("ALL") ? "ALL" : "EXECUTE"; + const type = m[3].toLowerCase(); + const schema = m[4] ?? ""; + const name = m[5]; + const params = m[6] + .split(",") + .map((p) => p.trim()) + .filter(Boolean) + .map((p) => parseOneParam(p).type.toLowerCase()) + .join(","); + const grantee = m[7].trim(); + + const key = `${type}:${schema}.${name}(${params})`; + const list = map.get(key) ?? []; + list.push({ privilege: privilege as "EXECUTE" | "ALL", grantee, isGrant }); + map.set(key, list); + } + return map; +} + /** * Build a comment lookup key from a ParsedRoutine. */ @@ -397,12 +438,13 @@ function commentKey(r: { type: string; schema: string | null; name: string; para return `${r.type}:${r.schema ?? ""}.${r.name}(${params})`; } -export function parseRoutines(content: string): ParsedRoutine[] { +export function parseRoutines(content: string, options?: { grants?: boolean }): ParsedRoutine[] { if (!content.trim()) return []; const commentStripped = stripComments(content); const cleaned = stripDollarBodies(commentStripped); const comments = parseComments(commentStripped); + const grantMap = options?.grants ? parseGrants(commentStripped) : null; const routines: ParsedRoutine[] = []; let match: RegExpExecArray | null; @@ -424,10 +466,14 @@ export function parseRoutines(content: string): ParsedRoutine[] { attributes, body, comment: null, + grants: [], }; const key = commentKey(routine); routine.comment = comments.get(key) ?? null; + if (grantMap) { + routine.grants = grantMap.get(key) ?? []; + } routines.push(routine); } diff --git a/src/test/db.ts b/src/test/db.ts index 8507242..d44000e 100644 --- a/src/test/db.ts +++ b/src/test/db.ts @@ -18,15 +18,14 @@ export async function loadTestConfig(): Promise { const envFile = resolve(import.meta.dir, "../../test.env"); const fileVars = await loadEnvFile(envFile); - const get = (key: string, fallback: string) => - fileVars[key] ?? process.env[key] ?? fallback; - + // Only use test.env for config — never fall through to process.env + // to prevent accidentally dropping a real database (e.g. from .env) cachedConfig = { - host: get("PGHOST", "localhost"), - port: get("PGPORT", "5432"), - user: get("PGUSER", "postgres"), - password: get("PGPASSWORD", "postgres"), - database: get("PGDATABASE", "pgdev_test"), + host: fileVars.PGHOST ?? "localhost", + port: fileVars.PGPORT ?? "5432", + user: fileVars.PGUSER ?? "postgres", + password: fileVars.PGPASSWORD ?? "postgres", + database: fileVars.PGDATABASE ?? "pgdev_test", }; return cachedConfig; } From 682010aa3f1aa1f175f03b95a670ff2edce26a90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 12 Mar 2026 14:10:59 +0100 Subject: [PATCH 2/9] Add sync command, formatter, configurable skip prefixes, and TUI dashboard reorganization - Add sync command to dump database routines to formatted SQL files - Add SQL formatter with DROP IF EXISTS, CREATE OR REPLACE, and extensive options - Add directory grouping by API/internal type and by name segment - Replace skip_generic_prefixes boolean with configurable skip_prefixes array - Add exec command, env utilities, file helpers, and parser improvements - Reorganize config TUI dashboard into logical sections (Project, Diff, Sync, Format) Co-Authored-By: Claude Opus 4.6 --- src/cli.ts | 6 +- src/commands/config.ts | 225 +++++++++- src/commands/diff.ts | 19 +- src/commands/exec.ts | 6 +- src/commands/sync.ts | 90 +++- src/config.ts | 141 ++++++ src/parser/catalog-tests/begin-atomic.test.ts | 5 +- .../body-formatting-diff.test.ts | 6 +- src/parser/catalog.ts | 8 +- src/parser/formatter.ts | 353 +++++++++++++++ src/parser/parser-tests/formatter.test.ts | 421 ++++++++++++++++++ .../parser-tests/routine-body-hash.test.ts | 36 +- .../parser-tests/routine-handwritten.test.ts | 18 +- .../parser-tests/routine-params.test.ts | 88 ++-- src/parser/routine.ts | 22 +- src/test/db.ts | 63 ++- src/utils/env.test.ts | 65 +++ src/utils/env.ts | 17 +- src/utils/files.ts | 16 + 19 files changed, 1488 insertions(+), 117 deletions(-) create mode 100644 src/parser/formatter.ts create mode 100644 src/parser/parser-tests/formatter.test.ts create mode 100644 src/utils/env.test.ts create mode 100644 src/utils/files.ts diff --git a/src/cli.ts b/src/cli.ts index 82d3ec3..0917c27 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -12,7 +12,7 @@ import { syncCommand } from "./commands/sync.ts"; import { diffCommand } from "./commands/diff.ts"; import { loadConfig, ensureConfigFile, isSharedConnection, type PgdevConfig } from "./config.ts"; import { readJsonConfig } from "./utils/json.ts"; -import { resolveEnvVars, loadEnvFile } from "./utils/env.ts"; +import { resolvePlaceholders, loadEnvFile } from "./utils/env.ts"; export function splitCommand(command: string): string[] { return command.trim().split(/\s+/); @@ -358,7 +358,7 @@ async function printStatus(): Promise { } for (const [connName, connStr] of Object.entries(connStrings)) { - const { resolved } = resolveEnvVars(connStr, envDict); + const { resolved } = resolvePlaceholders(connStr, envDict); const parsed: Record = {}; for (const part of resolved.split(";")) { const eq = part.indexOf("="); @@ -433,7 +433,7 @@ ${pc.bold("Commands:")} diff Compare project routines with database exec Execute SQL command via psql psql Open interactive psql session - sync Dump database schema to migrations directory + sync Sync database routines and schema to project files update Update ${PACKAGE_NAME} to the latest version `; diff --git a/src/commands/config.ts b/src/commands/config.ts index 9f8ae23..3749ddf 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -1,12 +1,12 @@ import { $ } from "bun"; import { statSync, readdirSync, mkdirSync } from "node:fs"; import { resolve, dirname } from "node:path"; -import { loadConfig, type PgdevConfig, updateConfig, updateConfigBool, updateConfigArraySync, removeConfigKey, isSharedConnection } from "../config.ts"; +import { loadConfig, type PgdevConfig, updateConfig, updateConfigBool, updateConfigInt, updateConfigArraySync, removeConfigKey, isSharedConnection } from "../config.ts"; import { success, error, pc, formatCmd, spinner } from "../utils/terminal.ts"; import { ask, askConfirm, askValue, askPath, askDashboard, askMultiSelect } from "../utils/prompt.ts"; import { readJsonConfig, writeJsonConfig } from "../utils/json.ts"; import { splitCommand } from "../cli.ts"; -import { resolveEnvVars, loadEnvFile, buildPgdevEnvDict } from "../utils/env.ts"; +import { resolvePlaceholders, loadEnvFile, buildPgdevEnvDict } from "../utils/env.ts"; import { runPsqlQuery } from "./exec.ts"; import { setupNpgsqlRest, setupPostgresTools } from "./setup.ts"; import { detectNpgsqlRest, detectPgTools, type PgInstallation } from "../utils/tools.ts"; @@ -768,7 +768,7 @@ interface ConnectionFields { } function resolveConnectionField(value: string, envDict: Record, warnings: string[]): string { - const { resolved, unresolved } = resolveEnvVars(value, envDict); + const { resolved, unresolved } = resolvePlaceholders(value, envDict); if (unresolved.length > 0) { warnings.push(`Unresolved: ${unresolved.join(", ")}`); } @@ -1676,7 +1676,7 @@ async function testPgdevConnection(config: PgdevConfig): Promise { Object.assign(envDict, await loadEnvFile(resolve(process.cwd(), envFile))); } } - const { resolved } = resolveEnvVars(connStr, envDict); + const { resolved } = resolvePlaceholders(connStr, envDict); const parsed = parseConnectionString(resolved); const connResult = await testConnectionFields(config, { @@ -2191,7 +2191,7 @@ export async function configCommand(config: PgdevConfig): Promise { ], }, { - title: "Project Settings", + title: "Project", items: [ { key: "project", @@ -2205,6 +2205,11 @@ export async function configCommand(config: PgdevConfig): Promise { value: schemasStatus(currentConfig.project.schemas), help: "Select database schemas used by this project.\nEmpty means all non-system schemas.", }, + ], + }, + { + title: "Diff", + items: [ { key: "grants", label: "Track grants", @@ -2219,6 +2224,106 @@ export async function configCommand(config: PgdevConfig): Promise { }, ], }, + { + title: "Sync", + items: [ + { + key: "api_dir", + label: "API routines dir", + value: currentConfig.project.api_dir || pc.dim("(none)"), + help: "Subdirectory within routines_dir for API (HTTP endpoint) routines.\nA routine is an API routine if its comment contains HTTP at the start or start of a line.\nLeave empty to place all routines directly in routines_dir.", + }, + { + key: "internal_dir", + label: "Internal routines dir", + value: currentConfig.project.internal_dir || pc.dim("(none)"), + help: "Subdirectory within routines_dir for internal (non-API) routines.\nLeave empty to place all routines directly in routines_dir.", + }, + { + key: "group_segment", + label: "Group by name segment", + value: currentConfig.project.group_segment === 0 ? pc.dim("disabled") : String(currentConfig.project.group_segment), + help: "Group routines into subdirectories by snake_case name segment.\n0 = disabled. 1 = use first segment of the name.\nE.g. auth_login → auth/, get_user_data → user/ (with generic prefix skipping).", + }, + { + key: "skip_prefixes", + label: "Skip prefixes", + value: currentConfig.project.skip_prefixes.length === 0 ? pc.dim("defaults") : `${currentConfig.project.skip_prefixes.length} custom`, + help: "Prefixes to skip when grouping by name segment.\nEmpty = use built-in defaults (get, set, delete, insert, is, has, etc.).\nCustomize to control which verb prefixes are skipped.\nE.g. get_user_data → user/ instead of get/.", + }, + { + key: "group_order", + label: "Group order", + value: currentConfig.project.group_order, + help: "Directory nesting order when both api/internal and group segment dirs are used.\n\"type_first\" = api/auth/auth_login.sql\n\"group_first\" = auth/api/auth_login.sql", + }, + ], + }, + { + title: "Format", + items: [ + { + key: "fmt_lowercase", + label: "Lowercase keywords", + value: currentConfig.format.lowercase ? "yes" : "no", + help: "Lowercase SQL keywords (CREATE, FUNCTION, RETURNS, etc.) in formatted output.", + }, + { + key: "fmt_param_style", + label: "Parameter style", + value: currentConfig.format.param_style, + help: "Parameter layout in routine signatures.\n\"multiline\" puts each parameter on its own indented line.\n\"inline\" keeps all parameters on a single line.", + }, + { + key: "fmt_attribute_style", + label: "Attribute style", + value: currentConfig.format.attribute_style, + help: "Placement of attributes (LANGUAGE, SECURITY DEFINER, IMMUTABLE, etc.).\n\"multiline\" puts each on its own line between ) and AS.\n\"inline\" keeps them all on one line.", + }, + { + key: "fmt_simplify_defaults", + label: "Simplify defaults", + value: currentConfig.format.simplify_defaults ? "yes" : "no", + help: "Simplify pg_dump default expressions.\nE.g. (NULL::text = NULL::text) → null, '{}'::jsonb → '{}'.", + }, + { + key: "fmt_omit_default_direction", + label: "Omit IN direction", + value: currentConfig.format.omit_default_direction ? "yes" : "no", + help: "Omit the IN keyword for parameters since it's the default direction.\nOUT, INOUT, and VARIADIC are always shown.", + }, + { + key: "fmt_strip_dump_comments", + label: "Strip dump comments", + value: currentConfig.format.strip_dump_comments ? "yes" : "no", + help: "Remove pg_dump header/footer comments from formatted output.\nE.g. \"-- PostgreSQL database dump\", \"-- Name: ...\", etc.", + }, + { + key: "fmt_comment_signature_style", + label: "Comment signature", + value: currentConfig.format.comment_signature_style, + help: "Signature style in COMMENT ON statements.\n\"types_only\" uses just types: name(text, integer).\n\"full\" includes parameter names: name(_a text, _b integer).", + }, + { + key: "fmt_indent", + label: "Indent", + value: currentConfig.format.indent === " " ? "4 spaces" : currentConfig.format.indent === " " ? "2 spaces" : currentConfig.format.indent === "\t" ? "tab" : JSON.stringify(currentConfig.format.indent), + help: "Indentation string used for multiline parameters and table columns.", + }, + { + key: "fmt_drop_before_create", + label: "Drop before create", + value: currentConfig.format.drop_before_create ? "yes" : "no", + help: "Add DROP FUNCTION/PROCEDURE IF EXISTS before the CREATE statement.\nUseful for re-runnable SQL files.", + }, + { + key: "fmt_create_or_replace", + label: "Create or replace", + value: currentConfig.format.create_or_replace ? "yes" : "no", + help: "Use CREATE OR REPLACE instead of plain CREATE.\nNote: procedures only support OR REPLACE in PostgreSQL 14+.", + }, + ], + }, ]; const actions = [{ key: "q", label: "Quit" }]; @@ -2248,6 +2353,116 @@ export async function configCommand(config: PgdevConfig): Promise { const newValue = !currentConfig.project.ignore_body_whitespace; await updateConfigBool("project", "ignore_body_whitespace", newValue); lastStatus = `ignore_body_whitespace = ${newValue}`; + } else if (choice.key === "api_dir") { + const value = await askValue("API routines dir", currentConfig.project.api_dir); + if (value !== null) { + await updateConfig("project", "api_dir", value); + lastStatus = `api_dir = "${value}"`; + } + } else if (choice.key === "internal_dir") { + const value = await askValue("Internal routines dir", currentConfig.project.internal_dir); + if (value !== null) { + await updateConfig("project", "internal_dir", value); + lastStatus = `internal_dir = "${value}"`; + } + } else if (choice.key === "group_segment") { + const value = await askValue("Group segment (0 = disabled)", String(currentConfig.project.group_segment)); + if (value !== null) { + const num = parseInt(value, 10); + if (!isNaN(num) && num >= 0) { + await updateConfigInt("project", "group_segment", num); + lastStatus = `group_segment = ${num}`; + } else { + lastStatus = "Invalid value — must be 0 or a positive integer"; + } + } + } else if (choice.key === "skip_prefixes") { + const current = currentConfig.project.skip_prefixes.length > 0 + ? currentConfig.project.skip_prefixes.join(", ") + : ""; + const value = await askValue("Skip prefixes (comma-separated, empty = defaults)", current); + if (value !== null) { + const prefixes = value.trim() === "" + ? [] + : value.split(",").map((s) => s.trim()).filter(Boolean); + updateConfigArraySync("project", "skip_prefixes", prefixes); + lastStatus = prefixes.length === 0 ? "skip_prefixes = [] (using defaults)" : `skip_prefixes = ${prefixes.length} custom`; + } + } else if (choice.key === "group_order") { + const idx = await ask("Group order", [ + { label: "type_first", description: "api/auth/ — type dir first, then group" }, + { label: "group_first", description: "auth/api/ — group dir first, then type" }, + ]); + if (idx >= 0) { + const value = idx === 0 ? "type_first" : "group_first"; + await updateConfig("project", "group_order", value); + lastStatus = `group_order = "${value}"`; + } + } else if (choice.key === "fmt_lowercase") { + const newValue = !currentConfig.format.lowercase; + await updateConfigBool("format", "lowercase", newValue); + lastStatus = `lowercase = ${newValue}`; + } else if (choice.key === "fmt_param_style") { + const idx = await ask("Parameter style", [ + { label: "multiline", description: "Each parameter on its own line" }, + { label: "inline", description: "All parameters on one line" }, + ]); + if (idx >= 0) { + const value = idx === 0 ? "multiline" : "inline"; + await updateConfig("format", "param_style", value); + lastStatus = `param_style = "${value}"`; + } + } else if (choice.key === "fmt_attribute_style") { + const idx = await ask("Attribute style", [ + { label: "multiline", description: "Each attribute on its own line" }, + { label: "inline", description: "All attributes on one line" }, + ]); + if (idx >= 0) { + const value = idx === 0 ? "multiline" : "inline"; + await updateConfig("format", "attribute_style", value); + lastStatus = `attribute_style = "${value}"`; + } + } else if (choice.key === "fmt_simplify_defaults") { + const newValue = !currentConfig.format.simplify_defaults; + await updateConfigBool("format", "simplify_defaults", newValue); + lastStatus = `simplify_defaults = ${newValue}`; + } else if (choice.key === "fmt_omit_default_direction") { + const newValue = !currentConfig.format.omit_default_direction; + await updateConfigBool("format", "omit_default_direction", newValue); + lastStatus = `omit_default_direction = ${newValue}`; + } else if (choice.key === "fmt_strip_dump_comments") { + const newValue = !currentConfig.format.strip_dump_comments; + await updateConfigBool("format", "strip_dump_comments", newValue); + lastStatus = `strip_dump_comments = ${newValue}`; + } else if (choice.key === "fmt_comment_signature_style") { + const idx = await ask("Comment signature style", [ + { label: "types_only", description: "name(text, integer)" }, + { label: "full", description: "name(_a text, _b integer)" }, + ]); + if (idx >= 0) { + const value = idx === 0 ? "types_only" : "full"; + await updateConfig("format", "comment_signature_style", value); + lastStatus = `comment_signature_style = "${value}"`; + } + } else if (choice.key === "fmt_drop_before_create") { + const newValue = !currentConfig.format.drop_before_create; + await updateConfigBool("format", "drop_before_create", newValue); + lastStatus = `drop_before_create = ${newValue}`; + } else if (choice.key === "fmt_create_or_replace") { + const newValue = !currentConfig.format.create_or_replace; + await updateConfigBool("format", "create_or_replace", newValue); + lastStatus = `create_or_replace = ${newValue}`; + } else if (choice.key === "fmt_indent") { + const idx = await ask("Indentation", [ + { label: "4 spaces", description: " (default)" }, + { label: "2 spaces", description: " " }, + { label: "Tab", description: "\\t" }, + ]); + if (idx >= 0) { + const value = idx === 0 ? " " : idx === 1 ? " " : "\t"; + await updateConfig("format", "indent", value); + lastStatus = `indent = ${idx === 2 ? "tab" : `${idx === 0 ? 4 : 2} spaces`}`; + } } currentConfig = await loadConfig(); diff --git a/src/commands/diff.ts b/src/commands/diff.ts index 48bdeda..23b97f5 100644 --- a/src/commands/diff.ts +++ b/src/commands/diff.ts @@ -1,7 +1,8 @@ import { resolve } from "node:path"; -import { readdirSync, statSync } from "node:fs"; +import { statSync } from "node:fs"; import type { PgdevConfig } from "../config.ts"; import { pc, spinner } from "../utils/terminal.ts"; +import { findSqlFiles } from "../utils/files.ts"; import { parseRoutines, type ParsedRoutine } from "../parser/routine.ts"; import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; import { routinesDiffer, commentsDiffer, grantsDiffer, type DiffOptions } from "../parser/compare.ts"; @@ -34,20 +35,6 @@ function catalogDisplayKey(r: CatalogRoutine): string { return `${r.schema}.${r.name}(${params.join(", ")})`; } -/** Recursively find all .sql files in a directory. */ -function findSqlFiles(dir: string): string[] { - const results: string[] = []; - for (const entry of readdirSync(dir, { withFileTypes: true })) { - const full = resolve(dir, entry.name); - if (entry.isDirectory()) { - results.push(...findSqlFiles(full)); - } else if (entry.isFile() && entry.name.endsWith(".sql")) { - results.push(full); - } - } - return results.sort(); -} - export async function diffCommand(config: PgdevConfig): Promise { const { routines_dir, schemas, grants, ignore_body_whitespace } = config.project; @@ -192,7 +179,7 @@ export async function diffCommand(config: PgdevConfig): Promise { if (needUpdating.length > 0) { console.log(pc.bold(`Different from database (${needUpdating.length}):`)); for (const { display, file, changes } of needUpdating) { - console.log(` ${pc.yellow("~")} ${display} ${pc.dim(file)}`); + console.log(` ${pc.yellow("~")} ${display} ${pc.dim(file)} ${pc.yellow(changes.join(", "))}`); } console.log(); } diff --git a/src/commands/exec.ts b/src/commands/exec.ts index 680c8da..25a9673 100644 --- a/src/commands/exec.ts +++ b/src/commands/exec.ts @@ -2,7 +2,7 @@ import { resolve } from "node:path"; import { type PgdevConfig, isSharedConnection } from "../config.ts"; import { error, pc, formatCmd } from "../utils/terminal.ts"; import { splitCommand } from "../cli.ts"; -import { resolveEnvVars, loadEnvFile, buildPgdevEnvDict } from "../utils/env.ts"; +import { resolvePlaceholders, loadEnvFile, buildPgdevEnvDict } from "../utils/env.ts"; import { readJsonConfig } from "../utils/json.ts"; export interface ConnectionFields { @@ -53,7 +53,7 @@ export async function resolveConnection(config: PgdevConfig): Promise resolveEnvVars(v, envDict).resolved; + const resolve_ = (v: string) => resolvePlaceholders(v, envDict).resolved; return { host: resolve_(conn.host ?? "") || "localhost", diff --git a/src/commands/sync.ts b/src/commands/sync.ts index 94315d9..7e6e1a1 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -5,6 +5,9 @@ import { type PgdevConfig } from "../config.ts"; import { resolveConnection } from "./exec.ts"; import { splitCommand } from "../cli.ts"; import { error, success, pc, formatCmd } from "../utils/terminal.ts"; +import { findSqlFiles } from "../utils/files.ts"; +import { parseRoutines } from "../parser/routine.ts"; +import { isApiRoutine, getGroupDir, formatRoutines, configToFormatOptions, DEFAULT_SKIP_PREFIXES } from "../parser/formatter.ts"; function cleanRestoreOutput(sql: string): string { return sql @@ -165,8 +168,12 @@ export async function syncCommand(config: PgdevConfig): Promise { const cleaned = cleanRestoreOutput(restoreStdout); const outPath = resolve(fullDir, "schema.sql"); - await Bun.write(outPath, cleaned); - console.log(success(`Schema written to ${pc.bold(outPath)}`)); + if (existsSync(outPath)) { + console.log(pc.dim(`Schema file already exists: ${outPath} (skipped)`)); + } else { + await Bun.write(outPath, cleaned); + console.log(success(`Schema written to ${pc.bold(outPath)}`)); + } } finally { try { unlinkSync(tocFile); } catch {} } @@ -177,12 +184,25 @@ export async function syncCommand(config: PgdevConfig): Promise { const fullRoutinesDir = resolve(process.cwd(), routinesDir); mkdirSync(fullRoutinesDir, { recursive: true }); + // Scan existing files to map routine names to file paths + const existingRoutines = new Map(); + const existingFiles = findSqlFiles(fullRoutinesDir); + for (const file of existingFiles) { + const content = await Bun.file(file).text(); + const parsed = parseRoutines(content); + for (const r of parsed) { + existingRoutines.set(r.name, { file, content }); + } + } + const routineGroups = parseRoutineGroups(listStdout, config.project.grants); if (routineGroups.length > 0) { const routineTocFile = resolve(tmpdir(), `pgdev-routine-toc-${Date.now()}.list`); try { - let filesWritten = 0; + let created = 0; + let updated = 0; + let unchanged = 0; for (const group of routineGroups) { await Bun.write(routineTocFile, group.tocLines.join("\n") + "\n"); @@ -204,17 +224,69 @@ export async function syncCommand(config: PgdevConfig): Promise { continue; } - const routineSql = cleanRestoreOutput(rStdout); - const outFile = resolve(fullRoutinesDir, `${group.name}.sql`); + const cleaned = cleanRestoreOutput(rStdout); + const formatOpts = configToFormatOptions(config.format); + const parsed = parseRoutines(cleaned, { grants: config.project.grants }); + const routineSql = parsed.length > 0 ? formatRoutines(parsed, formatOpts) : cleaned; + const existing = existingRoutines.get(group.name); + + if (existing && existing.content.trimEnd() === routineSql.trimEnd()) { + // Content identical — skip + unchanged++; + if (config.verbose) { + console.error(pc.dim(` ${group.name} (unchanged)`)); + } + continue; + } + + // Write to existing file path if routine exists, otherwise new file + let outFile: string; + if (existing) { + outFile = existing.file; + } else { + // Determine base dir: api_dir or internal_dir if configured + const isApi = isApiRoutine(parsed); + const typeSubDir = isApi ? config.project.api_dir : config.project.internal_dir; + + // Determine group dir from name segment + const skipSet = new Set(config.project.skip_prefixes.length > 0 ? config.project.skip_prefixes : DEFAULT_SKIP_PREFIXES); + const groupSubDir = getGroupDir( + group.name, + config.project.group_segment, + skipSet, + ); + + let targetDir = fullRoutinesDir; + if (config.project.group_order === "group_first") { + if (groupSubDir) targetDir = resolve(targetDir, groupSubDir); + if (typeSubDir) targetDir = resolve(targetDir, typeSubDir); + } else { + if (typeSubDir) targetDir = resolve(targetDir, typeSubDir); + if (groupSubDir) targetDir = resolve(targetDir, groupSubDir); + } + if (targetDir !== fullRoutinesDir) mkdirSync(targetDir, { recursive: true }); + outFile = resolve(targetDir, `${group.name}.sql`); + } await Bun.write(outFile, routineSql); - filesWritten++; - if (config.verbose) { - console.error(pc.dim(` ${group.name}.sql`)); + if (existing) { + updated++; + if (config.verbose) { + console.error(pc.yellow(` ${group.name} (updated)`)); + } + } else { + created++; + if (config.verbose) { + console.error(pc.green(` ${group.name} (created)`)); + } } } - console.log(success(`Routines written to ${pc.bold(routinesDir + "/")} (${filesWritten} files)`)); + const parts: string[] = []; + if (created > 0) parts.push(pc.green(`${created} created`)); + if (updated > 0) parts.push(pc.yellow(`${updated} updated`)); + if (unchanged > 0) parts.push(`${unchanged} unchanged`); + console.log(success(`Routines in ${pc.bold(routinesDir + "/")}: ${parts.join(", ")}`)); } finally { try { unlinkSync(routineTocFile); } catch {} } diff --git a/src/config.ts b/src/config.ts index 45326c9..c62f698 100644 --- a/src/config.ts +++ b/src/config.ts @@ -30,6 +30,24 @@ export interface ProjectConfig { schemas: string[]; grants: boolean; ignore_body_whitespace: boolean; + api_dir: string; + internal_dir: string; + group_segment: number; + skip_prefixes: string[]; + group_order: "type_first" | "group_first"; +} + +export interface FormatConfig { + lowercase: boolean; + param_style: "inline" | "multiline"; + indent: string; + simplify_defaults: boolean; + omit_default_direction: boolean; + attribute_style: "inline" | "multiline"; + strip_dump_comments: boolean; + comment_signature_style: "types_only" | "full"; + drop_before_create: boolean; + create_or_replace: boolean; } export interface PgdevConfig { @@ -44,6 +62,7 @@ export interface PgdevConfig { commands: CommandsConfig; connection: ConnectionConfig; project: ProjectConfig; + format: FormatConfig; verbose: boolean; } @@ -70,6 +89,23 @@ const defaults: PgdevConfig = { schemas: [], grants: false, ignore_body_whitespace: false, + api_dir: "", + internal_dir: "", + group_segment: 0, + skip_prefixes: [], + group_order: "type_first", + }, + format: { + lowercase: true, + param_style: "multiline", + indent: " ", + simplify_defaults: true, + omit_default_direction: true, + attribute_style: "multiline", + strip_dump_comments: true, + comment_signature_style: "types_only", + drop_before_create: true, + create_or_replace: false, }, verbose: true, }; @@ -187,6 +223,53 @@ export async function updateConfigBool(section: string, key: string, value: bool await Bun.write(path, content); } +export async function updateConfigInt(section: string, key: string, value: number): Promise { + // Same logic as updateConfigBool — writes `key = value` without quotes + const path = `${process.cwd()}/pgdev.toml`; + const file = Bun.file(path); + let content = (await file.exists()) ? await file.text() : ""; + + const newLine = `${key} = ${value}`; + const keyPattern = new RegExp(`^${key}\\s*=.*$`, "m"); + + if (!section) { + const firstSectionMatch = content.match(/^\[/m); + const topLevelEnd = firstSectionMatch?.index ?? content.length; + const topLevel = content.slice(0, topLevelEnd); + + if (keyPattern.test(topLevel)) { + content = topLevel.replace(keyPattern, newLine) + content.slice(topLevelEnd); + } else { + const suffix = topLevel.endsWith("\n") || topLevel === "" ? "" : "\n"; + content = topLevel + suffix + newLine + "\n" + content.slice(topLevelEnd); + } + } else { + const sectionHeader = `[${section}]`; + const sectionIndex = content.indexOf(sectionHeader); + if (sectionIndex !== -1) { + const afterSection = content.slice(sectionIndex + sectionHeader.length); + const nextSectionMatch = afterSection.match(/\n\[/); + const sectionEnd = nextSectionMatch + ? sectionIndex + sectionHeader.length + nextSectionMatch.index! + : content.length; + const sectionContent = content.slice(sectionIndex, sectionEnd); + + if (keyPattern.test(sectionContent)) { + const updated = sectionContent.replace(keyPattern, newLine); + content = content.slice(0, sectionIndex) + updated + content.slice(sectionEnd); + } else { + const insertPos = sectionIndex + sectionHeader.length; + content = content.slice(0, insertPos) + `\n${newLine}` + content.slice(insertPos); + } + } else { + const suffix = content.endsWith("\n") || content === "" ? "" : "\n"; + content += `${suffix}\n${sectionHeader}\n${newLine}\n`; + } + } + + await Bun.write(path, content); +} + function applyArrayUpdate(content: string, section: string, key: string, values: string[]): string { const tomlValue = values.length === 0 ? "[]" @@ -328,6 +411,22 @@ const EXPECTED_KEYS: { section: string; key: string; raw: string }[] = [ { section: "project", key: "schemas", raw: "schemas = []" }, { section: "project", key: "grants", raw: "# Track GRANT/REVOKE statements for routines\ngrants = false" }, { section: "project", key: "ignore_body_whitespace", raw: "# Ignore whitespace differences in routine bodies when comparing\nignore_body_whitespace = false" }, + { section: "project", key: "api_dir", raw: "# Subdirectory within routines_dir for API (HTTP endpoint) routines\napi_dir = \"\"" }, + { section: "project", key: "internal_dir", raw: "# Subdirectory within routines_dir for internal (non-API) routines\ninternal_dir = \"\"" }, + { section: "project", key: "group_segment", raw: "# Group routines into subdirs by name segment (0 = disabled, 1 = first segment)\ngroup_segment = 0" }, + { section: "project", key: "skip_prefixes", raw: "# Prefixes to skip when grouping by name segment (empty = use built-in defaults)\n# skip_prefixes = [\"get\", \"set\", \"delete\", \"insert\", \"update\", \"create\", \"remove\", \"find\", \"list\", \"is\", \"has\", \"check\", \"count\", \"compute\", \"run\", \"do\", \"send\"]\nskip_prefixes = []" }, + { section: "project", key: "group_order", raw: "# Directory nesting order when both api/internal and group dirs are used\n# \"type_first\" = api/auth/, \"group_first\" = auth/api/\ngroup_order = \"type_first\"" }, + // [format] + { section: "format", key: "lowercase", raw: "# Lowercase SQL keywords in formatted output\nlowercase = true" }, + { section: "format", key: "param_style", raw: '# Parameter layout: "inline" or "multiline"\nparam_style = "multiline"' }, + { section: "format", key: "indent", raw: '# Indentation string\nindent = " "' }, + { section: "format", key: "simplify_defaults", raw: "# Simplify default expressions (e.g. NULL::text → null)\nsimplify_defaults = true" }, + { section: "format", key: "omit_default_direction", raw: "# Omit IN direction (it's the default)\nomit_default_direction = true" }, + { section: "format", key: "attribute_style", raw: '# Attribute placement: "inline" or "multiline"\nattribute_style = "multiline"' }, + { section: "format", key: "strip_dump_comments", raw: "# Remove pg_dump header/footer comments\nstrip_dump_comments = true" }, + { section: "format", key: "comment_signature_style", raw: '# Comment signature: "types_only" or "full"\ncomment_signature_style = "types_only"' }, + { section: "format", key: "drop_before_create", raw: "# Add DROP IF EXISTS before CREATE statement\ndrop_before_create = true" }, + { section: "format", key: "create_or_replace", raw: "# Use CREATE OR REPLACE instead of CREATE\ncreate_or_replace = false" }, ]; const SECTION_COMMENTS: Record = { @@ -335,6 +434,7 @@ const SECTION_COMMENTS: Record = { "npgsqlrest.commands": '# NpgsqlRest run commands — value is the config file args passed to npgsqlrest CLI\n# Example: dev = "./config/production.json --optional ./config/development.json"', commands: "# SQL commands used by pgdev", project: "# Project directories for SQL source files\n# Leave empty to skip; directories are created when first needed", + format: "# SQL formatter options for routine files generated by sync", }; async function backfillConfig(path: string): Promise { @@ -462,6 +562,42 @@ schemas = [] grants = false # Ignore whitespace differences in routine bodies when comparing ignore_body_whitespace = false +# Subdirectory within routines_dir for API (HTTP endpoint) routines +api_dir = "" +# Subdirectory within routines_dir for internal (non-API) routines +internal_dir = "" +# Group routines into subdirs by name segment (0 = disabled, 1 = first segment) +group_segment = 0 +# Prefixes to skip when grouping by name segment (empty = use built-in defaults) +# skip_prefixes = ["get", "set", "delete", "insert", "update", "create", "remove", "find", "list", "is", "has", "check", "count", "compute", "run", "do", "send"] +skip_prefixes = [] +# Directory nesting order when both api/internal and group dirs are used +# "type_first" = api/auth/, "group_first" = auth/api/ +group_order = "type_first" + +# SQL formatter options for routine files generated by sync +[format] + +# Lowercase SQL keywords in formatted output +lowercase = true +# Parameter layout: "inline" or "multiline" +param_style = "multiline" +# Indentation string +indent = " " +# Simplify default expressions (e.g. NULL::text → null) +simplify_defaults = true +# Omit IN direction (it's the default) +omit_default_direction = true +# Attribute placement: "inline" or "multiline" +attribute_style = "multiline" +# Remove pg_dump header/footer comments +strip_dump_comments = true +# Comment signature: "types_only" or "full" +comment_signature_style = "types_only" +# Add DROP IF EXISTS before CREATE statement +drop_before_create = true +# Use CREATE OR REPLACE instead of CREATE +create_or_replace = false `; await Bun.write(path, content); @@ -510,5 +646,10 @@ export async function loadConfig(): Promise { ...(project?.project as Partial | undefined), ...(local?.project as Partial | undefined), }, + format: { + ...defaults.format, + ...(project?.format as Partial | undefined), + ...(local?.format as Partial | undefined), + }, } as PgdevConfig; } diff --git a/src/parser/catalog-tests/begin-atomic.test.ts b/src/parser/catalog-tests/begin-atomic.test.ts index 64e3751..5c39281 100644 --- a/src/parser/catalog-tests/begin-atomic.test.ts +++ b/src/parser/catalog-tests/begin-atomic.test.ts @@ -7,7 +7,10 @@ const SQL = ` CREATE FUNCTION test_schema.atomic_add(_a int, _b int) RETURNS int IMMUTABLE PARALLEL SAFE BEGIN ATOMIC; - SELECT _a + _b; + select + _a + + + _b; END; `; diff --git a/src/parser/catalog-tests/body-formatting-diff.test.ts b/src/parser/catalog-tests/body-formatting-diff.test.ts index f80fb3f..04cacda 100644 --- a/src/parser/catalog-tests/body-formatting-diff.test.ts +++ b/src/parser/catalog-tests/body-formatting-diff.test.ts @@ -37,10 +37,12 @@ describe("body comparison — formatting differences", () => { expect(bodyHash(parsed.body!)).toBe(bodyHash(match!.body!)); }); - test("normalizeBody collapses whitespace and lowercases", () => { + test("normalizeBody lowercases and trims but preserves whitespace structure", () => { const a = " SELECT\n _a\n +\n _b; "; - const b = "select _a + _b;"; + const b = "select\n _a\n +\n _b;"; expect(normalizeBody(a)).toBe(normalizeBody(b)); + // Different whitespace structure is detected + expect(normalizeBody(a)).not.toBe(normalizeBody("select _a + _b;")); }); test("different bodies produce different hashes", () => { diff --git a/src/parser/catalog.ts b/src/parser/catalog.ts index 7234267..16262b3 100644 --- a/src/parser/catalog.ts +++ b/src/parser/catalog.ts @@ -136,12 +136,14 @@ function parsePgArray(raw: string): string[] { return raw.replace(/^\{/, "").replace(/\}$/, "").split(","); } -/** Normalize body for comparison: lowercase, strip non-printable, collapse whitespace. */ +/** Normalize body for comparison: lowercase, normalize line endings, trim trailing whitespace per line. */ export function normalizeBody(body: string): string { return body .toLowerCase() - .replace(/[^\x20-\x7e]/g, " ") - .replace(/\s+/g, " ") + .replace(/\r\n?/g, "\n") // normalize line endings + .replace(/[^\x20-\x7e\n]/g, " ") // strip non-printable (keep newlines) + .replace(/[ \t]+$/gm, "") // trim trailing whitespace per line + .replace(/\n{3,}/g, "\n\n") // collapse 3+ blank lines to 2 .trim(); } diff --git a/src/parser/formatter.ts b/src/parser/formatter.ts new file mode 100644 index 0000000..b419962 --- /dev/null +++ b/src/parser/formatter.ts @@ -0,0 +1,353 @@ +import type { ParsedRoutine } from "./routine.ts"; +import type { FormatConfig } from "../config.ts"; + +export interface FormatOptions { + /** Lowercase SQL keywords (default: true) */ + lowercase: boolean; + /** Parameter layout: "inline" or "multiline" (default: "multiline") */ + paramStyle: "inline" | "multiline"; + /** Indentation string (default: " ") */ + indent: string; + /** Simplify default expressions like (NULL::text = NULL::text) → null (default: true) */ + simplifyDefaults: boolean; + /** Omit IN direction since it's the default (default: true) */ + omitDefaultDirection: boolean; + /** Attribute placement: "inline" or "multiline" (default: "multiline") */ + attributeStyle: "inline" | "multiline"; + /** Remove pg_dump header/footer comments (default: true) */ + stripDumpComments: boolean; + /** Comment signature: "types_only" or "full" (default: "types_only") */ + commentSignatureStyle: "types_only" | "full"; + /** Add DROP FUNCTION/PROCEDURE IF EXISTS before CREATE (default: true) */ + dropBeforeCreate: boolean; + /** Use CREATE OR REPLACE instead of CREATE (default: false) */ + createOrReplace: boolean; +} + +export const DEFAULT_FORMAT_OPTIONS: FormatOptions = { + lowercase: true, + paramStyle: "multiline", + indent: " ", + simplifyDefaults: true, + omitDefaultDirection: true, + attributeStyle: "multiline", + stripDumpComments: true, + commentSignatureStyle: "types_only", + dropBeforeCreate: true, + createOrReplace: false, +}; + +/** + * Simplify a pg_dump default expression to a more human-readable form. + * - (NULL::type = NULL::type) → null + * - NULL::type → null + * - 'value'::type → 'value' + * - (value)::type → value (for simple parenthesized expressions) + */ +function simplifyDefault(expr: string): string { + // (NULL::type = NULL::type) → null + if (/^\(NULL::\w+\s*=\s*NULL::\w+\)$/i.test(expr)) return "null"; + + // NULL::type → null + if (/^NULL::\w+$/i.test(expr)) return "null"; + + // 'value'::type → 'value' (but keep the value itself) + const quotedCast = expr.match(/^'([^']*)'(?:::\w+(?:\[\])?)$/); + if (quotedCast) return `'${quotedCast[1]}'`; + + // (value)::type for simple numeric/literal → value + const parenCast = expr.match(/^\(([^)]+)\)(?:::\w+(?:\[\])?)$/); + if (parenCast) { + const inner = parenCast[1].trim(); + // Only simplify if inner is a simple literal (number, string, null) + if (/^[\d.]+$/.test(inner) || /^'[^']*'$/.test(inner) || /^null$/i.test(inner)) { + return inner.toLowerCase() === "null" ? "null" : inner; + } + } + + return expr; +} + +function kw(word: string, lowercase: boolean): string { + return lowercase ? word.toLowerCase() : word.toUpperCase(); +} + +/** Format the CREATE FUNCTION/PROCEDURE header with parameters. */ +function formatHeader(r: ParsedRoutine, opts: FormatOptions): string { + const orReplace = opts.createOrReplace ? ` ${kw("OR REPLACE", opts.lowercase)}` : ""; + const createKw = r.type === "function" + ? `${kw("CREATE", opts.lowercase)}${orReplace} ${kw("FUNCTION", opts.lowercase)}` + : `${kw("CREATE", opts.lowercase)}${orReplace} ${kw("PROCEDURE", opts.lowercase)}`; + + const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + + // Format parameters + const params = r.parameters.map((p) => { + const parts: string[] = []; + + // Direction + if (p.dir && !(opts.omitDefaultDirection && p.dir === "in")) { + parts.push(kw(p.dir, opts.lowercase)); + } + + // Name + if (p.name) parts.push(p.name); + + // Type + parts.push(opts.lowercase ? p.type.toLowerCase() : p.type); + + // Default + if (p.default != null) { + const def = opts.simplifyDefaults ? simplifyDefault(p.default) : p.default; + parts.push(`= ${def}`); + } + + return parts.join(" "); + }); + + if (params.length === 0) { + return `${createKw} ${qualName}()`; + } + + if (opts.paramStyle === "inline") { + return `${createKw} ${qualName}(${params.join(", ")})`; + } + + // Multiline + const paramLines = params.map((p, i) => { + const comma = i < params.length - 1 ? "," : ""; + return `${opts.indent}${p}${comma}`; + }); + return `${createKw} ${qualName}(\n${paramLines.join("\n")}\n)`; +} + +/** Format the RETURNS clause. */ +function formatReturns(r: ParsedRoutine, opts: FormatOptions): string | null { + if (!r.returns) return null; + + if (r.returns.table) { + const cols = r.returns.table.map((c) => { + const type = opts.lowercase ? c.type.toLowerCase() : c.type; + return `${opts.indent}${c.name} ${type}`; + }); + return `${kw("RETURNS", opts.lowercase)} ${kw("TABLE", opts.lowercase)}(\n${cols.join(",\n")}\n)`; + } + + const parts: string[] = [kw("RETURNS", opts.lowercase)]; + if (r.returns.setof) parts.push(kw("SETOF", opts.lowercase)); + if (r.returns.type) { + parts.push(opts.lowercase ? r.returns.type.toLowerCase() : r.returns.type.toUpperCase()); + } + return parts.join(" "); +} + +/** + * Known attribute prefixes for grouping. + */ +function formatAttribute(attr: string, lowercase: boolean): string { + return lowercase ? attr.toLowerCase() : attr.toUpperCase(); +} + +/** Format attributes (LANGUAGE, SECURITY DEFINER, IMMUTABLE, etc.). */ +function formatAttributes(r: ParsedRoutine, opts: FormatOptions): string[] { + // Reorder: non-LANGUAGE attributes first, then LANGUAGE + const langAttr = r.attributes.find((a) => /^LANGUAGE\s/i.test(a)); + const others = r.attributes.filter((a) => !/^LANGUAGE\s/i.test(a)); + + const ordered = [...others]; + if (langAttr) ordered.push(langAttr); + + return ordered.map((a) => formatAttribute(a, opts.lowercase)); +} + +/** Format the body with dollar quoting. */ +function formatBody(r: ParsedRoutine, opts: FormatOptions): string | null { + if (r.body == null) return null; + return `${kw("AS", opts.lowercase)}\n$$${r.body}$$`; +} + +/** Format COMMENT ON statement. */ +function formatComment(r: ParsedRoutine, opts: FormatOptions): string | null { + if (r.comment == null) return null; + + const typeKw = r.type === "function" + ? kw("FUNCTION", opts.lowercase) + : kw("PROCEDURE", opts.lowercase); + const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + + let sig: string; + if (opts.commentSignatureStyle === "types_only") { + sig = r.parameters + .map((p) => opts.lowercase ? p.type.toLowerCase() : p.type) + .join(", "); + } else { + sig = r.parameters + .map((p) => { + const parts: string[] = []; + if (p.dir && !(opts.omitDefaultDirection && p.dir === "in")) { + parts.push(kw(p.dir, opts.lowercase)); + } + if (p.name) parts.push(p.name); + parts.push(opts.lowercase ? p.type.toLowerCase() : p.type); + return parts.join(" "); + }) + .join(", "); + } + + // Escape single quotes in comment text + const escaped = r.comment.replace(/'/g, "''"); + return `${kw("COMMENT ON", opts.lowercase)} ${typeKw} ${qualName}(${sig}) ${kw("IS", opts.lowercase)} '${escaped}';`; +} + +/** Format GRANT/REVOKE statements. */ +function formatGrants(r: ParsedRoutine, opts: FormatOptions): string[] { + if (r.grants.length === 0) return []; + + const typeKw = r.type === "function" + ? kw("FUNCTION", opts.lowercase) + : kw("PROCEDURE", opts.lowercase); + const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + const sig = r.parameters + .map((p) => opts.lowercase ? p.type.toLowerCase() : p.type) + .join(", "); + + return r.grants.map((g) => { + const action = g.isGrant ? kw("GRANT", opts.lowercase) : kw("REVOKE", opts.lowercase); + const priv = kw(g.privilege, opts.lowercase); + const preposition = g.isGrant + ? kw("TO", opts.lowercase) + : kw("FROM", opts.lowercase); + const onKw = kw("ON", opts.lowercase); + return `${action} ${priv} ${onKw} ${typeKw} ${qualName}(${sig}) ${preposition} ${g.grantee};`; + }); +} + +/** Format a single parsed routine to SQL text. */ +export function formatRoutine(r: ParsedRoutine, options?: Partial): string { + const opts: FormatOptions = { ...DEFAULT_FORMAT_OPTIONS, ...options }; + const parts: string[] = []; + + // DROP IF EXISTS before CREATE + if (opts.dropBeforeCreate) { + const typeKw = r.type === "function" + ? kw("FUNCTION", opts.lowercase) + : kw("PROCEDURE", opts.lowercase); + const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + const sig = r.parameters + .map((p) => opts.lowercase ? p.type.toLowerCase() : p.type.toUpperCase()) + .join(", "); + parts.push(`${kw("DROP", opts.lowercase)} ${typeKw} ${kw("IF EXISTS", opts.lowercase)} ${qualName}(${sig});`); + parts.push(""); + } + + // Header (CREATE + params) + parts.push(formatHeader(r, opts)); + + // Returns + const returns = formatReturns(r, opts); + + // Attributes + const attrs = formatAttributes(r, opts); + + // Build the section between ) and AS + const midParts: string[] = []; + if (returns) midParts.push(returns); + midParts.push(...attrs); + + if (opts.attributeStyle === "multiline") { + // Each on its own line + for (const part of midParts) { + parts.push(part); + } + } else { + // All inline after the header + if (midParts.length > 0) { + parts[parts.length - 1] += " " + midParts.join(" "); + } + } + + // Body + const body = formatBody(r, opts); + if (body) { + parts.push(body + ";"); + } + + let result = parts.join("\n"); + + // Comment + const comment = formatComment(r, opts); + if (comment) { + result += "\n\n" + comment; + } + + // Grants + const grants = formatGrants(r, opts); + if (grants.length > 0) { + result += "\n\n" + grants.join("\n"); + } + + return result + "\n"; +} + +/** Format multiple parsed routines into a single SQL file. */ +export function formatRoutines(routines: ParsedRoutine[], options?: Partial): string { + if (routines.length === 0) return ""; + return routines.map((r) => formatRoutine(r, options)).join("\n"); +} + +/** Default prefixes to skip when grouping routines by name segment. */ +export const DEFAULT_SKIP_PREFIXES: string[] = [ + // CRUD / query + "get", "select", "read", "fetch", "find", "list", "load", "search", "lookup", "all", + // write + "set", "update", "put", "upsert", "insert", "add", "create", "save", "store", "write", + // delete + "delete", "remove", "drop", "clear", "purge", + // boolean + "is", "has", "can", "check", "validate", "verify", + // math + "count", "sum", "compute", "calculate", + // action + "run", "execute", "do", "process", "handle", "call", "invoke", "trigger", "perform", + "send", "notify", "emit", "sync", "refresh", "reset", "init", "setup", + "parse", "format", "convert", "transform", "generate", "build", "make", + "ensure", "try", +]; + +/** + * Extract a directory group name from a routine's snake_case name. + * Returns empty string if grouping doesn't apply (segment=0 or name too short). + */ +export function getGroupDir(name: string, segment: number, skipPrefixes: Set): string { + if (segment <= 0) return ""; + const parts = name.split("_"); + let idx = segment - 1; // convert to 0-based + if (idx >= parts.length) return ""; + if (skipPrefixes.size > 0) { + while (idx < parts.length - 1 && skipPrefixes.has(parts[idx])) { + idx++; + } + } + return parts[idx]; +} + +/** A routine is "public" if its comment contains HTTP at start or at start of a new line. */ +export function isApiRoutine(routines: ParsedRoutine[]): boolean { + return routines.some((r) => r.comment != null && /(?:^|\n)HTTP\b/.test(r.comment)); +} + +/** Convert snake_case FormatConfig from pgdev.toml to camelCase FormatOptions. */ +export function configToFormatOptions(config: FormatConfig): FormatOptions { + return { + lowercase: config.lowercase, + paramStyle: config.param_style, + indent: config.indent, + simplifyDefaults: config.simplify_defaults, + omitDefaultDirection: config.omit_default_direction, + attributeStyle: config.attribute_style, + stripDumpComments: config.strip_dump_comments, + commentSignatureStyle: config.comment_signature_style, + dropBeforeCreate: config.drop_before_create, + createOrReplace: config.create_or_replace, + }; +} diff --git a/src/parser/parser-tests/formatter.test.ts b/src/parser/parser-tests/formatter.test.ts new file mode 100644 index 0000000..c3caf10 --- /dev/null +++ b/src/parser/parser-tests/formatter.test.ts @@ -0,0 +1,421 @@ +import { describe, test, expect } from "bun:test"; +import { parseRoutines } from "../routine.ts"; +import { formatRoutine, formatRoutines, isApiRoutine, getGroupDir, DEFAULT_SKIP_PREFIXES, DEFAULT_FORMAT_OPTIONS, type FormatOptions } from "../formatter.ts"; + +// Real pg_dump output for a procedure with defaults, comment, and attributes +const PG_DUMP_PROCEDURE = ` +CREATE PROCEDURE mathmodule.auth_logout(IN _analytics jsonb DEFAULT '{}'::jsonb, IN _user_id text DEFAULT (NULL::text = NULL::text), IN _user_name text DEFAULT (NULL::text = NULL::text), IN _ip_address text DEFAULT (NULL::text = NULL::text)) + LANGUAGE plpgsql SECURITY DEFINER + AS $$ +begin + _analytics = coalesce(_analytics, '{}'::jsonb) || jsonb_build_object('ip', _ip_address, 'user_id', _user_id, 'username', _user_name); + + insert into mathmodule.auth_log (type, success, message, username, analytics) + values ('O', true, 'logout successful', _user_name, _analytics); +end; +$$; + +COMMENT ON PROCEDURE mathmodule.auth_logout(IN _analytics jsonb, IN _user_id text, IN _user_name text, IN _ip_address text) IS 'HTTP POST +logout +authorize +security_sensitive +tsclient_module = user'; +`; + +// Real pg_dump output for a function with returns, no defaults +const PG_DUMP_FUNCTION = ` +CREATE FUNCTION mathmodule.compute_value(_computed_spec jsonb, _things jsonb) RETURNS double precision + LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE + AS $$ +declare + _result double precision = 0; +begin + return _result; +end; +$$; +`; + +// Function with RETURNS SETOF and a DEFAULT NULL::type +const PG_DUMP_SETOF = ` +CREATE FUNCTION mathmodule.get_intervals(_cache text DEFAULT NULL::text) RETURNS SETOF text + LANGUAGE sql IMMUTABLE + AS $$ +values ('5 minutes'), ('1 hour') +$$; + +COMMENT ON FUNCTION mathmodule.get_intervals(_cache text) IS 'HTTP GET +Cache-Control: public, max-age=31536000, immutable +authorize'; +`; + +describe("formatRoutine — default options", () => { + test("procedure with defaults, comment, and attributes", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + const result = formatRoutine(parsed); + + expect(result).toContain("create procedure mathmodule.auth_logout("); + // Multiline params + expect(result).toContain(" _analytics jsonb = '{}'"); + expect(result).toContain(" _user_id text = null,"); + expect(result).toContain(" _user_name text = null,"); + expect(result).toContain(" _ip_address text = null"); + // No IN direction (omitted by default) + expect(result).not.toContain("in _analytics"); + expect(result).not.toContain("IN _analytics"); + // Attributes on own lines + expect(result).toContain("security definer\n"); + expect(result).toContain("language plpgsql\n"); + // Body + expect(result).toContain("as\n$$"); + expect(result).toContain("end;\n$$;"); + // Comment with types-only signature + expect(result).toContain("comment on procedure mathmodule.auth_logout(jsonb, text, text, text)"); + expect(result).toContain("is 'HTTP POST"); + }); + + test("function with returns, no defaults", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed); + + expect(result).toContain("create function mathmodule.compute_value("); + expect(result).toContain(" _computed_spec jsonb,"); + expect(result).toContain(" _things jsonb"); + expect(result).toContain("returns double precision"); + expect(result).toContain("immutable\n"); + expect(result).toContain("parallel safe\n"); + expect(result).toContain("language plpgsql\n"); + expect(result).not.toContain("COMMENT"); // no comment + }); + + test("function with SETOF return and DEFAULT NULL::type", () => { + const [parsed] = parseRoutines(PG_DUMP_SETOF); + const result = formatRoutine(parsed); + + expect(result).toContain("_cache text = null"); + expect(result).toContain("returns setof text"); + expect(result).toContain("comment on function mathmodule.get_intervals(text)"); + }); +}); + +describe("formatRoutine — option variations", () => { + test("uppercase keywords", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { lowercase: false }); + + expect(result).toContain("CREATE FUNCTION"); + expect(result).toContain("RETURNS DOUBLE PRECISION"); + expect(result).toContain("LANGUAGE PLPGSQL"); + expect(result).toContain("IMMUTABLE"); + }); + + test("inline params", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { paramStyle: "inline" }); + + expect(result).toContain("create function mathmodule.compute_value(_computed_spec jsonb, _things jsonb)"); + }); + + test("inline attributes", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { attributeStyle: "inline" }); + + // Returns + attributes all on the closing line + expect(result).toContain(") returns double precision immutable parallel safe language plpgsql"); + }); + + test("keep IN direction", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + const result = formatRoutine(parsed, { omitDefaultDirection: false }); + + expect(result).toContain("in _analytics jsonb"); + }); + + test("don't simplify defaults", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + const result = formatRoutine(parsed, { simplifyDefaults: false }); + + expect(result).toContain("= '{}'::jsonb"); + expect(result).toContain("= (NULL::text = NULL::text)"); + }); + + test("full comment signature", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + const result = formatRoutine(parsed, { commentSignatureStyle: "full" }); + + expect(result).toContain("comment on procedure mathmodule.auth_logout(_analytics jsonb, _user_id text, _user_name text, _ip_address text)"); + }); + + test("custom indent", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { indent: " " }); + + expect(result).toContain(" _computed_spec jsonb"); + }); +}); + +describe("simplifyDefaults", () => { + test("(NULL::text = NULL::text) → null", () => { + const sql = `CREATE FUNCTION f(_a text DEFAULT (NULL::text = NULL::text)) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + expect(result).toContain("_a text = null"); + }); + + test("NULL::text → null", () => { + const sql = `CREATE FUNCTION f(_a text DEFAULT NULL::text) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + expect(result).toContain("_a text = null"); + }); + + test("'{}'::jsonb → '{}'", () => { + const sql = `CREATE FUNCTION f(_a jsonb DEFAULT '{}'::jsonb) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + expect(result).toContain("_a jsonb = '{}'"); + }); + + test("preserves non-simplifiable defaults", () => { + const sql = `CREATE FUNCTION f(_a int DEFAULT 42) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + expect(result).toContain("_a int = 42"); + }); +}); + +describe("formatRoutines — multiple routines", () => { + test("formats multiple routines separated by blank line", () => { + const input = PG_DUMP_FUNCTION + "\n" + PG_DUMP_SETOF; + const parsed = parseRoutines(input); + const result = formatRoutines(parsed); + + expect(parsed.length).toBe(2); + expect(result).toContain("create function mathmodule.compute_value"); + expect(result).toContain("create function mathmodule.get_intervals"); + }); +}); + +describe("parseRoutines preserves defaults", () => { + test("DEFAULT keyword", () => { + const sql = `CREATE FUNCTION f(_a int DEFAULT 42) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + expect(parsed.parameters[0].default).toBe("42"); + }); + + test("= shorthand", () => { + const sql = `CREATE FUNCTION f(_a int = 42) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + expect(parsed.parameters[0].default).toBe("42"); + }); + + test("NULL::type default", () => { + const sql = `CREATE FUNCTION f(_a text DEFAULT NULL::text) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + expect(parsed.parameters[0].default).toBe("NULL::text"); + }); + + test("complex default expression", () => { + const sql = `CREATE FUNCTION f(_a jsonb DEFAULT '{}'::jsonb) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + expect(parsed.parameters[0].default).toBe("'{}'::jsonb"); + }); + + test("no default → null", () => { + const sql = `CREATE FUNCTION f(_a int) RETURNS void LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + expect(parsed.parameters[0].default).toBeNull(); + }); + + test("(NULL::type = NULL::type) pg_dump pattern", () => { + const sql = `CREATE PROCEDURE p(_a text DEFAULT (NULL::text = NULL::text)) LANGUAGE sql AS $$ $$;`; + const [parsed] = parseRoutines(sql); + expect(parsed.parameters[0].default).toBe("(NULL::text = NULL::text)"); + }); +}); + +describe("dropBeforeCreate", () => { + test("adds DROP IF EXISTS before CREATE by default", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed); + + expect(result).toContain("drop function if exists mathmodule.compute_value(jsonb, jsonb);"); + expect(result).toContain("create function mathmodule.compute_value("); + // DROP should come before CREATE + const dropIdx = result.indexOf("drop function"); + const createIdx = result.indexOf("create function"); + expect(dropIdx).toBeLessThan(createIdx); + }); + + test("adds DROP for procedure", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + const result = formatRoutine(parsed); + + expect(result).toContain("drop procedure if exists mathmodule.auth_logout(jsonb, text, text, text);"); + }); + + test("uppercase DROP when lowercase: false", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { lowercase: false }); + + expect(result).toContain("DROP FUNCTION IF EXISTS mathmodule.compute_value(JSONB, JSONB);"); + }); + + test("no DROP when dropBeforeCreate: false", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { dropBeforeCreate: false }); + + expect(result).not.toContain("drop function if exists"); + expect(result).not.toContain("DROP FUNCTION IF EXISTS"); + expect(result).toContain("create function"); + }); +}); + +describe("createOrReplace", () => { + test("uses CREATE OR REPLACE when enabled", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { createOrReplace: true }); + + expect(result).toContain("create or replace function mathmodule.compute_value("); + }); + + test("uses CREATE OR REPLACE for procedure", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + const result = formatRoutine(parsed, { createOrReplace: true }); + + expect(result).toContain("create or replace procedure mathmodule.auth_logout("); + }); + + test("uppercase CREATE OR REPLACE", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { createOrReplace: true, lowercase: false }); + + expect(result).toContain("CREATE OR REPLACE FUNCTION"); + }); + + test("no OR REPLACE by default", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed); + + expect(result).not.toContain("or replace"); + expect(result).not.toContain("OR REPLACE"); + }); + + test("both dropBeforeCreate and createOrReplace", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + const result = formatRoutine(parsed, { dropBeforeCreate: true, createOrReplace: true }); + + expect(result).toContain("drop function if exists"); + expect(result).toContain("create or replace function"); + }); +}); + +describe("isApiRoutine", () => { + test("routine with HTTP at start of comment is public", () => { + const [parsed] = parseRoutines(PG_DUMP_SETOF); + expect(isApiRoutine([parsed])).toBe(true); + }); + + test("procedure with HTTP at start of comment is public", () => { + const [parsed] = parseRoutines(PG_DUMP_PROCEDURE); + expect(isApiRoutine([parsed])).toBe(true); + }); + + test("routine without comment is private", () => { + const [parsed] = parseRoutines(PG_DUMP_FUNCTION); + expect(isApiRoutine([parsed])).toBe(false); + }); + + test("routine with non-HTTP comment is private", () => { + const sql = `CREATE FUNCTION f(_a int) RETURNS void LANGUAGE sql AS $$ $$;\nCOMMENT ON FUNCTION f(int) IS 'some internal helper';`; + const [parsed] = parseRoutines(sql); + expect(isApiRoutine([parsed])).toBe(false); + }); + + test("HTTP on a new line in comment is public", () => { + const sql = `CREATE FUNCTION f(_a int) RETURNS void LANGUAGE sql AS $$ $$;\nCOMMENT ON FUNCTION f(int) IS 'some prefix\nHTTP GET';`; + const [parsed] = parseRoutines(sql); + expect(isApiRoutine([parsed])).toBe(true); + }); + + test("HTTP mid-line is not public", () => { + const sql = `CREATE FUNCTION f(_a int) RETURNS void LANGUAGE sql AS $$ $$;\nCOMMENT ON FUNCTION f(int) IS 'uses HTTP internally';`; + const [parsed] = parseRoutines(sql); + expect(isApiRoutine([parsed])).toBe(false); + }); +}); + +describe("getGroupDir", () => { + const defaults = new Set(DEFAULT_SKIP_PREFIXES); + const none = new Set(); + + test("segment 0 returns empty (disabled)", () => { + expect(getGroupDir("auth_login", 0, defaults)).toBe(""); + }); + + test("segment 1 with non-generic prefix", () => { + expect(getGroupDir("auth_login", 1, defaults)).toBe("auth"); + }); + + test("segment 1 skips generic prefix to next segment", () => { + expect(getGroupDir("get_user_data", 1, defaults)).toBe("user"); + }); + + test("segment 1 without skip uses generic prefix as-is", () => { + expect(getGroupDir("get_user_data", 1, none)).toBe("get"); + }); + + test("skips multiple generic prefixes", () => { + expect(getGroupDir("get_all_users", 1, defaults)).toBe("users"); + }); + + test("stops at last segment even if generic", () => { + expect(getGroupDir("get", 1, defaults)).toBe("get"); + }); + + test("single word name returns that word", () => { + expect(getGroupDir("helpers", 1, defaults)).toBe("helpers"); + }); + + test("segment 2 uses second segment", () => { + expect(getGroupDir("auth_login_check", 2, defaults)).toBe("login"); + }); + + test("segment beyond name length returns empty", () => { + expect(getGroupDir("auth_login", 5, defaults)).toBe(""); + }); + + test("common verbs are skipped", () => { + expect(getGroupDir("insert_order_item", 1, defaults)).toBe("order"); + expect(getGroupDir("delete_session", 1, defaults)).toBe("session"); + expect(getGroupDir("is_admin", 1, defaults)).toBe("admin"); + expect(getGroupDir("compute_value", 1, defaults)).toBe("value"); + expect(getGroupDir("update_user_settings", 1, defaults)).toBe("user"); + }); + + test("non-generic first segment is kept", () => { + expect(getGroupDir("user_settings", 1, defaults)).toBe("user"); + expect(getGroupDir("math_compute", 1, defaults)).toBe("math"); + expect(getGroupDir("order_items", 1, defaults)).toBe("order"); + }); + + test("custom skip prefixes", () => { + const custom = new Set(["auth"]); + expect(getGroupDir("auth_login", 1, custom)).toBe("login"); + expect(getGroupDir("auth_login", 1, none)).toBe("auth"); + }); +}); + +describe("grants formatting", () => { + test("formats GRANT/REVOKE statements", () => { + const sql = ` +CREATE FUNCTION mathmodule.myfn(_a int) RETURNS void LANGUAGE sql AS $$ $$; +REVOKE ALL ON FUNCTION mathmodule.myfn(int) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION mathmodule.myfn(int) TO web_user; +`; + const [parsed] = parseRoutines(sql, { grants: true }); + const result = formatRoutine(parsed); + + expect(result).toContain("revoke all on function mathmodule.myfn(int) from PUBLIC;"); + expect(result).toContain("grant execute on function mathmodule.myfn(int) to web_user;"); + }); +}); diff --git a/src/parser/parser-tests/routine-body-hash.test.ts b/src/parser/parser-tests/routine-body-hash.test.ts index 8128765..6809bf9 100644 --- a/src/parser/parser-tests/routine-body-hash.test.ts +++ b/src/parser/parser-tests/routine-body-hash.test.ts @@ -6,12 +6,13 @@ describe("normalizeBody", () => { expect(normalizeBody("SELECT 1")).toBe("select 1"); }); - test("collapses whitespace", () => { - expect(normalizeBody("select _a + _b")).toBe("select _a + _b"); + test("preserves internal whitespace structure", () => { + // New behavior: spaces are NOT collapsed — whitespace differences are meaningful + expect(normalizeBody("select _a + _b")).toBe("select _a + _b"); }); - test("strips newlines and tabs", () => { - expect(normalizeBody("select\n _a\n +\n _b;")).toBe("select _a + _b;"); + test("preserves newlines but trims trailing spaces per line", () => { + expect(normalizeBody("select\n _a\n +\n _b;")).toBe("select\n _a\n +\n _b;"); }); test("trims leading and trailing whitespace", () => { @@ -22,9 +23,24 @@ describe("normalizeBody", () => { expect(normalizeBody("select\x001")).toBe("select 1"); }); - test("identical logic with different formatting normalizes the same", () => { + test("normalizes CRLF to LF", () => { + expect(normalizeBody("select\r\n_a")).toBe("select\n_a"); + }); + + test("collapses 3+ blank lines to 2", () => { + expect(normalizeBody("select 1;\n\n\n\nselect 2;")).toBe("select 1;\n\nselect 2;"); + }); + + test("different formatting produces different hash in strict mode", () => { const a = " SELECT\n _price * _rate;\n"; const b = "select _price * _rate;"; + // These have different whitespace structure — strict mode should detect this + expect(normalizeBody(a)).not.toBe(normalizeBody(b)); + }); + + test("identical formatting normalizes the same", () => { + const a = "select\n _price * _rate;"; + const b = "SELECT\n _price * _rate;"; expect(normalizeBody(a)).toBe(normalizeBody(b)); }); }); @@ -34,12 +50,18 @@ describe("bodyHash", () => { expect(bodyHash("select 1")).toBe(bodyHash("select 1")); }); - test("different formatting produces same hash", () => { - const a = " SELECT\n _a + _b;\n"; + test("same content with case difference produces same hash", () => { + const a = "SELECT _a + _b;"; const b = "select _a + _b;"; expect(bodyHash(a)).toBe(bodyHash(b)); }); + test("different whitespace produces different hash in strict mode", () => { + const a = "select _a + _b;"; + const b = "select _a + _b;"; + expect(bodyHash(a)).not.toBe(bodyHash(b)); + }); + test("different content produces different hash", () => { expect(bodyHash("select 1")).not.toBe(bodyHash("select 2")); }); diff --git a/src/parser/parser-tests/routine-handwritten.test.ts b/src/parser/parser-tests/routine-handwritten.test.ts index 152c664..b3cd341 100644 --- a/src/parser/parser-tests/routine-handwritten.test.ts +++ b/src/parser/parser-tests/routine-handwritten.test.ts @@ -20,9 +20,9 @@ $$;`; expect(r.name).toBe("create_order"); expect(r.schema).toBe("inventory"); expect(r.parameters).toHaveLength(3); - expect(r.parameters[0]).toEqual({ dir: null, name: "_customer_id", type: "integer" }); - expect(r.parameters[1]).toEqual({ dir: null, name: "_product_id", type: "integer" }); - expect(r.parameters[2]).toEqual({ dir: null, name: "_quantity", type: "integer" }); + expect(r.parameters[0]).toEqual({ dir: null, name: "_customer_id", type: "integer", default: null }); + expect(r.parameters[1]).toEqual({ dir: null, name: "_product_id", type: "integer", default: null }); + expect(r.parameters[2]).toEqual({ dir: null, name: "_quantity", type: "integer", default: null }); }); test("defaults with = instead of DEFAULT", () => { @@ -40,9 +40,9 @@ end; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toHaveLength(3); - expect(r.parameters[0]).toEqual({ dir: null, name: "_category", type: "text" }); - expect(r.parameters[1]).toEqual({ dir: null, name: "_min_price", type: "numeric" }); - expect(r.parameters[2]).toEqual({ dir: null, name: "_limit", type: "integer" }); + expect(r.parameters[0]).toEqual({ dir: null, name: "_category", type: "text", default: null }); + expect(r.parameters[1]).toEqual({ dir: null, name: "_min_price", type: "numeric", default: "0" }); + expect(r.parameters[2]).toEqual({ dir: null, name: "_limit", type: "integer", default: "50" }); }); test("attributes on separate lines", () => { @@ -102,7 +102,7 @@ $$;`; expect(r.name).toBe("restock"); expect(r.type).toBe("procedure"); expect(r.parameters).toHaveLength(3); - expect(r.parameters[2]).toEqual({ dir: null, name: "_user_id", type: "text" }); + expect(r.parameters[2]).toEqual({ dir: null, name: "_user_id", type: "text", default: "null" }); expect(r.body).toContain("declare"); expect(r.body).toContain("-- look up current stock level"); expect(r.body).toContain("raise notice"); @@ -207,7 +207,7 @@ $$ $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toHaveLength(2); - expect(r.parameters[0]).toEqual({ dir: null, name: "_tags", type: "text[]" }); - expect(r.parameters[1]).toEqual({ dir: null, name: "_ids", type: "integer[]" }); + expect(r.parameters[0]).toEqual({ dir: null, name: "_tags", type: "text[]", default: "array[]::text[]" }); + expect(r.parameters[1]).toEqual({ dir: null, name: "_ids", type: "integer[]", default: "'{}'::integer[]" }); }); }); diff --git a/src/parser/parser-tests/routine-params.test.ts b/src/parser/parser-tests/routine-params.test.ts index 5705e17..58a79cc 100644 --- a/src/parser/parser-tests/routine-params.test.ts +++ b/src/parser/parser-tests/routine-params.test.ts @@ -13,7 +13,7 @@ describe("parseRoutines — parameters", () => { const sql = `CREATE FUNCTION app.get_user(_id integer) RETURNS void LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_id", type: "integer" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_id", type: "integer", default: null }]); }); test("multiple named parameters", () => { @@ -21,9 +21,9 @@ describe("parseRoutines — parameters", () => { LANGUAGE plpgsql AS $$ begin return 1; end; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toEqual([ - { dir: null, name: "_customer", type: "text" }, - { dir: null, name: "_amount", type: "numeric" }, - { dir: null, name: "_note", type: "text" }, + { dir: null, name: "_customer", type: "text", default: null }, + { dir: null, name: "_amount", type: "numeric", default: null }, + { dir: null, name: "_note", type: "text", default: null }, ]); }); @@ -32,8 +32,8 @@ describe("parseRoutines — parameters", () => { LANGUAGE sql AS $$ SELECT $1 + $2; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toEqual([ - { dir: null, name: null, type: "integer" }, - { dir: null, name: null, type: "integer" }, + { dir: null, name: null, type: "integer", default: null }, + { dir: null, name: null, type: "integer", default: null }, ]); }); @@ -41,7 +41,7 @@ describe("parseRoutines — parameters", () => { const sql = `CREATE PROCEDURE app.archive(IN _days integer) LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: "in", name: "_days", type: "integer" }]); + expect(r.parameters).toEqual([{ dir: "in", name: "_days", type: "integer", default: null }]); }); test("OUT modifier", () => { @@ -49,8 +49,8 @@ describe("parseRoutines — parameters", () => { LANGUAGE plpgsql AS $$ begin _total := 0; _avg := 0; end; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toEqual([ - { dir: "out", name: "_total", type: "integer" }, - { dir: "out", name: "_avg", type: "numeric" }, + { dir: "out", name: "_total", type: "integer", default: null }, + { dir: "out", name: "_avg", type: "numeric", default: null }, ]); }); @@ -58,14 +58,14 @@ describe("parseRoutines — parameters", () => { const sql = `CREATE PROCEDURE app.increment(INOUT _counter integer) LANGUAGE plpgsql AS $$ begin _counter := _counter + 1; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: "inout", name: "_counter", type: "integer" }]); + expect(r.parameters).toEqual([{ dir: "inout", name: "_counter", type: "integer", default: null }]); }); test("VARIADIC modifier", () => { const sql = `CREATE FUNCTION app.concat_all(VARIADIC _parts text[]) RETURNS text LANGUAGE sql AS $$ SELECT array_to_string(_parts, ','); $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: "variadic", name: "_parts", type: "text[]" }]); + expect(r.parameters).toEqual([{ dir: "variadic", name: "_parts", type: "text[]", default: null }]); }); test("mixed IN and OUT modifiers", () => { @@ -73,9 +73,9 @@ describe("parseRoutines — parameters", () => { LANGUAGE plpgsql AS $$ begin _result := _a::numeric / _b; end; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toEqual([ - { dir: "in", name: "_a", type: "integer" }, - { dir: "in", name: "_b", type: "integer" }, - { dir: "out", name: "_result", type: "numeric" }, + { dir: "in", name: "_a", type: "integer", default: null }, + { dir: "in", name: "_b", type: "integer", default: null }, + { dir: "out", name: "_result", type: "numeric", default: null }, ]); }); @@ -83,42 +83,42 @@ describe("parseRoutines — parameters", () => { const sql = `CREATE PROCEDURE app.reset(IN integer) LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: "in", name: null, type: "integer" }]); + expect(r.parameters).toEqual([{ dir: "in", name: null, type: "integer", default: null }]); }); - test("strips simple DEFAULT value", () => { + test("preserves simple DEFAULT value", () => { const sql = `CREATE FUNCTION app.list_items(_limit integer DEFAULT 10) RETURNS void LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_limit", type: "integer" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_limit", type: "integer", default: "10" }]); }); - test("strips DEFAULT with cast", () => { + test("preserves DEFAULT with cast", () => { const sql = `CREATE FUNCTION app.search(_query text DEFAULT NULL::text) RETURNS void LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_query", type: "text" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_query", type: "text", default: "NULL::text" }]); }); - test("strips DEFAULT with string literal and cast", () => { + test("preserves DEFAULT with string literal and cast", () => { const sql = `CREATE FUNCTION app.greet(_lang text DEFAULT 'en'::text) RETURNS text LANGUAGE sql AS $$ SELECT 'hello'; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_lang", type: "text" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_lang", type: "text", default: "'en'::text" }]); }); - test("strips DEFAULT with jsonb literal", () => { + test("preserves DEFAULT with jsonb literal", () => { const sql = `CREATE FUNCTION app.process(_data jsonb DEFAULT '{}'::jsonb) RETURNS void LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_data", type: "jsonb" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_data", type: "jsonb", default: "'{}'::jsonb" }]); }); - test("strips DEFAULT with parenthesized expression", () => { + test("preserves DEFAULT with parenthesized expression", () => { const sql = `CREATE PROCEDURE app.do_thing(IN _flag text DEFAULT (NULL::text = NULL::text)) LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: "in", name: "_flag", type: "text" }]); + expect(r.parameters).toEqual([{ dir: "in", name: "_flag", type: "text", default: "(NULL::text = NULL::text)" }]); }); test("multiple parameters with defaults", () => { @@ -126,9 +126,9 @@ describe("parseRoutines — parameters", () => { LANGUAGE plpgsql AS $$ begin null; end; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toEqual([ - { dir: null, name: "_host", type: "text" }, - { dir: null, name: "_port", type: "integer" }, - { dir: null, name: "_ssl", type: "boolean" }, + { dir: null, name: "_host", type: "text", default: null }, + { dir: null, name: "_port", type: "integer", default: "5432" }, + { dir: null, name: "_ssl", type: "boolean", default: "true" }, ]); }); @@ -136,63 +136,63 @@ describe("parseRoutines — parameters", () => { const sql = `CREATE FUNCTION app.sum_all(_values integer[]) RETURNS integer LANGUAGE sql AS $$ SELECT 0; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_values", type: "integer[]" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_values", type: "integer[]", default: null }]); }); test("unnamed multi-word type: character varying", () => { const sql = `CREATE FUNCTION app.echo(character varying) RETURNS character varying LANGUAGE sql AS $$ SELECT $1; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: null, type: "character varying" }]); + expect(r.parameters).toEqual([{ dir: null, name: null, type: "character varying", default: null }]); }); test("named multi-word type: character varying", () => { const sql = `CREATE FUNCTION app.echo(_val character varying) RETURNS character varying LANGUAGE sql AS $$ SELECT _val; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_val", type: "character varying" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_val", type: "character varying", default: null }]); }); test("unnamed multi-word type: double precision", () => { const sql = `CREATE FUNCTION app.square(double precision) RETURNS double precision LANGUAGE sql AS $$ SELECT $1 * $1; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: null, type: "double precision" }]); + expect(r.parameters).toEqual([{ dir: null, name: null, type: "double precision", default: null }]); }); test("named multi-word type: timestamp with time zone", () => { const sql = `CREATE FUNCTION app.format_ts(_ts timestamp with time zone) RETURNS text LANGUAGE sql AS $$ SELECT _ts::text; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_ts", type: "timestamp with time zone" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_ts", type: "timestamp with time zone", default: null }]); }); test("unnamed multi-word type: timestamp without time zone", () => { const sql = `CREATE FUNCTION app.to_epoch(timestamp without time zone) RETURNS bigint LANGUAGE sql AS $$ SELECT 0::bigint; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: null, type: "timestamp without time zone" }]); + expect(r.parameters).toEqual([{ dir: null, name: null, type: "timestamp without time zone", default: null }]); }); test("numeric with precision", () => { const sql = `CREATE FUNCTION app.round_price(_val numeric(10,2)) RETURNS numeric LANGUAGE sql AS $$ SELECT _val; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_val", type: "numeric(10,2)" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_val", type: "numeric(10,2)", default: null }]); }); test("case insensitive modifiers", () => { const sql = `create procedure app.do_it(in _x integer default 0) language plpgsql as $$ begin null; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: "in", name: "_x", type: "integer" }]); + expect(r.parameters).toEqual([{ dir: "in", name: "_x", type: "integer", default: "0" }]); }); test("RETURNS TABLE does not pollute parameters", () => { const sql = `CREATE FUNCTION app.list_users(_active boolean) RETURNS TABLE(id integer, name text) LANGUAGE plpgsql AS $$ begin return query select 1, 'a'::text; end; $$;`; const [r] = parseRoutines(sql); - expect(r.parameters).toEqual([{ dir: null, name: "_active", type: "boolean" }]); + expect(r.parameters).toEqual([{ dir: null, name: "_active", type: "boolean", default: null }]); }); test("real pg_dump output with complex defaults", () => { @@ -209,10 +209,10 @@ end; $$;`; const [r] = parseRoutines(sql); expect(r.parameters).toEqual([ - { dir: null, name: "_category", type: "text" }, - { dir: null, name: "_min_price", type: "numeric" }, - { dir: null, name: "_tags", type: "jsonb" }, - { dir: null, name: "_limit", type: "integer" }, + { dir: null, name: "_category", type: "text", default: null }, + { dir: null, name: "_min_price", type: "numeric", default: "0" }, + { dir: null, name: "_tags", type: "jsonb", default: "'{}'::jsonb" }, + { dir: null, name: "_limit", type: "integer", default: "100" }, ]); }); @@ -224,9 +224,9 @@ CREATE PROCEDURE app.log_event(IN _msg text) LANGUAGE plpgsql AS $$ begin null; end; $$;`; const results = parseRoutines(sql); expect(results[0].parameters).toEqual([ - { dir: null, name: "_a", type: "integer" }, - { dir: null, name: "_b", type: "integer" }, + { dir: null, name: "_a", type: "integer", default: null }, + { dir: null, name: "_b", type: "integer", default: null }, ]); - expect(results[1].parameters).toEqual([{ dir: "in", name: "_msg", type: "text" }]); + expect(results[1].parameters).toEqual([{ dir: "in", name: "_msg", type: "text", default: null }]); }); }); diff --git a/src/parser/routine.ts b/src/parser/routine.ts index 96c4c41..32f7409 100644 --- a/src/parser/routine.ts +++ b/src/parser/routine.ts @@ -4,6 +4,7 @@ export interface RoutineParameter { dir: ParameterDir | null; name: string | null; type: string; + default: string | null; } export interface TableColumn { @@ -148,20 +149,31 @@ function parseOneParam(raw: string): RoutineParameter { dir = modeMatch[1].toLowerCase() as ParameterDir; s = s.substring(modeMatch[0].length).trim(); } - s = s.replace(/\s+DEFAULT\s+.*/i, "").replace(/\s*=\s.*/, "").trim(); - if (!s) return { dir, name: null, type: "" }; + // Extract default value before stripping it + let defaultVal: string | null = null; + const defaultMatch = s.match(/\s+DEFAULT\s+(.*)/i); + const eqMatch = !defaultMatch ? s.match(/\s*=\s+(.*)/) : null; + if (defaultMatch) { + defaultVal = defaultMatch[1].trim(); + s = s.substring(0, defaultMatch.index!).trim(); + } else if (eqMatch) { + defaultVal = eqMatch[1].trim(); + s = s.substring(0, eqMatch.index!).trim(); + } + + if (!s) return { dir, name: null, type: "", default: defaultVal }; if (MULTI_WORD_TYPE_RE.test(s)) { - return { dir, name: null, type: s }; + return { dir, name: null, type: s, default: defaultVal }; } const firstSpace = s.search(/\s/); if (firstSpace === -1) { - return { dir, name: null, type: s }; + return { dir, name: null, type: s, default: defaultVal }; } - return { dir, name: s.substring(0, firstSpace), type: s.substring(firstSpace + 1).trim() }; + return { dir, name: s.substring(0, firstSpace), type: s.substring(firstSpace + 1).trim(), default: defaultVal }; } function parseParameters(paramStr: string): RoutineParameter[] { diff --git a/src/test/db.ts b/src/test/db.ts index d44000e..14c6bf5 100644 --- a/src/test/db.ts +++ b/src/test/db.ts @@ -1,6 +1,10 @@ /// import { resolve } from "node:path"; -import { loadEnvFile } from "../utils/env.ts"; +import { existsSync } from "node:fs"; +import { loadEnvFile, resolvePlaceholders } from "../utils/env.ts"; + +/** Database names that must NEVER be dropped. */ +const PROTECTED_DATABASES = new Set(["postgres", "template0", "template1"]); export interface TestConfig { host: string; @@ -16,8 +20,31 @@ export async function loadTestConfig(): Promise { if (cachedConfig) return cachedConfig; const envFile = resolve(import.meta.dir, "../../test.env"); + + // Hard fail if test.env is missing — never guess database config + if (!existsSync(envFile)) { + throw new Error( + `test.env not found at ${envFile}. ` + + `Create it with PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE pointing to a test database. ` + + `This file is required to prevent accidentally dropping a production database.` + ); + } + const fileVars = await loadEnvFile(envFile); + // Require PGDATABASE to be explicitly set — never use a default + if (!fileVars.PGDATABASE) { + throw new Error( + `PGDATABASE is not set in test.env. ` + + `Explicitly set the test database name to prevent accidental drops.` + ); + } + + // Replace {placeholders} — e.g. {test_suffix} gets a random string + const { resolved: database } = resolvePlaceholders(fileVars.PGDATABASE, { + test_suffix: Math.random().toString(36).slice(2, 10), + }); + // Only use test.env for config — never fall through to process.env // to prevent accidentally dropping a real database (e.g. from .env) cachedConfig = { @@ -25,11 +52,29 @@ export async function loadTestConfig(): Promise { port: fileVars.PGPORT ?? "5432", user: fileVars.PGUSER ?? "postgres", password: fileVars.PGPASSWORD ?? "postgres", - database: fileVars.PGDATABASE ?? "pgdev_test", + database, }; + return cachedConfig; } +/** + * Validate that a database name is safe to drop. + * Throws if the name matches a protected database or doesn't contain "test". + */ +function assertSafeToDropDatabase(name: string): void { + if (PROTECTED_DATABASES.has(name.toLowerCase())) { + throw new Error(`FATAL: refusing to drop protected database "${name}"`); + } + if (!name.toLowerCase().includes("test")) { + throw new Error( + `FATAL: refusing to drop database "${name}" — name does not contain "test". ` + + `This safeguard prevents accidental drops of production databases. ` + + `If this is a test database, include "test" in the name (e.g. "${name}_test").` + ); + } +} + function connect(database?: string) { const cfg = cachedConfig!; return new Bun.SQL({ @@ -45,11 +90,21 @@ export async function createTestDb(): Promise { const cfg = await loadTestConfig(); const db = cfg.database; - console.error(`[test] Recreating database "${db}"...`); + assertSafeToDropDatabase(db); const admin = connect("postgres"); try { - await admin.unsafe(`DROP DATABASE IF EXISTS "${db}" WITH (FORCE)`); + // Drop any leftover test databases from previous runs (random suffixes accumulate) + const leftover = await admin.unsafe( + `SELECT datname FROM pg_database WHERE datname LIKE 'pgdev_test_%'` + ); + for (const row of leftover) { + const name = (row as Record).datname; + assertSafeToDropDatabase(name); + await admin.unsafe(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`); + } + + console.error(`[test] Creating database "${db}"...`); await admin.unsafe(`CREATE DATABASE "${db}"`); } finally { await admin.close(); diff --git a/src/utils/env.test.ts b/src/utils/env.test.ts new file mode 100644 index 0000000..3cf5d69 --- /dev/null +++ b/src/utils/env.test.ts @@ -0,0 +1,65 @@ +import { describe, test, expect } from "bun:test"; +import { resolvePlaceholders } from "./env.ts"; + +describe("resolvePlaceholders", () => { + test("replaces a single placeholder", () => { + const { resolved, unresolved } = resolvePlaceholders("hello {name}", { name: "world" }); + expect(resolved).toBe("hello world"); + expect(unresolved).toEqual([]); + }); + + test("replaces multiple placeholders", () => { + const { resolved } = resolvePlaceholders("{a}_{b}_{c}", { a: "1", b: "2", c: "3" }); + expect(resolved).toBe("1_2_3"); + }); + + test("replaces same placeholder multiple times", () => { + const { resolved } = resolvePlaceholders("{x}+{x}", { x: "5" }); + expect(resolved).toBe("5+5"); + }); + + test("returns unresolved keys for missing placeholders", () => { + const { resolved, unresolved } = resolvePlaceholders("{a}_{b}", { a: "1" }); + expect(resolved).toBe("1_{b}"); + expect(unresolved).toEqual(["b"]); + }); + + test("returns string unchanged when no placeholders", () => { + const { resolved, unresolved } = resolvePlaceholders("no placeholders here", { x: "1" }); + expect(resolved).toBe("no placeholders here"); + expect(unresolved).toEqual([]); + }); + + test("returns empty string unchanged", () => { + const { resolved } = resolvePlaceholders("", { x: "1" }); + expect(resolved).toBe(""); + }); + + test("handles empty dictionary", () => { + const { resolved, unresolved } = resolvePlaceholders("{a}_{b}", {}); + expect(resolved).toBe("{a}_{b}"); + expect(unresolved).toEqual(["a", "b"]); + }); + + test("replaces with empty string value", () => { + const { resolved } = resolvePlaceholders("pre{x}post", { x: "" }); + expect(resolved).toBe("prepost"); + }); + + test("handles adjacent placeholders", () => { + const { resolved } = resolvePlaceholders("{a}{b}", { a: "1", b: "2" }); + expect(resolved).toBe("12"); + }); + + test("nested braces — inner key includes leading brace", () => { + // {{a}} matches {a as the key (regex is greedy non-}), so it stays unresolved + const { resolved, unresolved } = resolvePlaceholders("{{a}}", { a: "1" }); + expect(resolved).toBe("{{a}}"); + expect(unresolved).toEqual(["{a"]); + }); + + test("handles special regex characters in values", () => { + const { resolved } = resolvePlaceholders("{x}", { x: "$1.00 (test)" }); + expect(resolved).toBe("$1.00 (test)"); + }); +}); diff --git a/src/utils/env.ts b/src/utils/env.ts index 515b568..005b94c 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -1,18 +1,23 @@ import { resolve } from "node:path"; -export function resolveEnvVars( +/** Replace `{key}` placeholders in a string using values from a dictionary. */ +export function resolvePlaceholders( value: string, - envDict: Record, + dict: Record, ): { resolved: string; unresolved: string[] } { + if (!value.includes("{")) return { resolved: value, unresolved: [] }; const unresolved: string[] = []; - const resolved = value.replace(/\{([^}]+)\}/g, (_match, varName: string) => { - if (varName in envDict) return envDict[varName]; - unresolved.push(varName); - return `{${varName}}`; + const resolved = value.replace(/\{([^}]+)\}/g, (_match, key: string) => { + if (key in dict) return dict[key]; + unresolved.push(key); + return `{${key}}`; }); return { resolved, unresolved }; } +/** @deprecated Use `resolvePlaceholders` instead. */ +export const resolveEnvVars = resolvePlaceholders; + export async function loadEnvFile(path: string): Promise> { const file = Bun.file(path); if (!(await file.exists())) return {}; diff --git a/src/utils/files.ts b/src/utils/files.ts new file mode 100644 index 0000000..df7c6fb --- /dev/null +++ b/src/utils/files.ts @@ -0,0 +1,16 @@ +import { resolve } from "node:path"; +import { readdirSync } from "node:fs"; + +/** Recursively find all .sql files in a directory. */ +export function findSqlFiles(dir: string): string[] { + const results: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = resolve(dir, entry.name); + if (entry.isDirectory()) { + results.push(...findSqlFiles(full)); + } else if (entry.isFile() && entry.name.endsWith(".sql")) { + results.push(full); + } + } + return results.sort(); +} From a22ab6e5369edcf71f880fa56cb98d98312ff863 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 13 Mar 2026 14:47:31 +0100 Subject: [PATCH 3/9] Add quoted identifier support, flexible directory grouping, and VIEW extraction - Fix parser to handle double-quoted SQL identifiers (e.g. _."exists") in CREATE, COMMENT ON, and GRANT/REVOKE statements - Formatter preserves quoting via nameQuoted/schemaQuoted flags - Replace group_order string with ordered array of dimensions: "type", "schema", "name", "kind" for flexible directory nesting - Add routine_types config to control which object types are extracted into individual files (default: FUNCTION, PROCEDURE) - Add VIEW support in sync: TOC parsing, extraction as raw SQL, existing file indexing by filename stem - Add routine_types validation against supported types - Warn when group_order dimensions have missing config Co-Authored-By: Claude Opus 4.6 --- src/commands/config.ts | 36 +++-- src/commands/sync.test.ts | 90 +++++++++++- src/commands/sync.ts | 142 +++++++++++++------ src/config.ts | 22 ++- src/parser/formatter.ts | 19 ++- src/parser/parser-tests/formatter.test.ts | 50 +++++++ src/parser/parser-tests/routine-name.test.ts | 80 +++++++++++ src/parser/routine.ts | 65 +++++++-- 8 files changed, 423 insertions(+), 81 deletions(-) diff --git a/src/commands/config.ts b/src/commands/config.ts index 3749ddf..604fd51 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -2251,11 +2251,17 @@ export async function configCommand(config: PgdevConfig): Promise { value: currentConfig.project.skip_prefixes.length === 0 ? pc.dim("defaults") : `${currentConfig.project.skip_prefixes.length} custom`, help: "Prefixes to skip when grouping by name segment.\nEmpty = use built-in defaults (get, set, delete, insert, is, has, etc.).\nCustomize to control which verb prefixes are skipped.\nE.g. get_user_data → user/ instead of get/.", }, + { + key: "routine_types", + label: "Routine types", + value: currentConfig.project.routine_types.length > 0 ? currentConfig.project.routine_types.join(", ") : pc.dim("none"), + help: "Object types to extract into individual files (excluded from schema.sql).\nDefault: FUNCTION, PROCEDURE. Add AGGREGATE if needed.", + }, { key: "group_order", label: "Group order", - value: currentConfig.project.group_order, - help: "Directory nesting order when both api/internal and group segment dirs are used.\n\"type_first\" = api/auth/auth_login.sql\n\"group_first\" = auth/api/auth_login.sql", + value: currentConfig.project.group_order.length > 0 ? currentConfig.project.group_order.join(", ") : pc.dim("flat"), + help: "Directory nesting order. Each element adds a subdirectory level.\nAvailable: type (api/internal), schema, name (name segment), kind (function/procedure).\nExample: type, schema, name → api/myschema/auth/routine.sql\nEmpty = flat (all files in routines_dir).", }, ], }, @@ -2388,15 +2394,25 @@ export async function configCommand(config: PgdevConfig): Promise { updateConfigArraySync("project", "skip_prefixes", prefixes); lastStatus = prefixes.length === 0 ? "skip_prefixes = [] (using defaults)" : `skip_prefixes = ${prefixes.length} custom`; } + } else if (choice.key === "routine_types") { + const current = currentConfig.project.routine_types.join(", "); + const value = await askValue("Routine types (comma-separated, e.g. FUNCTION, PROCEDURE)", current); + if (value !== null) { + const types = value.trim() === "" + ? [] + : value.split(",").map((s) => s.trim().toUpperCase()).filter(Boolean); + updateConfigArraySync("project", "routine_types", types); + lastStatus = types.length === 0 ? "routine_types = [] (nothing extracted)" : `routine_types = [${types.join(", ")}]`; + } } else if (choice.key === "group_order") { - const idx = await ask("Group order", [ - { label: "type_first", description: "api/auth/ — type dir first, then group" }, - { label: "group_first", description: "auth/api/ — group dir first, then type" }, - ]); - if (idx >= 0) { - const value = idx === 0 ? "type_first" : "group_first"; - await updateConfig("project", "group_order", value); - lastStatus = `group_order = "${value}"`; + const current = currentConfig.project.group_order.join(", "); + const value = await askValue("Group order (comma-separated: type, schema, name, kind)", current); + if (value !== null) { + const dims = value.trim() === "" + ? [] + : value.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean); + updateConfigArraySync("project", "group_order", dims); + lastStatus = dims.length === 0 ? "group_order = [] (flat)" : `group_order = [${dims.join(", ")}]`; } } else if (choice.key === "fmt_lowercase") { const newValue = !currentConfig.format.lowercase; diff --git a/src/commands/sync.test.ts b/src/commands/sync.test.ts index b8d4ccd..b6e5e0c 100644 --- a/src/commands/sync.test.ts +++ b/src/commands/sync.test.ts @@ -36,6 +36,18 @@ describe("parseRoutineGroups", () => { ]); }); + test("captures schema from TOC", () => { + const product = groups.find((g) => g.name === "get_product")!; + expect(product.schema).toBe("inventory"); + }); + + test("captures routineType from TOC", () => { + const product = groups.find((g) => g.name === "get_product")!; + expect(product.routineType).toBe("function"); + const restock = groups.find((g) => g.name === "restock_item")!; + expect(restock.routineType).toBe("procedure"); + }); + test("includes COMMENT lines with the routine", () => { const product = groups.find((g) => g.name === "get_product")!; expect(product.tocLines.length).toBe(2); @@ -69,7 +81,7 @@ describe("parseRoutineGroups", () => { expect(allNames).not.toContain("products"); }); - test("excludes ACL lines by default (grants=false)", () => { + test("excludes ACL lines by default", () => { const tocWithAcl = ` 1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb 5800; 0 0 ACL inventory FUNCTION get_product(_product_id integer) shopdb @@ -79,12 +91,12 @@ describe("parseRoutineGroups", () => { expect(result[0].tocLines[0]).toContain("FUNCTION"); }); - test("includes ACL lines when grants=true", () => { + test("includes ACL lines when includeGrants=true", () => { const tocWithAcl = ` 1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb 5800; 0 0 ACL inventory FUNCTION get_product(_product_id integer) shopdb `; - const result = parseRoutineGroups(tocWithAcl, true); + const result = parseRoutineGroups(tocWithAcl, { includeGrants: true }); expect(result[0].tocLines.length).toBe(2); expect(result[0].tocLines[1]).toContain("ACL"); }); @@ -98,4 +110,76 @@ describe("parseRoutineGroups", () => { `); expect(empty).toEqual([]); }); + + test("filters by custom routineTypes", () => { + const functionsOnly = parseRoutineGroups(SAMPLE_TOC, { routineTypes: ["FUNCTION"] }); + expect(functionsOnly.length).toBe(3); + expect(functionsOnly.every((g) => g.routineType === "function")).toBe(true); + expect(functionsOnly.map((g) => g.name)).not.toContain("restock_item"); + }); + + test("includes AGGREGATE when in routineTypes", () => { + const tocWithAgg = ` +1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb +1500; 1255 586800 AGGREGATE inventory avg_price(numeric) shopdb +`; + const result = parseRoutineGroups(tocWithAgg, { routineTypes: ["FUNCTION", "AGGREGATE"] }); + expect(result.length).toBe(2); + expect(result[1].name).toBe("avg_price"); + expect(result[1].routineType).toBe("aggregate"); + expect(result[1].schema).toBe("inventory"); + }); + + test("parses VIEW TOC entries (no parentheses)", () => { + const tocWithView = ` +1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb +1300; 1259 586800 VIEW inventory product_summary shopdb +`; + const result = parseRoutineGroups(tocWithView, { routineTypes: ["FUNCTION", "VIEW"] }); + expect(result.length).toBe(2); + expect(result[1].name).toBe("product_summary"); + expect(result[1].routineType).toBe("view"); + expect(result[1].schema).toBe("inventory"); + }); + + test("VIEW COMMENT lines are grouped with the view", () => { + const toc = ` +1300; 1259 586800 VIEW inventory product_summary shopdb +5803; 0 0 COMMENT inventory VIEW product_summary shopdb +`; + const result = parseRoutineGroups(toc, { routineTypes: ["VIEW"] }); + expect(result.length).toBe(1); + expect(result[0].name).toBe("product_summary"); + expect(result[0].tocLines.length).toBe(2); + expect(result[0].tocLines[1]).toContain("COMMENT"); + }); + + test("VIEW ACL lines are included with includeGrants", () => { + const toc = ` +1300; 1259 586800 VIEW inventory product_summary shopdb +5804; 0 0 ACL inventory VIEW product_summary shopdb +`; + const result = parseRoutineGroups(toc, { routineTypes: ["VIEW"], includeGrants: true }); + expect(result[0].tocLines.length).toBe(2); + expect(result[0].tocLines[1]).toContain("ACL"); + }); + + test("mixed FUNCTION and VIEW types in same TOC", () => { + const toc = ` +1290; 1255 586699 FUNCTION inventory get_product(integer) shopdb +5801; 0 0 COMMENT inventory FUNCTION get_product(_product_id integer) shopdb +1300; 1259 586800 VIEW inventory product_summary shopdb +5803; 0 0 COMMENT inventory VIEW product_summary shopdb +1495; 1255 586705 PROCEDURE inventory restock_item(integer, integer) shopdb +`; + const result = parseRoutineGroups(toc, { routineTypes: ["FUNCTION", "PROCEDURE", "VIEW"] }); + expect(result.length).toBe(3); + expect(result.map((g) => g.name)).toEqual(["get_product", "product_summary", "restock_item"]); + expect(result[0].routineType).toBe("function"); + expect(result[0].tocLines.length).toBe(2); + expect(result[1].routineType).toBe("view"); + expect(result[1].tocLines.length).toBe(2); + expect(result[2].routineType).toBe("procedure"); + expect(result[2].tocLines.length).toBe(1); + }); }); diff --git a/src/commands/sync.ts b/src/commands/sync.ts index 7e6e1a1..74417a8 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -6,7 +6,7 @@ import { resolveConnection } from "./exec.ts"; import { splitCommand } from "../cli.ts"; import { error, success, pc, formatCmd } from "../utils/terminal.ts"; import { findSqlFiles } from "../utils/files.ts"; -import { parseRoutines } from "../parser/routine.ts"; +import { parseRoutines, unquoteIdent } from "../parser/routine.ts"; import { isApiRoutine, getGroupDir, formatRoutines, configToFormatOptions, DEFAULT_SKIP_PREFIXES } from "../parser/formatter.ts"; function cleanRestoreOutput(sql: string): string { @@ -16,54 +16,76 @@ function cleanRestoreOutput(sql: string): string { !/^\\(un)?restrict\b/.test(line) && !/^SET\s+\w+/.test(line) && !/^SELECT\s+pg_catalog\.set_config\b/.test(line) && - !/^ALTER\s+(FUNCTION|PROCEDURE)\s+.+\s+OWNER\s+TO\b/.test(line), + !/^ALTER\s+(FUNCTION|PROCEDURE|VIEW|AGGREGATE)\s+.+\s+OWNER\s+TO\b/.test(line), ) .join("\n"); } -interface RoutineGroup { +export interface RoutineGroup { name: string; + schema: string; + routineType: string; tocLines: string[]; } -export function parseRoutineGroups(tocOutput: string, includeGrants = false): RoutineGroup[] { - const groups = new Map(); +/** Supported routine_types values. */ +export const SUPPORTED_ROUTINE_TYPES = ["FUNCTION", "PROCEDURE", "AGGREGATE", "VIEW"]; + +export function parseRoutineGroups( + tocOutput: string, + options: { includeGrants?: boolean; routineTypes?: string[] } = {}, +): RoutineGroup[] { + const { includeGrants = false, routineTypes = ["FUNCTION", "PROCEDURE"] } = options; + const typePattern = routineTypes.join("|"); + + // Definition: "1290; 1255 586699 FUNCTION schema name(...) owner" + // or for VIEW: "1290; 1259 586699 VIEW schema view_name owner" + // (\S+?) with lazy match stops at ( or whitespace — works for both. + const routineRe = new RegExp( + `^\\d+;\\s+\\d+\\s+\\d+\\s+(${typePattern})\\s+(\\S+)\\s+(\\S+?)(?:\\(|\\s)`, + ); + // COMMENT: "5801; 0 0 COMMENT schema FUNCTION name(...) owner" + // or: "5801; 0 0 COMMENT schema VIEW view_name owner" + const commentRe = new RegExp( + `^\\d+;\\s+0\\s+0\\s+COMMENT\\s+\\S+\\s+(?:${typePattern})\\s+(\\S+?)(?:\\(|\\s)`, + ); + // ACL: "5800; 0 0 ACL schema FUNCTION name(...) owner" + const aclRe = new RegExp( + `^\\d+;\\s+0\\s+0\\s+ACL\\s+\\S+\\s+(?:${typePattern})\\s+(\\S+?)(?:\\(|\\s)`, + ); + + const groups = new Map(); const groupOrder: string[] = []; for (const line of tocOutput.split("\n")) { if (line.startsWith(";") || !line.trim()) continue; - // Routine definition: "1290; 1255 586699 FUNCTION mathmodule auth_login(...) legendea" - const routineMatch = line.match(/^\d+;\s+1255\s+\d+\s+(?:FUNCTION|PROCEDURE)\s+\S+\s+(\S+)\(/); + const routineMatch = line.match(routineRe); if (routineMatch) { - const name = routineMatch[1]; + const [, routineType, schema, name] = routineMatch; if (!groups.has(name)) { - groups.set(name, []); + groups.set(name, { name, schema, routineType: routineType.toLowerCase(), tocLines: [] }); groupOrder.push(name); } - groups.get(name)!.push(line); + groups.get(name)!.tocLines.push(line); continue; } - // COMMENT on routine: "5801; 0 0 COMMENT mathmodule FUNCTION auth_login(...) legendea" - const commentMatch = line.match(/^\d+;\s+0\s+0\s+COMMENT\s+\S+\s+(?:FUNCTION|PROCEDURE)\s+(\S+)\(/); + const commentMatch = line.match(commentRe); if (commentMatch) { - const name = commentMatch[1]; - groups.get(name)?.push(line); + groups.get(commentMatch[1])?.tocLines.push(line); continue; } - // ACL on routine: "5800; 0 0 ACL mathmodule FUNCTION auth_login(...) legendea" if (includeGrants) { - const aclMatch = line.match(/^\d+;\s+0\s+0\s+ACL\s+\S+\s+(?:FUNCTION|PROCEDURE)\s+(\S+)\(/); + const aclMatch = line.match(aclRe); if (aclMatch) { - const name = aclMatch[1]; - groups.get(name)?.push(line); + groups.get(aclMatch[1])?.tocLines.push(line); } } } - return groupOrder.map((name) => ({ name, tocLines: groups.get(name)! })); + return groupOrder.map((name) => groups.get(name)!); } export async function syncCommand(config: PgdevConfig): Promise { @@ -79,6 +101,13 @@ export async function syncCommand(config: PgdevConfig): Promise { process.exit(1); } + // Validate routine_types + const unsupported = config.project.routine_types.filter((t) => !SUPPORTED_ROUTINE_TYPES.includes(t)); + if (unsupported.length > 0) { + console.error(error(`Unsupported routine_types: ${unsupported.join(", ")}. Supported: ${SUPPORTED_ROUTINE_TYPES.join(", ")}`)); + process.exit(1); + } + const schemas = config.project.schemas ?? []; const fields = await resolveConnection(config); @@ -137,9 +166,13 @@ export async function syncCommand(config: PgdevConfig): Promise { process.exit(listExit); } + // Filter out configured routine types from schema.sql TOC + const routineTypeFilterRe = config.project.routine_types.length > 0 + ? new RegExp(`\\b(?:${config.project.routine_types.join("|")})\\b`) + : null; const filteredToc = listStdout .split("\n") - .filter((line) => !/\bFUNCTION\b|\bPROCEDURE\b/.test(line)) + .filter((line) => !routineTypeFilterRe || !routineTypeFilterRe.test(line)) .join("\n"); const tocFile = resolve(tmpdir(), `pgdev-toc-${Date.now()}.list`); @@ -181,6 +214,14 @@ export async function syncCommand(config: PgdevConfig): Promise { // Step 4: Extract routines to individual files const routinesDir = config.project.routines_dir; if (routinesDir) { + // Warn about group_order dimensions with missing config + const groupOrder = config.project.group_order; + if (groupOrder.includes("type") && !config.project.api_dir && !config.project.internal_dir) { + console.error(pc.yellow(`Warning: group_order includes "type" but api_dir and internal_dir are both empty — "type" dimension will have no effect.`)); + } + if (groupOrder.includes("name") && config.project.group_segment <= 0) { + console.error(pc.yellow(`Warning: group_order includes "name" but group_segment is 0 (disabled) — "name" dimension will have no effect.`)); + } const fullRoutinesDir = resolve(process.cwd(), routinesDir); mkdirSync(fullRoutinesDir, { recursive: true }); @@ -190,12 +231,22 @@ export async function syncCommand(config: PgdevConfig): Promise { for (const file of existingFiles) { const content = await Bun.file(file).text(); const parsed = parseRoutines(content); - for (const r of parsed) { - existingRoutines.set(r.name, { file, content }); + if (parsed.length > 0) { + for (const r of parsed) { + existingRoutines.set(r.name, { file, content }); + } + } else { + // Non-parseable files (e.g. VIEWs) — index by filename stem + const stem = file.split("/").pop()!.replace(/\.sql$/i, ""); + existingRoutines.set(stem, { file, content }); } } - const routineGroups = parseRoutineGroups(listStdout, config.project.grants); + const routineTypes = config.project.routine_types; + const routineGroups = parseRoutineGroups(listStdout, { + includeGrants: config.project.grants, + routineTypes, + }); if (routineGroups.length > 0) { const routineTocFile = resolve(tmpdir(), `pgdev-routine-toc-${Date.now()}.list`); @@ -228,13 +279,15 @@ export async function syncCommand(config: PgdevConfig): Promise { const formatOpts = configToFormatOptions(config.format); const parsed = parseRoutines(cleaned, { grants: config.project.grants }); const routineSql = parsed.length > 0 ? formatRoutines(parsed, formatOpts) : cleaned; - const existing = existingRoutines.get(group.name); + // Strip quotes from TOC name for lookups/filenames (parser stores bare names) + const bareName = unquoteIdent(group.name).bare; + const existing = existingRoutines.get(bareName); if (existing && existing.content.trimEnd() === routineSql.trimEnd()) { // Content identical — skip unchanged++; if (config.verbose) { - console.error(pc.dim(` ${group.name} (unchanged)`)); + console.error(pc.dim(` ${bareName} (unchanged)`)); } continue; } @@ -244,40 +297,37 @@ export async function syncCommand(config: PgdevConfig): Promise { if (existing) { outFile = existing.file; } else { - // Determine base dir: api_dir or internal_dir if configured - const isApi = isApiRoutine(parsed); - const typeSubDir = isApi ? config.project.api_dir : config.project.internal_dir; - - // Determine group dir from name segment - const skipSet = new Set(config.project.skip_prefixes.length > 0 ? config.project.skip_prefixes : DEFAULT_SKIP_PREFIXES); - const groupSubDir = getGroupDir( - group.name, - config.project.group_segment, - skipSet, - ); - + // Build target directory from group_order dimensions let targetDir = fullRoutinesDir; - if (config.project.group_order === "group_first") { - if (groupSubDir) targetDir = resolve(targetDir, groupSubDir); - if (typeSubDir) targetDir = resolve(targetDir, typeSubDir); - } else { - if (typeSubDir) targetDir = resolve(targetDir, typeSubDir); - if (groupSubDir) targetDir = resolve(targetDir, groupSubDir); + for (const dim of config.project.group_order) { + let subDir = ""; + if (dim === "type") { + const isApi = isApiRoutine(parsed); + subDir = isApi ? config.project.api_dir : config.project.internal_dir; + } else if (dim === "schema") { + subDir = unquoteIdent(group.schema).bare; + } else if (dim === "name") { + const skipSet = new Set(config.project.skip_prefixes.length > 0 ? config.project.skip_prefixes : DEFAULT_SKIP_PREFIXES); + subDir = getGroupDir(bareName, config.project.group_segment, skipSet); + } else if (dim === "kind") { + subDir = group.routineType; + } + if (subDir) targetDir = resolve(targetDir, subDir); } if (targetDir !== fullRoutinesDir) mkdirSync(targetDir, { recursive: true }); - outFile = resolve(targetDir, `${group.name}.sql`); + outFile = resolve(targetDir, `${bareName}.sql`); } await Bun.write(outFile, routineSql); if (existing) { updated++; if (config.verbose) { - console.error(pc.yellow(` ${group.name} (updated)`)); + console.error(pc.yellow(` ${bareName} (updated)`)); } } else { created++; if (config.verbose) { - console.error(pc.green(` ${group.name} (created)`)); + console.error(pc.green(` ${bareName} (created)`)); } } } diff --git a/src/config.ts b/src/config.ts index c62f698..5867ce0 100644 --- a/src/config.ts +++ b/src/config.ts @@ -23,6 +23,8 @@ export interface CommandsConfig { schemas_query: string; } +export type GroupDimension = "type" | "schema" | "name" | "kind"; + export interface ProjectConfig { routines_dir: string; migrations_dir: string; @@ -30,11 +32,14 @@ export interface ProjectConfig { schemas: string[]; grants: boolean; ignore_body_whitespace: boolean; + /** Object types to extract into individual files (excluded from schema.sql) */ + routine_types: string[]; api_dir: string; internal_dir: string; group_segment: number; skip_prefixes: string[]; - group_order: "type_first" | "group_first"; + /** Directory nesting order. Available: "type", "schema", "name", "kind" */ + group_order: GroupDimension[]; } export interface FormatConfig { @@ -89,11 +94,12 @@ const defaults: PgdevConfig = { schemas: [], grants: false, ignore_body_whitespace: false, + routine_types: ["FUNCTION", "PROCEDURE"], api_dir: "", internal_dir: "", group_segment: 0, skip_prefixes: [], - group_order: "type_first", + group_order: [], }, format: { lowercase: true, @@ -415,7 +421,8 @@ const EXPECTED_KEYS: { section: string; key: string; raw: string }[] = [ { section: "project", key: "internal_dir", raw: "# Subdirectory within routines_dir for internal (non-API) routines\ninternal_dir = \"\"" }, { section: "project", key: "group_segment", raw: "# Group routines into subdirs by name segment (0 = disabled, 1 = first segment)\ngroup_segment = 0" }, { section: "project", key: "skip_prefixes", raw: "# Prefixes to skip when grouping by name segment (empty = use built-in defaults)\n# skip_prefixes = [\"get\", \"set\", \"delete\", \"insert\", \"update\", \"create\", \"remove\", \"find\", \"list\", \"is\", \"has\", \"check\", \"count\", \"compute\", \"run\", \"do\", \"send\"]\nskip_prefixes = []" }, - { section: "project", key: "group_order", raw: "# Directory nesting order when both api/internal and group dirs are used\n# \"type_first\" = api/auth/, \"group_first\" = auth/api/\ngroup_order = \"type_first\"" }, + { section: "project", key: "routine_types", raw: "# Object types to extract into individual files (excluded from schema.sql)\nroutine_types = [\"FUNCTION\", \"PROCEDURE\"]" }, + { section: "project", key: "group_order", raw: "# Directory nesting order. Each element adds a subdirectory level.\n# Available: \"type\" (api/internal), \"schema\", \"name\" (name segment), \"kind\" (function/procedure)\n# Example: [\"type\", \"schema\", \"name\"] → api/myschema/auth/get_auth_login.sql\ngroup_order = []" }, // [format] { section: "format", key: "lowercase", raw: "# Lowercase SQL keywords in formatted output\nlowercase = true" }, { section: "format", key: "param_style", raw: '# Parameter layout: "inline" or "multiline"\nparam_style = "multiline"' }, @@ -571,9 +578,12 @@ group_segment = 0 # Prefixes to skip when grouping by name segment (empty = use built-in defaults) # skip_prefixes = ["get", "set", "delete", "insert", "update", "create", "remove", "find", "list", "is", "has", "check", "count", "compute", "run", "do", "send"] skip_prefixes = [] -# Directory nesting order when both api/internal and group dirs are used -# "type_first" = api/auth/, "group_first" = auth/api/ -group_order = "type_first" +# Object types to extract into individual files (excluded from schema.sql) +routine_types = ["FUNCTION", "PROCEDURE"] +# Directory nesting order. Each element adds a subdirectory level. +# Available: "type" (api/internal), "schema", "name" (name segment), "kind" (function/procedure) +# Example: ["type", "schema", "name"] → api/myschema/auth/get_auth_login.sql +group_order = [] # SQL formatter options for routine files generated by sync [format] diff --git a/src/parser/formatter.ts b/src/parser/formatter.ts index b419962..d8d8780 100644 --- a/src/parser/formatter.ts +++ b/src/parser/formatter.ts @@ -1,4 +1,5 @@ import type { ParsedRoutine } from "./routine.ts"; +import { quoteIdent } from "./routine.ts"; import type { FormatConfig } from "../config.ts"; export interface FormatOptions { @@ -72,6 +73,16 @@ function kw(word: string, lowercase: boolean): string { return lowercase ? word.toLowerCase() : word.toUpperCase(); } +/** Build schema-qualified name, quoting identifiers that were quoted in the source. */ +function qualifiedName(r: ParsedRoutine): string { + const name = quoteIdent(r.name, r.nameQuoted ?? false); + if (r.schema) { + const schema = quoteIdent(r.schema, r.schemaQuoted ?? false); + return `${schema}.${name}`; + } + return name; +} + /** Format the CREATE FUNCTION/PROCEDURE header with parameters. */ function formatHeader(r: ParsedRoutine, opts: FormatOptions): string { const orReplace = opts.createOrReplace ? ` ${kw("OR REPLACE", opts.lowercase)}` : ""; @@ -79,7 +90,7 @@ function formatHeader(r: ParsedRoutine, opts: FormatOptions): string { ? `${kw("CREATE", opts.lowercase)}${orReplace} ${kw("FUNCTION", opts.lowercase)}` : `${kw("CREATE", opts.lowercase)}${orReplace} ${kw("PROCEDURE", opts.lowercase)}`; - const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + const qualName = qualifiedName(r); // Format parameters const params = r.parameters.map((p) => { @@ -173,7 +184,7 @@ function formatComment(r: ParsedRoutine, opts: FormatOptions): string | null { const typeKw = r.type === "function" ? kw("FUNCTION", opts.lowercase) : kw("PROCEDURE", opts.lowercase); - const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + const qualName = qualifiedName(r); let sig: string; if (opts.commentSignatureStyle === "types_only") { @@ -206,7 +217,7 @@ function formatGrants(r: ParsedRoutine, opts: FormatOptions): string[] { const typeKw = r.type === "function" ? kw("FUNCTION", opts.lowercase) : kw("PROCEDURE", opts.lowercase); - const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + const qualName = qualifiedName(r); const sig = r.parameters .map((p) => opts.lowercase ? p.type.toLowerCase() : p.type) .join(", "); @@ -232,7 +243,7 @@ export function formatRoutine(r: ParsedRoutine, options?: Partial const typeKw = r.type === "function" ? kw("FUNCTION", opts.lowercase) : kw("PROCEDURE", opts.lowercase); - const qualName = r.schema ? `${r.schema}.${r.name}` : r.name; + const qualName = qualifiedName(r); const sig = r.parameters .map((p) => opts.lowercase ? p.type.toLowerCase() : p.type.toUpperCase()) .join(", "); diff --git a/src/parser/parser-tests/formatter.test.ts b/src/parser/parser-tests/formatter.test.ts index c3caf10..6646745 100644 --- a/src/parser/parser-tests/formatter.test.ts +++ b/src/parser/parser-tests/formatter.test.ts @@ -418,4 +418,54 @@ GRANT EXECUTE ON FUNCTION mathmodule.myfn(int) TO web_user; expect(result).toContain("revoke all on function mathmodule.myfn(int) from PUBLIC;"); expect(result).toContain("grant execute on function mathmodule.myfn(int) to web_user;"); }); + + test("formats quoted identifier names correctly", () => { + const sql = `CREATE FUNCTION _."exists"(text) RETURNS boolean + LANGUAGE sql + AS $$ SELECT true; $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + + expect(result).toContain('drop function if exists _."exists"(text);'); + expect(result).toContain('create function _."exists"('); + }); + + test("formats quoted schema and name", () => { + const sql = `CREATE FUNCTION "My Schema"."My Func"() RETURNS void + LANGUAGE sql AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + + expect(result).toContain('drop function if exists "My Schema"."My Func"();'); + expect(result).toContain('create function "My Schema"."My Func"()'); + }); + + test("formats COMMENT ON with quoted identifier", () => { + const sql = `CREATE FUNCTION _."exists"(text) RETURNS boolean + LANGUAGE sql AS $$ SELECT true; $$; +COMMENT ON FUNCTION _."exists"(text) IS 'Check existence';`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + + expect(result).toContain('comment on function _."exists"(text) is \'Check existence\';'); + }); + + test("formats GRANT/REVOKE with quoted identifier", () => { + const sql = `CREATE FUNCTION _."exists"(_a text) RETURNS void LANGUAGE sql AS $$ $$; +GRANT EXECUTE ON FUNCTION _."exists"(text) TO web_user;`; + const [parsed] = parseRoutines(sql, { grants: true }); + const result = formatRoutine(parsed); + + expect(result).toContain('grant execute on function _."exists"(text) to web_user;'); + }); + + test("does not quote unquoted identifiers", () => { + const sql = `CREATE FUNCTION _.normal_func(text) RETURNS boolean + LANGUAGE sql AS $$ SELECT true; $$;`; + const [parsed] = parseRoutines(sql); + const result = formatRoutine(parsed); + + expect(result).toContain("drop function if exists _.normal_func(text);"); + expect(result).toContain("create function _.normal_func("); + }); }); diff --git a/src/parser/parser-tests/routine-name.test.ts b/src/parser/parser-tests/routine-name.test.ts index f0bc078..49d7c99 100644 --- a/src/parser/parser-tests/routine-name.test.ts +++ b/src/parser/parser-tests/routine-name.test.ts @@ -194,4 +194,84 @@ CREATE FUNCTION catalog.func() RETURNS void LANGUAGE sql AS $$ SELECT 1; $$;`; expect(result.length).toBe(1); expect(result[0].name).toBe("func"); }); + + test("parses double-quoted function name", () => { + const sql = `CREATE FUNCTION _."exists"(text) RETURNS boolean + LANGUAGE sql AS $$ SELECT true; $$;`; + const result = parseRoutines(sql); + expect(result.length).toBe(1); + expect(result[0].name).toBe("exists"); + expect(result[0].nameQuoted).toBe(true); + expect(result[0].schema).toBe("_"); + expect(result[0].schemaQuoted).toBeUndefined(); + }); + + test("parses double-quoted schema and name", () => { + const sql = `CREATE FUNCTION "my schema"."My Func"() RETURNS void + LANGUAGE sql AS $$ SELECT 1; $$;`; + const result = parseRoutines(sql); + expect(result.length).toBe(1); + expect(result[0].schema).toBe("my schema"); + expect(result[0].schemaQuoted).toBe(true); + expect(result[0].name).toBe("My Func"); + expect(result[0].nameQuoted).toBe(true); + }); + + test("parses quoted name with escaped double quotes", () => { + const sql = `CREATE FUNCTION s."say""hello"() RETURNS void + LANGUAGE sql AS $$ SELECT 1; $$;`; + const result = parseRoutines(sql); + expect(result.length).toBe(1); + expect(result[0].name).toBe('say"hello'); + expect(result[0].nameQuoted).toBe(true); + }); + + test("unquoted names have nameQuoted undefined", () => { + const sql = `CREATE FUNCTION s.normal_name() RETURNS void + LANGUAGE sql AS $$ SELECT 1; $$;`; + const result = parseRoutines(sql); + expect(result.length).toBe(1); + expect(result[0].name).toBe("normal_name"); + expect(result[0].nameQuoted).toBeUndefined(); + }); + + test("parses real pg_dump output with quoted identifier (exists)", () => { + const sql = `-- +-- PostgreSQL database dump +-- + +-- Dumped from database version 18.2 +-- Dumped by pg_dump version 18.1 + +-- +-- Name: exists(text); Type: FUNCTION; Schema: _; Owner: postgres +-- + +CREATE FUNCTION _."exists"(text) RETURNS boolean + LANGUAGE sql + SET search_path TO 'public', 'pg_catalog' + AS \$_\$select _.is_table($1) or _.is_schema($1) or _.is_function($1) or _.is_role($1) or _.is_type($1);\$_\$; + + +-- +-- PostgreSQL database dump complete +-- +`; + const result = parseRoutines(sql); + expect(result.length).toBe(1); + expect(result[0].name).toBe("exists"); + expect(result[0].nameQuoted).toBe(true); + expect(result[0].schema).toBe("_"); + expect(result[0].type).toBe("function"); + }); + + test("matches COMMENT ON with quoted identifiers", () => { + const sql = `CREATE FUNCTION _."exists"(text) RETURNS boolean + LANGUAGE sql AS $$ SELECT true; $$; + +COMMENT ON FUNCTION _."exists"(text) IS 'Check if something exists';`; + const result = parseRoutines(sql); + expect(result.length).toBe(1); + expect(result[0].comment).toBe("Check if something exists"); + }); }); diff --git a/src/parser/routine.ts b/src/parser/routine.ts index 32f7409..12f318b 100644 --- a/src/parser/routine.ts +++ b/src/parser/routine.ts @@ -34,6 +34,30 @@ export interface ParsedRoutine { body: string | null; comment: string | null; grants: RoutineGrant[]; + /** True if the name was double-quoted in the source SQL. */ + nameQuoted?: boolean; + /** True if the schema was double-quoted in the source SQL. */ + schemaQuoted?: boolean; +} + +/** + * Strip double quotes from a SQL identifier, unescaping "" → ". + * Returns the bare identifier and whether it was quoted. + */ +export function unquoteIdent(ident: string): { bare: string; quoted: boolean } { + if (ident.startsWith('"') && ident.endsWith('"')) { + return { bare: ident.slice(1, -1).replace(/""/g, '"'), quoted: true }; + } + return { bare: ident, quoted: false }; +} + +/** + * Quote a SQL identifier if needed (was originally quoted). + * Escapes internal double quotes as "". + */ +export function quoteIdent(name: string, needsQuoting: boolean): string { + if (!needsQuoting) return name; + return `"${name.replace(/"/g, '""')}"`; } /** @@ -369,15 +393,23 @@ function extractAttributes(cleaned: string, closeParen: number): string[] { return attrs; } -const CREATE_ROUTINE_RE = - /\bCREATE\s+(?:OR\s+REPLACE\s+)?(FUNCTION|PROCEDURE)\s+(?:([a-zA-Z_]\w*)\.)?([a-zA-Z_]\w*)\s*\(/gi; +/** Pattern for a SQL identifier: unquoted or double-quoted. */ +const IDENT = `(?:"(?:[^"]|"")*"|[a-zA-Z_]\\w*)`; + +const CREATE_ROUTINE_RE = new RegExp( + `\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(FUNCTION|PROCEDURE)\\s+(?:(${IDENT})\\.)?(${IDENT})\\s*\\(`, + "gi", +); /** * Match COMMENT ON FUNCTION/PROCEDURE [schema.]name(...) IS 'text'; * Captures: type, schema (optional), name, param signature, comment string. */ -const COMMENT_ON_RE = - /\bCOMMENT\s+ON\s+(FUNCTION|PROCEDURE)\s+(?:([a-zA-Z_]\w*)\.)?([a-zA-Z_]\w*)\s*\(([^)]*)\)\s+IS\s+'((?:[^']|'')*)'\s*;/gi; +const COMMENT_ON_RE = new RegExp( + `\\bCOMMENT\\s+ON\\s+(FUNCTION|PROCEDURE)\\s+(?:(${IDENT})\\.)?` + + `(${IDENT})\\s*\\(([^)]*)\\)\\s+IS\\s+'((?:[^']|'')*)'\\s*;`, + "gi", +); /** * Extract COMMENT ON statements and build a lookup map. @@ -389,8 +421,8 @@ function parseComments(commentStripped: string): Map { const re = new RegExp(COMMENT_ON_RE.source, COMMENT_ON_RE.flags); while ((m = re.exec(commentStripped)) !== null) { const type = m[1].toLowerCase(); - const schema = m[2] ?? ""; - const name = m[3]; + const schema = m[2] ? unquoteIdent(m[2]).bare : ""; + const name = unquoteIdent(m[3]).bare; // COMMENT ON signatures may include param names (pg_dump style: "_id integer") // or just types ("integer"). Use parseOneParam to extract just the type. const params = m[4] @@ -411,8 +443,12 @@ function parseComments(commentStripped: string): Map { * GRANT EXECUTE ON FUNCTION [schema.]name(params) TO role; * REVOKE ALL ON FUNCTION [schema.]name(params) FROM role; */ -const GRANT_REVOKE_RE = - /\b(GRANT|REVOKE)\s+(EXECUTE|ALL(?:\s+PRIVILEGES)?)\s+ON\s+(FUNCTION|PROCEDURE)\s+(?:([a-zA-Z_]\w*)\.)?([a-zA-Z_]\w*)\s*\(([^)]*)\)\s+(?:TO|FROM)\s+([^;]+?)\s*;/gi; +const GRANT_REVOKE_RE = new RegExp( + `\\b(GRANT|REVOKE)\\s+(EXECUTE|ALL(?:\\s+PRIVILEGES)?)\\s+ON\\s+(FUNCTION|PROCEDURE)\\s+` + + `(?:(${IDENT})\\.)?` + + `(${IDENT})\\s*\\(([^)]*)\\)\\s+(?:TO|FROM)\\s+([^;]+?)\\s*;`, + "gi", +); function parseGrants(commentStripped: string): Map { const map = new Map(); @@ -422,8 +458,8 @@ function parseGrants(commentStripped: string): Map { const isGrant = m[1].toUpperCase() === "GRANT"; const privilege = m[2].toUpperCase().startsWith("ALL") ? "ALL" : "EXECUTE"; const type = m[3].toLowerCase(); - const schema = m[4] ?? ""; - const name = m[5]; + const schema = m[4] ? unquoteIdent(m[4]).bare : ""; + const name = unquoteIdent(m[5]).bare; const params = m[6] .split(",") .map((p) => p.trim()) @@ -469,16 +505,21 @@ export function parseRoutines(content: string, options?: { grants?: boolean }): // Extract body from comment-stripped (not dollar-stripped) text const body = extractBody(commentStripped, match.index); + const schemaIdent = match[2] ? unquoteIdent(match[2]) : null; + const nameIdent = unquoteIdent(match[3]); + const routine: ParsedRoutine = { type: match[1].toLowerCase() as "function" | "procedure", - schema: match[2] ?? null, - name: match[3], + schema: schemaIdent?.bare ?? null, + name: nameIdent.bare, parameters: parseParameters(paramStr), returns, attributes, body, comment: null, grants: [], + nameQuoted: nameIdent.quoted || undefined, + schemaQuoted: schemaIdent?.quoted || undefined, }; const key = commentKey(routine); From da4d7818c457b79e408df4a3d55f1f38476c5ba6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 14 Mar 2026 12:38:07 +0100 Subject: [PATCH 4/9] Fix SET attribute parsing, PG array parsing, and diff display consistency - Fix SET attribute regex to capture comma-separated values (e.g. SET search_path TO 'public', 'pg_catalog' was truncated) - Fix parsePgArray to handle quoted elements containing commas (proconfig values like "search_path=public, pg_catalog" were split) - Fix compare.ts to strip quotes from individual SET values - Fix diff display keys to use types-only for consistent output Co-Authored-By: Claude Opus 4.6 (1M context) --- src/commands/diff.ts | 4 +-- src/parser/catalog.ts | 31 +++++++++++++++++-- src/parser/compare.ts | 4 ++- .../parser-tests/normalize-type.test.ts | 28 +++++++++++++++++ src/parser/parser-tests/routine-attrs.test.ts | 16 ++++++++++ src/parser/routine.ts | 4 +-- 6 files changed, 80 insertions(+), 7 deletions(-) diff --git a/src/commands/diff.ts b/src/commands/diff.ts index 23b97f5..34a0d0a 100644 --- a/src/commands/diff.ts +++ b/src/commands/diff.ts @@ -26,12 +26,12 @@ function catalogGroupKey(r: CatalogRoutine): string { function parsedDisplayKey(r: ParsedRoutine, defaultSchema: string): string { const schema = r.schema ?? defaultSchema; - const params = r.parameters.map((p) => p.name ? `${p.name} ${p.type.toLowerCase()}` : p.type.toLowerCase()); + const params = r.parameters.map((p) => p.type.toLowerCase()); return `${schema}.${r.name}(${params.join(", ")})`; } function catalogDisplayKey(r: CatalogRoutine): string { - const params = r.parameters.map((p) => p.name ? `${p.name} ${p.type}` : p.type); + const params = r.parameters.map((p) => p.type); return `${r.schema}.${r.name}(${params.join(", ")})`; } diff --git a/src/parser/catalog.ts b/src/parser/catalog.ts index 16262b3..960d50c 100644 --- a/src/parser/catalog.ts +++ b/src/parser/catalog.ts @@ -130,10 +130,37 @@ export function parseCatalogRows(rows: CatalogRow[]): CatalogRoutine[] { return [...map.values()]; } -/** Parse psql {key=val,...} array format to string[]. */ +/** Parse psql {key=val,...} array format to string[]. Handles quoted elements containing commas. */ function parsePgArray(raw: string): string[] { if (!raw || raw === "{}") return []; - return raw.replace(/^\{/, "").replace(/\}$/, "").split(","); + const inner = raw.replace(/^\{/, "").replace(/\}$/, ""); + const result: string[] = []; + let i = 0; + while (i < inner.length) { + if (inner[i] === '"') { + // Quoted element — find closing quote (escaped "" → ") + let end = i + 1; + while (end < inner.length) { + if (inner[end] === '"' && inner[end + 1] === '"') { end += 2; continue; } + if (inner[end] === '"') break; + end++; + } + result.push(inner.substring(i + 1, end).replace(/""/g, '"')); + i = end + 1; + // Skip comma separator + if (inner[i] === ',') i++; + } else { + // Unquoted element — find next comma + const comma = inner.indexOf(',', i); + if (comma === -1) { + result.push(inner.substring(i)); + break; + } + result.push(inner.substring(i, comma)); + i = comma + 1; + } + } + return result; } /** Normalize body for comparison: lowercase, normalize line endings, trim trailing whitespace per line. */ diff --git a/src/parser/compare.ts b/src/parser/compare.ts index 574e79f..b361ce2 100644 --- a/src/parser/compare.ts +++ b/src/parser/compare.ts @@ -120,7 +120,9 @@ export function attributesToCatalog(parsed: ParsedRoutine): ExpectedAttributes { // PG also strips surrounding single quotes from values const m = a.match(/^SET\s+(\S+)\s*(?:=|TO)\s*(.+)$/i); if (!m) return a; - const val = m[2].replace(/^'(.*)'$/, "$1"); + // Strip surrounding single quotes from each comma-separated value + // PG stores proconfig as "var=val1, val2" without quotes + const val = m[2].replace(/'([^']*)'/g, "$1"); return `${m[1]}=${val}`; }); diff --git a/src/parser/parser-tests/normalize-type.test.ts b/src/parser/parser-tests/normalize-type.test.ts index 73e3ea3..c33706b 100644 --- a/src/parser/parser-tests/normalize-type.test.ts +++ b/src/parser/parser-tests/normalize-type.test.ts @@ -213,4 +213,32 @@ describe("routinesDiffer — type alias normalization", () => { const catalog = makeCatalog([{ name: "_a", type: "integer" }], "integer", " SELECT _a + 2; "); expect(routinesDiffer(parsed, catalog, { ignoreBodyWhitespace: true })).toBe(true); }); + + test("SET config with comma-separated quoted values matches catalog", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS void + LANGUAGE sql SET search_path TO 'public', 'pg_catalog' + AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const expected = attributesToCatalog(parsed); + expect(expected.config).toEqual(["search_path=public, pg_catalog"]); + }); + + test("SET config with single quoted value matches catalog", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS void + LANGUAGE sql SET work_mem TO '64MB' + AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const expected = attributesToCatalog(parsed); + expect(expected.config).toEqual(["work_mem=64MB"]); + }); + + test("SET config matches catalog for routinesDiffer", () => { + const sql = `CREATE FUNCTION public.test_fn() RETURNS void + LANGUAGE sql SET search_path TO 'public', 'pg_catalog' + AS $$ SELECT 1; $$;`; + const [parsed] = parseRoutines(sql); + const catalog = makeCatalog([], "void"); + catalog.config = ["search_path=public, pg_catalog"]; + expect(routinesDiffer(parsed, catalog)).toBe(false); + }); }); diff --git a/src/parser/parser-tests/routine-attrs.test.ts b/src/parser/parser-tests/routine-attrs.test.ts index 7ec23bd..1dd8ed3 100644 --- a/src/parser/parser-tests/routine-attrs.test.ts +++ b/src/parser/parser-tests/routine-attrs.test.ts @@ -155,6 +155,22 @@ describe("parseRoutines — attributes", () => { expect(r.attributes).toContain("SET work_mem TO '64MB'"); }); + test("extracts SET with comma-separated quoted values", () => { + const sql = `CREATE FUNCTION app.my_fn() RETURNS void + LANGUAGE sql SET search_path TO 'public', 'pg_catalog' + AS $$ SELECT 1; $$;`; + const [r] = parseRoutines(sql); + expect(r.attributes).toContain("SET search_path TO 'public', 'pg_catalog'"); + }); + + test("extracts SET with comma-separated unquoted values", () => { + const sql = `CREATE FUNCTION app.my_fn() RETURNS void + LANGUAGE sql SET search_path = public, pg_catalog + AS $$ SELECT 1; $$;`; + const [r] = parseRoutines(sql); + expect(r.attributes).toContain("SET search_path = public, pg_catalog"); + }); + test("extracts SET parameter FROM CURRENT", () => { const sql = `CREATE FUNCTION app.inherit() RETURNS void LANGUAGE plpgsql SET search_path FROM CURRENT diff --git a/src/parser/routine.ts b/src/parser/routine.ts index 12f318b..24e2fe2 100644 --- a/src/parser/routine.ts +++ b/src/parser/routine.ts @@ -307,8 +307,8 @@ const ATTR_PATTERNS: RegExp[] = [ /^NOT\s+LEAKPROOF/i, /^PARALLEL\s+(?:UNSAFE|RESTRICTED|SAFE)/i, /^SET\s+\S+\s+FROM\s+CURRENT/i, - /^SET\s+\S+\s*(?:=|TO)\s*'[^']*'/i, - /^SET\s+\S+\s*(?:=|TO)\s*\S+/i, + /^SET\s+\S+\s*(?:=|TO)\s*'[^']*'(?:\s*,\s*'[^']*')*/i, + /^SET\s+\S+\s*(?:=|TO)\s*[^\s,]+(?:\s*,\s*[^\s,]+)*/i, /^LANGUAGE\s+\S+/i, /^SUPPORT\s+\S+/i, /^COST\s+\S+/i, From fe66ade3c49c022b57783e0ebab801b12049aee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 14 Mar 2026 13:38:23 +0100 Subject: [PATCH 5/9] Add diff --fix-comments, fix parser for DO blocks and multi-value types - Add --fix-comments/--fix-grants/--fix-definitions/--fix-all flags to diff command. --fix-comments inserts or replaces COMMENT ON statements in source files using comments from the database catalog. - Fix stripDollarBodies to preserve DO block content (only strip AS bodies) - Fix extractBody to pick nearest body marker (dollar vs single-quoted) - Fix extractReturns to bound search within the attribute zone - Add timestamp/time type aliases, handle array suffixes and char(1) normalization in type comparison - Fix COMMENT_ON_RE and GRANT_REVOKE_RE to handle nested parens in type modifiers like char(1), numeric(10,2) - Update README with diff fix switches and new features Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 101 ++++++++++++++++++++++--- src/cli.ts | 14 +++- src/commands/diff.ts | 160 +++++++++++++++++++++++++++++++++++++++- src/parser/compare.ts | 24 ++++++ src/parser/formatter.ts | 2 +- src/parser/routine.ts | 39 +++++++--- 6 files changed, 313 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 436cc2a..af42242 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,36 @@ Sections: - **NpgsqlRest Config Files** — create and manage NpgsqlRest JSON config files (production, development, local) with a TUI editor for connection strings, config settings, and more - **pgdev Environment** — configure env file, database connection, and project directories (migrations, routines, tests, schemas) +### `pgdev sync` + +Extract database schema and routines into project files: + +- Dumps the full schema to `migrations_dir/schema.sql` (DDL for tables, types, etc.) +- Extracts each routine (function, procedure, or other configured types) into individual `.sql` files in `routines_dir` +- Applies configurable formatting (see `[format]` options) +- Organizes files into subdirectories based on `group_order` (by API type, schema, name segment, or object kind) +- Supports `VIEW` extraction when added to `routine_types` +- On re-sync, updates existing files in place and reports created/updated/unchanged counts + +### `pgdev diff` + +Compare project SQL files against the live database: + +- Parses all `.sql` files in `routines_dir` and fetches routine metadata from `pg_catalog` +- Reports routines that need creating, updating, or dropping +- Compares definition (parameters, return type, body, attributes), comments, and optionally grants +- Supports `ignore_body_whitespace` for whitespace-insensitive body comparison +- Supports routines inside `DO $$ ... $$` blocks and files with multiple routines + +Fix switches pull data from the database into your source files: + +| Flag | Description | +|------|-------------| +| `--fix-comments` | Update source files with `COMMENT ON` statements from the database | +| `--fix-grants` | Update source files with `GRANT`/`REVOKE` statements from the database | +| `--fix-definitions` | Update source files with routine definitions from the database | +| `--fix-all` | Apply all fixes above | + ### `pgdev exec ` Execute a SQL command via psql using the configured connection. @@ -53,10 +83,6 @@ pgdev exec "SELECT version()" Open an interactive psql session using the configured connection. -### `pgdev sync` - -Dump database schema to the configured migrations directory. - ### `pgdev update` Update pgdev to the latest published version. @@ -77,6 +103,7 @@ Then `pgdev dev` will launch NpgsqlRest with those arguments. | Option | Description | |--------|-------------| | `--version`, `-v` | Show versions of pgdev, NpgsqlRest, PostgreSQL tools, and connected server | +| `--status`, `-s` | Show tools status | | `--help`, `-h` | Show help message | ## Configuration @@ -130,13 +157,33 @@ password = "{PGPASSWORD}" # config_file = "./config/production.json" # connection_name = "Default" -# Project directories for SQL source files -# Leave empty to skip; directories are created when first needed +# Project directories and settings [project] routines_dir = "" migrations_dir = "" tests_dir = "" schemas = [] +grants = false +ignore_body_whitespace = false +routine_types = ["FUNCTION", "PROCEDURE"] +api_dir = "" +internal_dir = "" +group_segment = 0 +skip_prefixes = [] +group_order = [] + +# SQL formatting options (applied during sync) +[format] +lowercase = true +param_style = "multiline" +indent = " " +simplify_defaults = true +omit_default_direction = true +attribute_style = "multiline" +strip_dump_comments = true +comment_signature_style = "types_only" +drop_before_create = true +create_or_replace = false ``` ### Top-level options @@ -199,14 +246,48 @@ Database connection for pgdev tools. Two modes: ### `[project]` -Project directory paths for SQL source files. +Project directories and sync/diff settings. | Key | Default | Description | |-----|---------|-------------| -| `routines_dir` | `""` | Directory for SQL routines (functions/procedures) | -| `migrations_dir` | `""` | Directory for migration scripts | +| `routines_dir` | `""` | Directory for extracted SQL routines | +| `migrations_dir` | `""` | Directory for migration scripts (schema.sql is written here) | | `tests_dir` | `""` | Directory for SQL test files | -| `schemas` | `[]` | Schemas used by this project (empty = all non-system schemas) | +| `schemas` | `[]` | Schemas to include (empty = all non-system schemas) | +| `grants` | `false` | Include GRANT/REVOKE statements in sync and diff | +| `ignore_body_whitespace` | `false` | Ignore whitespace differences in routine bodies during diff | +| `routine_types` | `["FUNCTION", "PROCEDURE"]` | Object types to extract into individual files. Supported: `FUNCTION`, `PROCEDURE`, `VIEW` | +| `api_dir` | `""` | Subdirectory for API routines (those with HTTP comments) within the "type" grouping dimension | +| `internal_dir` | `""` | Subdirectory for non-API routines within the "type" grouping dimension | +| `group_segment` | `0` | Name segment index for the "name" grouping dimension (0 = disabled). Splits on `_` after skipping common prefixes | +| `skip_prefixes` | `[]` | Prefixes to skip when extracting group segment (e.g. `["get", "set", "delete"]`). Uses built-in defaults when empty | +| `group_order` | `[]` | Directory nesting order. Available dimensions: `"type"`, `"schema"`, `"name"`, `"kind"`. Empty = flat directory | + +**Directory grouping dimensions:** + +- **`type`** — Split by API vs internal (uses `api_dir`/`internal_dir` names). Routines with HTTP comments go to `api_dir`, others to `internal_dir`. +- **`schema`** — Split by PostgreSQL schema name (uses the schema name as directory). +- **`name`** — Split by name segment extracted from the routine's snake_case name (e.g. `get_user_data` with `group_segment=1` → `user/`). +- **`kind`** — Split by object type (uses lowercase type name: `function/`, `procedure/`, `view/`). + +Example: `group_order = ["type", "schema", "kind"]` produces paths like `api/myschema/function/my_func.sql`. + +### `[format]` + +SQL formatting options applied when extracting routines during sync. + +| Key | Default | Description | +|-----|---------|-------------| +| `lowercase` | `true` | Lowercase SQL keywords | +| `param_style` | `"multiline"` | Parameter layout: `"inline"` or `"multiline"` | +| `indent` | `" "` | Indentation string for multiline formatting | +| `simplify_defaults` | `true` | Simplify default expressions (e.g. `NULL::text` → `null`) | +| `omit_default_direction` | `true` | Omit `IN` direction since it's the default | +| `attribute_style` | `"multiline"` | Attribute placement: `"inline"` or `"multiline"` | +| `strip_dump_comments` | `true` | Remove pg_dump header/footer comments | +| `comment_signature_style` | `"types_only"` | COMMENT ON signature: `"types_only"` or `"full"` (includes param names) | +| `drop_before_create` | `true` | Add `DROP FUNCTION/PROCEDURE IF EXISTS` before `CREATE` | +| `create_or_replace` | `false` | Use `CREATE OR REPLACE` instead of `CREATE` | ## License diff --git a/src/cli.ts b/src/cli.ts index 0917c27..dc6f528 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -431,6 +431,10 @@ ${pc.bold("Commands:")} config Configure tools, NpgsqlRest, environment, and project init, setup Alias for config diff Compare project routines with database + --fix-comments Update source files with comments from database + --fix-grants Update source files with grants from database + --fix-definitions Update source files with definitions from database + --fix-all Apply all fixes above exec Execute SQL command via psql psql Open interactive psql session sync Sync database routines and schema to project files @@ -500,9 +504,15 @@ export async function run(): Promise { case "psql": await psqlCommand(config); break; - case "diff": - await diffCommand(config); + case "diff": { + const fixFlags = { + comments: args.includes("--fix-comments") || args.includes("--fix-all"), + grants: args.includes("--fix-grants") || args.includes("--fix-all"), + definitions: args.includes("--fix-definitions") || args.includes("--fix-all"), + }; + await diffCommand(config, fixFlags); break; + } case "sync": await syncCommand(config); break; diff --git a/src/commands/diff.ts b/src/commands/diff.ts index 34a0d0a..9a335da 100644 --- a/src/commands/diff.ts +++ b/src/commands/diff.ts @@ -3,9 +3,16 @@ import { statSync } from "node:fs"; import type { PgdevConfig } from "../config.ts"; import { pc, spinner } from "../utils/terminal.ts"; import { findSqlFiles } from "../utils/files.ts"; -import { parseRoutines, type ParsedRoutine } from "../parser/routine.ts"; +import { parseRoutines, type ParsedRoutine, quoteIdent } from "../parser/routine.ts"; import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; import { routinesDiffer, commentsDiffer, grantsDiffer, type DiffOptions } from "../parser/compare.ts"; +import { formatComment, configToFormatOptions, type FormatOptions } from "../parser/formatter.ts"; + +export interface FixFlags { + comments: boolean; + grants: boolean; + definitions: boolean; +} /** * Match key uses schema.name only. Overloaded functions (same name, different @@ -35,7 +42,112 @@ function catalogDisplayKey(r: CatalogRoutine): string { return `${r.schema}.${r.name}(${params.join(", ")})`; } -export async function diffCommand(config: PgdevConfig): Promise { +/** Build a regex that matches an existing COMMENT ON for a routine. */ +function buildCommentOnRegex(r: ParsedRoutine): RegExp { + const typeKw = `(?:FUNCTION|PROCEDURE)`; + const schema = r.schema ? `(?:${escapeRegex(quoteIdent(r.schema, r.schemaQuoted ?? false))}|${escapeRegex(r.schema)})\\.` : ""; + const name = `(?:${escapeRegex(quoteIdent(r.name, r.nameQuoted ?? false))}|${escapeRegex(r.name)})`; + return new RegExp( + `\\bCOMMENT\\s+ON\\s+${typeKw}\\s+${schema}${name}\\s*\\([^)]*\\)\\s+IS\\s+'(?:[^']|'')*'\\s*;`, + "gi", + ); +} + +function escapeRegex(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** + * Find the end position of a routine body in the source text. + * Searches forward from the CREATE position for the body end ($$; or ';). + */ +function findRoutineBodyEnd(content: string, routine: ParsedRoutine): number { + // Find the CREATE statement for this routine + const schema = routine.schema + ? `(?:${escapeRegex(quoteIdent(routine.schema, routine.schemaQuoted ?? false))}|${escapeRegex(routine.schema)})\\.` + : ""; + const name = `(?:${escapeRegex(quoteIdent(routine.name, routine.nameQuoted ?? false))}|${escapeRegex(routine.name)})`; + const createRe = new RegExp( + `\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\s+${schema}${name}\\s*\\(`, + "gi", + ); + const createMatch = createRe.exec(content); + if (!createMatch) return -1; + + // From the CREATE position, find the body end + const rest = content.substring(createMatch.index); + + // Try dollar-quoted body: find AS $tag$...$tag$; + const dollarRe = /\bAS\s+(\$[a-zA-Z_0-9]*\$)[\s\S]*?\1\s*;/i; + const dollarMatch = rest.match(dollarRe); + + // Try single-quoted body: find AS [E]'...'; + const sqRe = /\bAS\s+(?:E)?'/i; + const sqMatch = rest.match(sqRe); + + const dollarPos = dollarMatch?.index ?? Infinity; + const sqPos = sqMatch?.index ?? Infinity; + + if (dollarMatch && dollarPos <= sqPos) { + return createMatch.index + dollarMatch.index! + dollarMatch[0].length; + } + + if (sqMatch && sqPos < dollarPos) { + // Find end of single-quoted string + let i = sqMatch.index! + sqMatch[0].length; + while (i < rest.length) { + if (rest[i] === "'" && rest[i + 1] === "'") { i += 2; continue; } + if (rest[i] === "'") { + // Find the semicolon after the closing quote + const afterQuote = rest.substring(i + 1); + const semi = afterQuote.match(/^\s*;/); + return createMatch.index + i + 1 + (semi ? semi[0].length : 0); + } + i++; + } + } + + return -1; +} + +/** + * Apply comment fixes to a file. Returns the number of routines fixed. + */ +function applyCommentFixes( + content: string, + fixes: { routine: ParsedRoutine; catalogComment: string }[], + formatOpts: FormatOptions, +): { content: string; count: number } { + let result = content; + let count = 0; + + for (const { routine, catalogComment } of fixes) { + // Create a routine copy with the catalog comment for formatting + const withComment: ParsedRoutine = { ...routine, comment: catalogComment }; + const commentSql = formatComment(withComment, formatOpts); + if (!commentSql) continue; + + // Try to replace existing COMMENT ON + const commentRe = buildCommentOnRegex(routine); + if (commentRe.test(result)) { + result = result.replace(commentRe, commentSql); + count++; + continue; + } + + // No existing COMMENT ON — insert after routine body end + const bodyEnd = findRoutineBodyEnd(result, routine); + if (bodyEnd === -1) continue; + + // Insert COMMENT ON after the body end, with a blank line separator + result = result.substring(0, bodyEnd) + "\n\n" + commentSql + result.substring(bodyEnd); + count++; + } + + return { content: result, count }; +} + +export async function diffCommand(config: PgdevConfig, fix?: FixFlags): Promise { const { routines_dir, schemas, grants, ignore_body_whitespace } = config.project; if (!routines_dir) { @@ -113,6 +225,9 @@ export async function diffCommand(config: PgdevConfig): Promise { const needDropping: string[] = []; const matchedCatalogKeys = new Set(); + // Collect fixable comment diffs grouped by absolute file path + const commentFixes = new Map(); + for (const [gk, parsedList] of parsedGroups) { const catList = catalogGroups.get(gk); if (!catList) { @@ -137,12 +252,21 @@ export async function diffCommand(config: PgdevConfig): Promise { const changes: string[] = []; const diffOpts: DiffOptions = { ignoreBodyWhitespace: ignore_body_whitespace }; if (routinesDiffer(p.routine, cat, diffOpts)) changes.push("definition"); - if (commentsDiffer(p.routine, cat)) changes.push("comment"); + const hasCommentDiff = commentsDiffer(p.routine, cat); + if (hasCommentDiff) changes.push("comment"); if (grants && grantsDiffer(p.routine, cat)) changes.push("grants"); if (changes.length > 0) { needUpdating.push({ display: p.display, file: p.file, changes }); } + + // Collect comment fix if needed + if (hasCommentDiff && fix?.comments && cat.comment != null) { + const absFile = resolve(process.cwd(), p.file); + let list = commentFixes.get(absFile); + if (!list) { list = []; commentFixes.set(absFile, list); } + list.push({ routine: p.routine, catalogComment: cat.comment }); + } } // Unmatched catalog routines in this group @@ -163,6 +287,9 @@ export async function diffCommand(config: PgdevConfig): Promise { if (needCreating.length === 0 && needUpdating.length === 0 && needDropping.length === 0) { console.log(pc.green(`All ${totalParsed} routines match the database.`)); + if (fix?.comments) console.log(pc.dim("No comment differences to fix.")); + if (fix?.grants) console.log(pc.dim("No grant differences to fix.")); + if (fix?.definitions) console.log(pc.dim("No definition differences to fix.")); return; } @@ -199,4 +326,31 @@ export async function diffCommand(config: PgdevConfig): Promise { if (needUpdating.length > 0) parts.push(pc.yellow(`${needUpdating.length} to update`)); if (needDropping.length > 0) parts.push(pc.red(`${needDropping.length} to drop`)); console.log(parts.join(", ")); + + // Apply fixes + if (fix?.comments && commentFixes.size > 0) { + console.log(); + const formatOpts = configToFormatOptions(config.format); + let totalFixed = 0; + for (const [absFile, fixes] of commentFixes) { + const content = await Bun.file(absFile).text(); + const { content: updated, count } = applyCommentFixes(content, fixes, formatOpts); + if (count > 0) { + await Bun.write(absFile, updated); + const relPath = absFile.slice(process.cwd().length + 1); + console.log(` ${pc.green("✓")} ${relPath} ${pc.dim(`${count} comment${count > 1 ? "s" : ""}`)}`); + totalFixed += count; + } + } + if (totalFixed > 0) { + console.log(pc.green(`\nFixed ${totalFixed} comment${totalFixed > 1 ? "s" : ""}.`)); + } + } + + if (fix?.definitions) { + console.log(pc.yellow("\n--fix-definitions is not yet implemented.")); + } + if (fix?.grants) { + console.log(pc.yellow("\n--fix-grants is not yet implemented.")); + } } diff --git a/src/parser/compare.ts b/src/parser/compare.ts index b361ce2..0477457 100644 --- a/src/parser/compare.ts +++ b/src/parser/compare.ts @@ -16,7 +16,9 @@ const TYPE_ALIASES: Record = { bool: "boolean", varchar: "character varying", char: "character", + timestamp: "timestamp without time zone", timestamptz: "timestamp with time zone", + time: "time without time zone", timetz: "time with time zone", serial: "integer", serial4: "integer", @@ -29,6 +31,28 @@ const TYPE_ALIASES: Record = { /** Normalize a SQL type to its canonical form (as returned by format_type). */ export function normalizeType(type: string): string { const lower = type.toLowerCase().trim(); + + // Handle array suffix: normalize base type, preserve [] + if (lower.endsWith("[]")) { + const base = lower.slice(0, -2); + return normalizeType(base) + "[]"; + } + + // Handle types with modifiers: char(1), varchar(255), numeric(10,2), etc. + const modMatch = lower.match(/^(\w+)\((.+)\)$/); + if (modMatch) { + const baseName = modMatch[1]; + const modifier = modMatch[2]; + const canonicalBase = TYPE_ALIASES[baseName] ?? baseName; + + // char(1) / character(1) → character (1 is the default length) + if ((canonicalBase === "character") && modifier.trim() === "1") { + return "character"; + } + + return `${canonicalBase}(${modifier})`; + } + return TYPE_ALIASES[lower] ?? lower; } diff --git a/src/parser/formatter.ts b/src/parser/formatter.ts index d8d8780..4c1ae62 100644 --- a/src/parser/formatter.ts +++ b/src/parser/formatter.ts @@ -178,7 +178,7 @@ function formatBody(r: ParsedRoutine, opts: FormatOptions): string | null { } /** Format COMMENT ON statement. */ -function formatComment(r: ParsedRoutine, opts: FormatOptions): string | null { +export function formatComment(r: ParsedRoutine, opts: FormatOptions): string | null { if (r.comment == null) return null; const typeKw = r.type === "function" diff --git a/src/parser/routine.ts b/src/parser/routine.ts index 24e2fe2..54b2a37 100644 --- a/src/parser/routine.ts +++ b/src/parser/routine.ts @@ -117,8 +117,14 @@ function stripComments(sql: string): string { * This prevents matching CREATE FUNCTION inside dynamic SQL strings. */ function stripDollarBodies(sql: string): string { - const dollarQuoteRe = /(\$[a-zA-Z_0-9]*\$)([\s\S]*?)\1/g; - return sql.replace(dollarQuoteRe, "$1$1"); + // Only strip dollar-quoted bodies preceded by AS (function/procedure bodies). + // DO $$ ... $$ blocks are left intact so CREATE statements inside them are visible. + const re = /\bAS\s+(\$[a-zA-Z_0-9]*\$)([\s\S]*?)\1/gi; + // Replace body content with spaces to preserve string length (position alignment with commentStripped) + return sql.replace(re, (match, tag, body) => { + const prefix = match.substring(0, match.indexOf(tag)); + return prefix + tag + " ".repeat(body.length) + tag; + }); } /** @@ -214,13 +220,19 @@ function parseParameters(paramStr: string): RoutineParameter[] { function extractBody(sql: string, afterParams: number): string | null { const rest = sql.substring(afterParams); - // 1. Dollar-quoted: AS $tag$...$tag$ + // Find the nearest body marker — dollar-quoted or single-quoted — to avoid + // matching a later function's body when the current one uses a different style. const dollarMatch = rest.match(/\bAS\s+(\$[a-zA-Z_0-9]*\$)([\s\S]*?)\1/i); - if (dollarMatch) return dollarMatch[2]; - - // 2. Single-quoted (with E prefix): AS [E]'...' const sqStart = rest.match(/\bAS\s+(E)?'/i); - if (sqStart) { + + const dollarPos = dollarMatch?.index ?? Infinity; + const sqPos = sqStart?.index ?? Infinity; + + // 1. Dollar-quoted: AS $tag$...$tag$ (use only if it appears before single-quoted) + if (dollarMatch && dollarPos <= sqPos) return dollarMatch[2]; + + // 2. Single-quoted (with E prefix): AS [E]'...' (use only if it appears before dollar-quoted) + if (sqStart && sqPos < dollarPos) { const offset = sqStart.index! + sqStart[0].length; let body = ""; let i = offset; @@ -267,11 +279,16 @@ function parseTableColumn(raw: string): TableColumn { function extractReturns(cleaned: string, afterCloseParen: number): RoutineReturn | null { const rest = cleaned.substring(afterCloseParen); - const returnsMatch = rest.match(/\bRETURNS\s+/i); + // Bound search to the zone between ) and body (AS, BEGIN ATOMIC, or ;) + const endMatch = rest.match(/\bAS\s|BEGIN\s+ATOMIC/i); + const endIdx = endMatch ? endMatch.index! : rest.indexOf(";"); + const zone = endIdx >= 0 ? rest.substring(0, endIdx) : rest; + + const returnsMatch = zone.match(/\bRETURNS\s+/i); if (!returnsMatch) return null; const afterReturns = returnsMatch.index! + returnsMatch[0].length; - const tail = rest.substring(afterReturns); + const tail = zone.substring(afterReturns); // RETURNS TABLE(...) const tableMatch = tail.match(/^TABLE\s*\(/i); @@ -407,7 +424,7 @@ const CREATE_ROUTINE_RE = new RegExp( */ const COMMENT_ON_RE = new RegExp( `\\bCOMMENT\\s+ON\\s+(FUNCTION|PROCEDURE)\\s+(?:(${IDENT})\\.)?` + - `(${IDENT})\\s*\\(([^)]*)\\)\\s+IS\\s+'((?:[^']|'')*)'\\s*;`, + `(${IDENT})\\s*\\(([^)]*(?:\\([^)]*\\)[^)]*)*)\\)\\s+IS\\s+'((?:[^']|'')*)'\\s*;`, "gi", ); @@ -446,7 +463,7 @@ function parseComments(commentStripped: string): Map { const GRANT_REVOKE_RE = new RegExp( `\\b(GRANT|REVOKE)\\s+(EXECUTE|ALL(?:\\s+PRIVILEGES)?)\\s+ON\\s+(FUNCTION|PROCEDURE)\\s+` + `(?:(${IDENT})\\.)?` + - `(${IDENT})\\s*\\(([^)]*)\\)\\s+(?:TO|FROM)\\s+([^;]+?)\\s*;`, + `(${IDENT})\\s*\\(([^)]*(?:\\([^)]*\\)[^)]*)*)\\)\\s+(?:TO|FROM)\\s+([^;]+?)\\s*;`, "gi", ); From 4873eb9a17b6f8d8d1552ef022478f4177fbaa84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 14 Mar 2026 13:55:50 +0100 Subject: [PATCH 6/9] Move selective sync from diff to sync command - diff is now purely read-only (compare only, no file modifications) - sync gains --comments/--grants/--definitions/--all flags for surgical updates to existing source files without full overwrite - Extract fix utilities into src/parser/fix.ts (shared module) - Update help text and README to reflect new command structure Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 22 +++--- src/cli.ts | 26 +++---- src/commands/diff.ts | 161 +------------------------------------------ src/commands/sync.ts | 123 ++++++++++++++++++++++++++++++++- src/parser/fix.ts | 102 +++++++++++++++++++++++++++ 5 files changed, 251 insertions(+), 183 deletions(-) create mode 100644 src/parser/fix.ts diff --git a/README.md b/README.md index af42242..4dd64ea 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ Sections: ### `pgdev sync` -Extract database schema and routines into project files: +Extract database schema and routines into project files (DB → Files): - Dumps the full schema to `migrations_dir/schema.sql` (DDL for tables, types, etc.) - Extracts each routine (function, procedure, or other configured types) into individual `.sql` files in `routines_dir` @@ -52,9 +52,18 @@ Extract database schema and routines into project files: - Supports `VIEW` extraction when added to `routine_types` - On re-sync, updates existing files in place and reports created/updated/unchanged counts +Selective sync updates only specific aspects of existing source files without overwriting them: + +| Flag | Description | +|------|-------------| +| `--comments` | Surgically insert or update `COMMENT ON` statements from the database | +| `--grants` | Update `GRANT`/`REVOKE` statements from the database | +| `--definitions` | Update routine definitions from the database | +| `--all` | Apply all selective updates above | + ### `pgdev diff` -Compare project SQL files against the live database: +Compare project SQL files against the live database (read-only): - Parses all `.sql` files in `routines_dir` and fetches routine metadata from `pg_catalog` - Reports routines that need creating, updating, or dropping @@ -62,15 +71,6 @@ Compare project SQL files against the live database: - Supports `ignore_body_whitespace` for whitespace-insensitive body comparison - Supports routines inside `DO $$ ... $$` blocks and files with multiple routines -Fix switches pull data from the database into your source files: - -| Flag | Description | -|------|-------------| -| `--fix-comments` | Update source files with `COMMENT ON` statements from the database | -| `--fix-grants` | Update source files with `GRANT`/`REVOKE` statements from the database | -| `--fix-definitions` | Update source files with routine definitions from the database | -| `--fix-all` | Apply all fixes above | - ### `pgdev exec ` Execute a SQL command via psql using the configured connection. diff --git a/src/cli.ts b/src/cli.ts index dc6f528..2bd0fa3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -431,13 +431,13 @@ ${pc.bold("Commands:")} config Configure tools, NpgsqlRest, environment, and project init, setup Alias for config diff Compare project routines with database - --fix-comments Update source files with comments from database - --fix-grants Update source files with grants from database - --fix-definitions Update source files with definitions from database - --fix-all Apply all fixes above exec Execute SQL command via psql psql Open interactive psql session sync Sync database routines and schema to project files + --comments Update only comments in existing source files + --grants Update only grants in existing source files + --definitions Update only definitions in existing source files + --all Apply all selective updates above update Update ${PACKAGE_NAME} to the latest version `; @@ -504,18 +504,18 @@ export async function run(): Promise { case "psql": await psqlCommand(config); break; - case "diff": { - const fixFlags = { - comments: args.includes("--fix-comments") || args.includes("--fix-all"), - grants: args.includes("--fix-grants") || args.includes("--fix-all"), - definitions: args.includes("--fix-definitions") || args.includes("--fix-all"), + case "diff": + await diffCommand(config); + break; + case "sync": { + const syncFlags = { + comments: args.includes("--comments") || args.includes("--all"), + grants: args.includes("--grants") || args.includes("--all"), + definitions: args.includes("--definitions") || args.includes("--all"), }; - await diffCommand(config, fixFlags); + await syncCommand(config, syncFlags); break; } - case "sync": - await syncCommand(config); - break; case "update": await updateCommand(config); break; diff --git a/src/commands/diff.ts b/src/commands/diff.ts index 9a335da..00967cd 100644 --- a/src/commands/diff.ts +++ b/src/commands/diff.ts @@ -3,16 +3,9 @@ import { statSync } from "node:fs"; import type { PgdevConfig } from "../config.ts"; import { pc, spinner } from "../utils/terminal.ts"; import { findSqlFiles } from "../utils/files.ts"; -import { parseRoutines, type ParsedRoutine, quoteIdent } from "../parser/routine.ts"; +import { parseRoutines, type ParsedRoutine } from "../parser/routine.ts"; import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; import { routinesDiffer, commentsDiffer, grantsDiffer, type DiffOptions } from "../parser/compare.ts"; -import { formatComment, configToFormatOptions, type FormatOptions } from "../parser/formatter.ts"; - -export interface FixFlags { - comments: boolean; - grants: boolean; - definitions: boolean; -} /** * Match key uses schema.name only. Overloaded functions (same name, different @@ -22,7 +15,6 @@ function groupKey(schema: string, name: string): string { return `${schema}.${name}`; } -/** Display key includes full parameter signature (name + type). */ function parsedGroupKey(r: ParsedRoutine, defaultSchema: string): string { return groupKey(r.schema ?? defaultSchema, r.name); } @@ -42,112 +34,7 @@ function catalogDisplayKey(r: CatalogRoutine): string { return `${r.schema}.${r.name}(${params.join(", ")})`; } -/** Build a regex that matches an existing COMMENT ON for a routine. */ -function buildCommentOnRegex(r: ParsedRoutine): RegExp { - const typeKw = `(?:FUNCTION|PROCEDURE)`; - const schema = r.schema ? `(?:${escapeRegex(quoteIdent(r.schema, r.schemaQuoted ?? false))}|${escapeRegex(r.schema)})\\.` : ""; - const name = `(?:${escapeRegex(quoteIdent(r.name, r.nameQuoted ?? false))}|${escapeRegex(r.name)})`; - return new RegExp( - `\\bCOMMENT\\s+ON\\s+${typeKw}\\s+${schema}${name}\\s*\\([^)]*\\)\\s+IS\\s+'(?:[^']|'')*'\\s*;`, - "gi", - ); -} - -function escapeRegex(s: string): string { - return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - -/** - * Find the end position of a routine body in the source text. - * Searches forward from the CREATE position for the body end ($$; or ';). - */ -function findRoutineBodyEnd(content: string, routine: ParsedRoutine): number { - // Find the CREATE statement for this routine - const schema = routine.schema - ? `(?:${escapeRegex(quoteIdent(routine.schema, routine.schemaQuoted ?? false))}|${escapeRegex(routine.schema)})\\.` - : ""; - const name = `(?:${escapeRegex(quoteIdent(routine.name, routine.nameQuoted ?? false))}|${escapeRegex(routine.name)})`; - const createRe = new RegExp( - `\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\s+${schema}${name}\\s*\\(`, - "gi", - ); - const createMatch = createRe.exec(content); - if (!createMatch) return -1; - - // From the CREATE position, find the body end - const rest = content.substring(createMatch.index); - - // Try dollar-quoted body: find AS $tag$...$tag$; - const dollarRe = /\bAS\s+(\$[a-zA-Z_0-9]*\$)[\s\S]*?\1\s*;/i; - const dollarMatch = rest.match(dollarRe); - - // Try single-quoted body: find AS [E]'...'; - const sqRe = /\bAS\s+(?:E)?'/i; - const sqMatch = rest.match(sqRe); - - const dollarPos = dollarMatch?.index ?? Infinity; - const sqPos = sqMatch?.index ?? Infinity; - - if (dollarMatch && dollarPos <= sqPos) { - return createMatch.index + dollarMatch.index! + dollarMatch[0].length; - } - - if (sqMatch && sqPos < dollarPos) { - // Find end of single-quoted string - let i = sqMatch.index! + sqMatch[0].length; - while (i < rest.length) { - if (rest[i] === "'" && rest[i + 1] === "'") { i += 2; continue; } - if (rest[i] === "'") { - // Find the semicolon after the closing quote - const afterQuote = rest.substring(i + 1); - const semi = afterQuote.match(/^\s*;/); - return createMatch.index + i + 1 + (semi ? semi[0].length : 0); - } - i++; - } - } - - return -1; -} - -/** - * Apply comment fixes to a file. Returns the number of routines fixed. - */ -function applyCommentFixes( - content: string, - fixes: { routine: ParsedRoutine; catalogComment: string }[], - formatOpts: FormatOptions, -): { content: string; count: number } { - let result = content; - let count = 0; - - for (const { routine, catalogComment } of fixes) { - // Create a routine copy with the catalog comment for formatting - const withComment: ParsedRoutine = { ...routine, comment: catalogComment }; - const commentSql = formatComment(withComment, formatOpts); - if (!commentSql) continue; - - // Try to replace existing COMMENT ON - const commentRe = buildCommentOnRegex(routine); - if (commentRe.test(result)) { - result = result.replace(commentRe, commentSql); - count++; - continue; - } - - // No existing COMMENT ON — insert after routine body end - const bodyEnd = findRoutineBodyEnd(result, routine); - if (bodyEnd === -1) continue; - - // Insert COMMENT ON after the body end, with a blank line separator - result = result.substring(0, bodyEnd) + "\n\n" + commentSql + result.substring(bodyEnd); - count++; - } - - return { content: result, count }; -} - -export async function diffCommand(config: PgdevConfig, fix?: FixFlags): Promise { +export async function diffCommand(config: PgdevConfig): Promise { const { routines_dir, schemas, grants, ignore_body_whitespace } = config.project; if (!routines_dir) { @@ -225,9 +112,6 @@ export async function diffCommand(config: PgdevConfig, fix?: FixFlags): Promise< const needDropping: string[] = []; const matchedCatalogKeys = new Set(); - // Collect fixable comment diffs grouped by absolute file path - const commentFixes = new Map(); - for (const [gk, parsedList] of parsedGroups) { const catList = catalogGroups.get(gk); if (!catList) { @@ -252,21 +136,12 @@ export async function diffCommand(config: PgdevConfig, fix?: FixFlags): Promise< const changes: string[] = []; const diffOpts: DiffOptions = { ignoreBodyWhitespace: ignore_body_whitespace }; if (routinesDiffer(p.routine, cat, diffOpts)) changes.push("definition"); - const hasCommentDiff = commentsDiffer(p.routine, cat); - if (hasCommentDiff) changes.push("comment"); + if (commentsDiffer(p.routine, cat)) changes.push("comment"); if (grants && grantsDiffer(p.routine, cat)) changes.push("grants"); if (changes.length > 0) { needUpdating.push({ display: p.display, file: p.file, changes }); } - - // Collect comment fix if needed - if (hasCommentDiff && fix?.comments && cat.comment != null) { - const absFile = resolve(process.cwd(), p.file); - let list = commentFixes.get(absFile); - if (!list) { list = []; commentFixes.set(absFile, list); } - list.push({ routine: p.routine, catalogComment: cat.comment }); - } } // Unmatched catalog routines in this group @@ -287,9 +162,6 @@ export async function diffCommand(config: PgdevConfig, fix?: FixFlags): Promise< if (needCreating.length === 0 && needUpdating.length === 0 && needDropping.length === 0) { console.log(pc.green(`All ${totalParsed} routines match the database.`)); - if (fix?.comments) console.log(pc.dim("No comment differences to fix.")); - if (fix?.grants) console.log(pc.dim("No grant differences to fix.")); - if (fix?.definitions) console.log(pc.dim("No definition differences to fix.")); return; } @@ -326,31 +198,4 @@ export async function diffCommand(config: PgdevConfig, fix?: FixFlags): Promise< if (needUpdating.length > 0) parts.push(pc.yellow(`${needUpdating.length} to update`)); if (needDropping.length > 0) parts.push(pc.red(`${needDropping.length} to drop`)); console.log(parts.join(", ")); - - // Apply fixes - if (fix?.comments && commentFixes.size > 0) { - console.log(); - const formatOpts = configToFormatOptions(config.format); - let totalFixed = 0; - for (const [absFile, fixes] of commentFixes) { - const content = await Bun.file(absFile).text(); - const { content: updated, count } = applyCommentFixes(content, fixes, formatOpts); - if (count > 0) { - await Bun.write(absFile, updated); - const relPath = absFile.slice(process.cwd().length + 1); - console.log(` ${pc.green("✓")} ${relPath} ${pc.dim(`${count} comment${count > 1 ? "s" : ""}`)}`); - totalFixed += count; - } - } - if (totalFixed > 0) { - console.log(pc.green(`\nFixed ${totalFixed} comment${totalFixed > 1 ? "s" : ""}.`)); - } - } - - if (fix?.definitions) { - console.log(pc.yellow("\n--fix-definitions is not yet implemented.")); - } - if (fix?.grants) { - console.log(pc.yellow("\n--fix-grants is not yet implemented.")); - } } diff --git a/src/commands/sync.ts b/src/commands/sync.ts index 74417a8..7fd290c 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -8,6 +8,16 @@ import { error, success, pc, formatCmd } from "../utils/terminal.ts"; import { findSqlFiles } from "../utils/files.ts"; import { parseRoutines, unquoteIdent } from "../parser/routine.ts"; import { isApiRoutine, getGroupDir, formatRoutines, configToFormatOptions, DEFAULT_SKIP_PREFIXES } from "../parser/formatter.ts"; +import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; +import { commentsDiffer } from "../parser/compare.ts"; +import { applyCommentFixes } from "../parser/fix.ts"; +import type { ParsedRoutine } from "../parser/routine.ts"; + +export interface SyncFlags { + comments: boolean; + grants: boolean; + definitions: boolean; +} function cleanRestoreOutput(sql: string): string { return sql @@ -88,7 +98,118 @@ export function parseRoutineGroups( return groupOrder.map((name) => groups.get(name)!); } -export async function syncCommand(config: PgdevConfig): Promise { +/** + * Selective sync: update only comments (or grants) in existing source files + * by comparing parsed routines against the database catalog. + */ +async function selectiveSync(config: PgdevConfig, flags: SyncFlags): Promise { + const { routines_dir, schemas, grants } = config.project; + + if (!routines_dir) { + console.error(error("No routines_dir configured. Run pgdev config to set it up.")); + process.exit(1); + } + + if (schemas.length === 0) { + console.error(error("No schemas configured. Run pgdev config to set project schemas.")); + process.exit(1); + } + + const fullDir = resolve(process.cwd(), routines_dir); + if (!existsSync(fullDir)) { + console.error(error(`Routines directory not found: ${routines_dir}`)); + process.exit(1); + } + + const sqlFiles = findSqlFiles(fullDir); + if (sqlFiles.length === 0) { + console.log(pc.yellow("No .sql files found in " + routines_dir)); + return; + } + + const defaultSchema = schemas[0]; + + // Parse all SQL files + const fileRoutines = new Map(); + for (const file of sqlFiles) { + const content = await Bun.file(file).text(); + const routines = parseRoutines(content, { grants }); + const relPath = file.slice(process.cwd().length + 1); + for (const r of routines) { + const key = `${r.schema ?? defaultSchema}.${r.name}`; + let list = fileRoutines.get(key); + if (!list) { list = []; fileRoutines.set(key, list); } + list.push({ routine: r, relPath }); + } + } + + // Fetch catalog + let catalog: CatalogRoutine[]; + try { + catalog = await fetchCatalogMetadata(config); + } catch (err) { + console.error(error(err instanceof Error ? err.message : String(err))); + process.exit(1); + } + + // Match and collect fixes grouped by absolute file path + const commentFixesByFile = new Map(); + + for (const cat of catalog) { + const key = `${cat.schema}.${cat.name}`; + const parsedList = fileRoutines.get(key); + if (!parsedList) continue; + + // Match by param count + const match = parsedList.find((p) => p.routine.parameters.length === cat.parameters.length); + if (!match) continue; + + if (flags.comments && commentsDiffer(match.routine, cat) && cat.comment != null) { + const absFile = resolve(process.cwd(), match.relPath); + let list = commentFixesByFile.get(absFile); + if (!list) { list = []; commentFixesByFile.set(absFile, list); } + list.push({ routine: match.routine, catalogComment: cat.comment }); + } + } + + // Apply comment fixes + if (flags.comments) { + if (commentFixesByFile.size === 0) { + console.log(pc.dim("No comment differences to sync.")); + return; + } + + const formatOpts = configToFormatOptions(config.format); + let totalFixed = 0; + for (const [absFile, fixes] of commentFixesByFile) { + const content = await Bun.file(absFile).text(); + const { content: updated, count } = applyCommentFixes(content, fixes, formatOpts); + if (count > 0) { + await Bun.write(absFile, updated); + const relPath = absFile.slice(process.cwd().length + 1); + console.log(` ${pc.green("✓")} ${relPath} ${pc.dim(`${count} comment${count > 1 ? "s" : ""}`)}`); + totalFixed += count; + } + } + if (totalFixed > 0) { + console.log(success(`Synced ${totalFixed} comment${totalFixed > 1 ? "s" : ""}.`)); + } + } + + if (flags.grants) { + console.log(pc.yellow("--grants sync is not yet implemented.")); + } + if (flags.definitions) { + console.log(pc.yellow("--definitions sync is not yet implemented.")); + } +} + +export async function syncCommand(config: PgdevConfig, flags?: SyncFlags): Promise { + // Selective sync mode — only update specific aspects of existing files + if (flags?.comments || flags?.grants || flags?.definitions) { + return selectiveSync(config, flags); + } + const migrationsDir = config.project.migrations_dir; if (!migrationsDir) { console.error(error("No migrations_dir configured. Run pgdev config to set it up.")); diff --git a/src/parser/fix.ts b/src/parser/fix.ts new file mode 100644 index 0000000..9e0d96f --- /dev/null +++ b/src/parser/fix.ts @@ -0,0 +1,102 @@ +import type { ParsedRoutine } from "./routine.ts"; +import { quoteIdent } from "./routine.ts"; +import { formatComment, type FormatOptions } from "./formatter.ts"; + +function escapeRegex(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Build a regex that matches an existing COMMENT ON for a routine. */ +function buildCommentOnRegex(r: ParsedRoutine): RegExp { + const typeKw = `(?:FUNCTION|PROCEDURE)`; + const schema = r.schema ? `(?:${escapeRegex(quoteIdent(r.schema, r.schemaQuoted ?? false))}|${escapeRegex(r.schema)})\\.` : ""; + const name = `(?:${escapeRegex(quoteIdent(r.name, r.nameQuoted ?? false))}|${escapeRegex(r.name)})`; + return new RegExp( + `\\bCOMMENT\\s+ON\\s+${typeKw}\\s+${schema}${name}\\s*\\([^)]*(?:\\([^)]*\\)[^)]*)*\\)\\s+IS\\s+'(?:[^']|'')*'\\s*;`, + "gi", + ); +} + +/** + * Find the end position of a routine body in the source text. + * Searches forward from the CREATE position for the body end ($$; or ';). + */ +function findRoutineBodyEnd(content: string, routine: ParsedRoutine): number { + const schema = routine.schema + ? `(?:${escapeRegex(quoteIdent(routine.schema, routine.schemaQuoted ?? false))}|${escapeRegex(routine.schema)})\\.` + : ""; + const name = `(?:${escapeRegex(quoteIdent(routine.name, routine.nameQuoted ?? false))}|${escapeRegex(routine.name)})`; + const createRe = new RegExp( + `\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\s+${schema}${name}\\s*\\(`, + "gi", + ); + const createMatch = createRe.exec(content); + if (!createMatch) return -1; + + const rest = content.substring(createMatch.index); + + // Try dollar-quoted body: find AS $tag$...$tag$; + const dollarRe = /\bAS\s+(\$[a-zA-Z_0-9]*\$)[\s\S]*?\1\s*;/i; + const dollarMatch = rest.match(dollarRe); + + // Try single-quoted body: find AS [E]'...'; + const sqRe = /\bAS\s+(?:E)?'/i; + const sqMatch = rest.match(sqRe); + + const dollarPos = dollarMatch?.index ?? Infinity; + const sqPos = sqMatch?.index ?? Infinity; + + if (dollarMatch && dollarPos <= sqPos) { + return createMatch.index + dollarMatch.index! + dollarMatch[0].length; + } + + if (sqMatch && sqPos < dollarPos) { + let i = sqMatch.index! + sqMatch[0].length; + while (i < rest.length) { + if (rest[i] === "'" && rest[i + 1] === "'") { i += 2; continue; } + if (rest[i] === "'") { + const afterQuote = rest.substring(i + 1); + const semi = afterQuote.match(/^\s*;/); + return createMatch.index + i + 1 + (semi ? semi[0].length : 0); + } + i++; + } + } + + return -1; +} + +/** + * Apply comment fixes to a file. Returns the number of routines fixed. + */ +export function applyCommentFixes( + content: string, + fixes: { routine: ParsedRoutine; catalogComment: string }[], + formatOpts: FormatOptions, +): { content: string; count: number } { + let result = content; + let count = 0; + + for (const { routine, catalogComment } of fixes) { + const withComment: ParsedRoutine = { ...routine, comment: catalogComment }; + const commentSql = formatComment(withComment, formatOpts); + if (!commentSql) continue; + + // Try to replace existing COMMENT ON + const commentRe = buildCommentOnRegex(routine); + if (commentRe.test(result)) { + result = result.replace(commentRe, commentSql); + count++; + continue; + } + + // No existing COMMENT ON — insert after routine body end + const bodyEnd = findRoutineBodyEnd(result, routine); + if (bodyEnd === -1) continue; + + result = result.substring(0, bodyEnd) + "\n\n" + commentSql + result.substring(bodyEnd); + count++; + } + + return { content: result, count }; +} From 643f8853beefdc189d4674840a8132265665239c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 14 Mar 2026 14:57:40 +0100 Subject: [PATCH 7/9] Add diff --script for SQL migration script generation - diff --script [file] generates a procedural DO block migration script matching pgmigrations format (useProceduralScript style) - Script includes CREATE, UPDATE (definition/comment/grants), and DROP - Each migration step has raise info with timing, routine signature, and file path - Optional file path argument; defaults to temp directory - diff remains read-only (--script only writes the migration file) - Export formatComment, formatGrants, qualifiedName from formatter - Update help text and README Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 4 ++ src/cli.ts | 33 +++++---- src/commands/diff.ts | 152 ++++++++++++++++++++++++++++++++++++---- src/parser/formatter.ts | 4 +- 4 files changed, 166 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 4dd64ea..cecc476 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,10 @@ Compare project SQL files against the live database (read-only): - Supports `ignore_body_whitespace` for whitespace-insensitive body comparison - Supports routines inside `DO $$ ... $$` blocks and files with multiple routines +| Flag | Description | +|------|-------------| +| `--script [file]` | Generate a SQL migration script (procedural `DO` block) for all differences. Optionally specify output file path; defaults to a temp file. | + ### `pgdev exec ` Execute a SQL command via psql using the configured connection. diff --git a/src/cli.ts b/src/cli.ts index 2bd0fa3..07d3db6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -428,16 +428,16 @@ ${pc.bold("Usage:")} ${PACKAGE_NAME} [options] ${pc.bold("Commands:")} - config Configure tools, NpgsqlRest, environment, and project - init, setup Alias for config - diff Compare project routines with database - exec Execute SQL command via psql - psql Open interactive psql session - sync Sync database routines and schema to project files - --comments Update only comments in existing source files - --grants Update only grants in existing source files - --definitions Update only definitions in existing source files - --all Apply all selective updates above + config Interactive TUI for tools, NpgsqlRest config, and project setup + sync Extract routines and schema from database into project files + --comments Patch comments into existing files (no overwrite) + --grants Patch grants into existing files (no overwrite) + --definitions Patch definitions into existing files (no overwrite) + --all Patch all of the above into existing files + diff Compare project files against database (read-only) + --script [file] Generate SQL migration script for all differences + exec Run a SQL statement via psql + psql Open an interactive psql session update Update ${PACKAGE_NAME} to the latest version `; @@ -504,9 +504,18 @@ export async function run(): Promise { case "psql": await psqlCommand(config); break; - case "diff": - await diffCommand(config); + case "diff": { + const scriptIdx = args.indexOf("--script"); + const scriptFile = scriptIdx !== -1 + ? (args[scriptIdx + 1] && !args[scriptIdx + 1].startsWith("--") ? args[scriptIdx + 1] : undefined) + : undefined; + const diffFlags = { + script: scriptIdx !== -1, + scriptFile, + }; + await diffCommand(config, diffFlags); break; + } case "sync": { const syncFlags = { comments: args.includes("--comments") || args.includes("--all"), diff --git a/src/commands/diff.ts b/src/commands/diff.ts index 00967cd..cc1c60e 100644 --- a/src/commands/diff.ts +++ b/src/commands/diff.ts @@ -1,11 +1,18 @@ import { resolve } from "node:path"; import { statSync } from "node:fs"; +import { tmpdir } from "node:os"; import type { PgdevConfig } from "../config.ts"; import { pc, spinner } from "../utils/terminal.ts"; import { findSqlFiles } from "../utils/files.ts"; import { parseRoutines, type ParsedRoutine } from "../parser/routine.ts"; import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; import { routinesDiffer, commentsDiffer, grantsDiffer, type DiffOptions } from "../parser/compare.ts"; +import { formatRoutine, formatComment, formatGrants, qualifiedName, configToFormatOptions } from "../parser/formatter.ts"; + +export interface DiffFlags { + script: boolean; + scriptFile?: string; +} /** * Match key uses schema.name only. Overloaded functions (same name, different @@ -34,7 +41,13 @@ function catalogDisplayKey(r: CatalogRoutine): string { return `${r.schema}.${r.name}(${params.join(", ")})`; } -export async function diffCommand(config: PgdevConfig): Promise { +/** Build qualified name for DROP statements from catalog routine. */ +function catalogQualifiedSig(r: CatalogRoutine): string { + const params = r.parameters.map((p) => p.type).join(", "); + return `${r.schema}.${r.name}(${params})`; +} + +export async function diffCommand(config: PgdevConfig, flags?: DiffFlags): Promise { const { routines_dir, schemas, grants, ignore_body_whitespace } = config.project; if (!routines_dir) { @@ -67,7 +80,8 @@ export async function diffCommand(config: PgdevConfig): Promise { const defaultSchema = schemas[0]; // Collect parsed routines grouped by schema.name - const parsedGroups = new Map(); + // Also keep raw file content for --script (to include the original SQL) + const parsedGroups = new Map(); let totalParsed = 0; for (const file of sqlFiles) { @@ -79,7 +93,7 @@ export async function diffCommand(config: PgdevConfig): Promise { const dk = parsedDisplayKey(r, defaultSchema); let group = parsedGroups.get(gk); if (!group) { group = []; parsedGroups.set(gk, group); } - group.push({ routine: r, file: relPath, display: dk }); + group.push({ routine: r, file: relPath, display: dk, content }); totalParsed++; } } @@ -107,15 +121,15 @@ export async function diffCommand(config: PgdevConfig): Promise { } // Compare — match by schema.name, then by param count for overloads - const needCreating: { display: string; file: string }[] = []; - const needUpdating: { display: string; file: string; changes: string[] }[] = []; - const needDropping: string[] = []; + const needCreating: { display: string; file: string; routine: ParsedRoutine; content: string }[] = []; + const needUpdating: { display: string; file: string; changes: string[]; routine: ParsedRoutine; content: string; catalog: CatalogRoutine }[] = []; + const needDropping: { display: string; catalog: CatalogRoutine }[] = []; const matchedCatalogKeys = new Set(); for (const [gk, parsedList] of parsedGroups) { const catList = catalogGroups.get(gk); if (!catList) { - for (const p of parsedList) needCreating.push({ display: p.display, file: p.file }); + for (const p of parsedList) needCreating.push({ display: p.display, file: p.file, routine: p.routine, content: p.content }); continue; } @@ -127,7 +141,7 @@ export async function diffCommand(config: PgdevConfig): Promise { const paramCount = p.routine.parameters.length; const catIdx = catList.findIndex((c, i) => !usedCat.has(i) && c.routine.parameters.length === paramCount); if (catIdx === -1) { - needCreating.push({ display: p.display, file: p.file }); + needCreating.push({ display: p.display, file: p.file, routine: p.routine, content: p.content }); continue; } usedCat.add(catIdx); @@ -140,20 +154,20 @@ export async function diffCommand(config: PgdevConfig): Promise { if (grants && grantsDiffer(p.routine, cat)) changes.push("grants"); if (changes.length > 0) { - needUpdating.push({ display: p.display, file: p.file, changes }); + needUpdating.push({ display: p.display, file: p.file, changes, routine: p.routine, content: p.content, catalog: cat }); } } // Unmatched catalog routines in this group for (let i = 0; i < catList.length; i++) { - if (!usedCat.has(i)) needDropping.push(catList[i].display); + if (!usedCat.has(i)) needDropping.push({ display: catList[i].display, catalog: catList[i].routine }); } } // Catalog routines with no parsed group at all for (const [gk, catList] of catalogGroups) { if (!matchedCatalogKeys.has(gk)) { - for (const c of catList) needDropping.push(c.display); + for (const c of catList) needDropping.push({ display: c.display, catalog: c.routine }); } } @@ -162,6 +176,7 @@ export async function diffCommand(config: PgdevConfig): Promise { if (needCreating.length === 0 && needUpdating.length === 0 && needDropping.length === 0) { console.log(pc.green(`All ${totalParsed} routines match the database.`)); + if (flags?.script) console.log(pc.dim("No script generated — nothing to migrate.")); return; } @@ -185,8 +200,8 @@ export async function diffCommand(config: PgdevConfig): Promise { if (needDropping.length > 0) { console.log(pc.bold(`Only in database (${needDropping.length}):`)); - for (const key of needDropping) { - console.log(` ${pc.red("-")} ${key}`); + for (const { display } of needDropping) { + console.log(` ${pc.red("-")} ${display}`); } console.log(); } @@ -198,4 +213,115 @@ export async function diffCommand(config: PgdevConfig): Promise { if (needUpdating.length > 0) parts.push(pc.yellow(`${needUpdating.length} to update`)); if (needDropping.length > 0) parts.push(pc.red(`${needDropping.length} to drop`)); console.log(parts.join(", ")); + + // Generate migration script + if (flags?.script) { + const formatOpts = configToFormatOptions(config.format); + const date = new Date(); + const ident = date.toISOString().replace(/[-:.ZT]/g, ""); + const tag = `$migration_${ident}$`; + const lines: string[] = []; + let migrationIdx = 0; + + lines.push("do"); + lines.push(tag); + lines.push("declare ___clock timestamp with time zone;"); + lines.push("begin"); + lines.push("--"); + lines.push("-- Migration file generated by pgdev"); + lines.push(`-- Date: ${date.toISOString()}`); + lines.push("--"); + lines.push(""); + + // Create new routines + for (const { file, routine } of needCreating) { + migrationIdx++; + const display = parsedDisplayKey(routine, defaultSchema); + lines.push("--"); + lines.push(`-- Migration ${migrationIdx}`); + lines.push(`-- Script: ${file}`); + lines.push(`-- Type: CREATE`); + lines.push("--"); + lines.push("___clock = clock_timestamp();"); + lines.push(`-- Migration ${migrationIdx} start`); + lines.push(formatRoutine(routine, formatOpts)); + lines.push(`-- Migration ${migrationIdx} end`); + lines.push(`raise info 'Migration ${migrationIdx}: CREATE ${display} completed in % (${file})', clock_timestamp() - ___clock;`); + lines.push(""); + } + + // Update changed routines + for (const { file, changes, routine } of needUpdating) { + migrationIdx++; + const display = parsedDisplayKey(routine, defaultSchema); + lines.push("--"); + lines.push(`-- Migration ${migrationIdx}`); + lines.push(`-- Script: ${file}`); + lines.push(`-- Type: UPDATE (${changes.join(", ")})`); + lines.push("--"); + lines.push("___clock = clock_timestamp();"); + lines.push(`-- Migration ${migrationIdx} start`); + + if (changes.includes("definition")) { + lines.push(formatRoutine(routine, { ...formatOpts, createOrReplace: true })); + } + + if (changes.includes("comment")) { + const commentSql = formatComment(routine, formatOpts); + if (commentSql) { + lines.push(commentSql); + } else { + // File has no comment — remove from database + const kw = (w: string) => formatOpts.lowercase ? w.toLowerCase() : w; + const typeKw = kw(routine.type === "function" ? "FUNCTION" : "PROCEDURE"); + const qn = qualifiedName(routine); + const sig = routine.parameters.map((p) => formatOpts.lowercase ? p.type.toLowerCase() : p.type).join(", "); + lines.push(`${kw("COMMENT ON")} ${typeKw} ${qn}(${sig}) ${kw("IS")} NULL;`); + } + lines.push(""); + } + + if (changes.includes("grants")) { + const grantSql = formatGrants(routine, formatOpts); + if (grantSql.length > 0) { + lines.push(grantSql.join("\n")); + lines.push(""); + } + } + + lines.push(`-- Migration ${migrationIdx} end`); + lines.push(`raise info 'Migration ${migrationIdx}: UPDATE ${display} (${changes.join(", ")}) completed in % (${file})', clock_timestamp() - ___clock;`); + lines.push(""); + } + + // Drop routines only in database + for (const { catalog: cat } of needDropping) { + migrationIdx++; + const typeKw = formatOpts.lowercase ? cat.type : cat.type.toUpperCase(); + const sig = catalogQualifiedSig(cat); + const dropKw = formatOpts.lowercase ? "drop" : "DROP"; + const ifExistsKw = formatOpts.lowercase ? "if exists" : "IF EXISTS"; + const display = `${cat.schema}.${cat.name}(${cat.parameters.map((p) => p.type).join(", ")})`; + + lines.push("--"); + lines.push(`-- Migration ${migrationIdx}`); + lines.push(`-- Type: DROP`); + lines.push("--"); + lines.push("___clock = clock_timestamp();"); + lines.push(`-- Migration ${migrationIdx} start`); + lines.push(`${dropKw} ${typeKw} ${ifExistsKw} ${sig};`); + lines.push(`-- Migration ${migrationIdx} end`); + lines.push(`raise info 'Migration ${migrationIdx}: DROP ${display} completed in %', clock_timestamp() - ___clock;`); + lines.push(""); + } + + lines.push("end;"); + lines.push(`${tag};`); + + const scriptFile = flags.scriptFile + ? resolve(process.cwd(), flags.scriptFile) + : resolve(tmpdir(), `migration_${ident}.sql`); + await Bun.write(scriptFile, lines.join("\n") + "\n"); + console.log(`\n${pc.bold("Migration script:")} ${scriptFile}`); + } } diff --git a/src/parser/formatter.ts b/src/parser/formatter.ts index 4c1ae62..4b6baaa 100644 --- a/src/parser/formatter.ts +++ b/src/parser/formatter.ts @@ -74,7 +74,7 @@ function kw(word: string, lowercase: boolean): string { } /** Build schema-qualified name, quoting identifiers that were quoted in the source. */ -function qualifiedName(r: ParsedRoutine): string { +export function qualifiedName(r: ParsedRoutine): string { const name = quoteIdent(r.name, r.nameQuoted ?? false); if (r.schema) { const schema = quoteIdent(r.schema, r.schemaQuoted ?? false); @@ -211,7 +211,7 @@ export function formatComment(r: ParsedRoutine, opts: FormatOptions): string | n } /** Format GRANT/REVOKE statements. */ -function formatGrants(r: ParsedRoutine, opts: FormatOptions): string[] { +export function formatGrants(r: ParsedRoutine, opts: FormatOptions): string[] { if (r.grants.length === 0) return []; const typeKw = r.type === "function" From 6137e5125bd009155774bc666b65fdf40e415787 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sun, 15 Mar 2026 12:29:09 +0100 Subject: [PATCH 8/9] Add interactive sync, functional comparison, and surgical updates - Sync is interactive by default: shows changes, prompts Y/n/N/a/q - Functional comparison: only updates files with real differences (definition, comments, grants), preserves user formatting - Surgical updates: patches only changed parts of existing files (body, comments, grants) instead of full file overwrite - Multi-routine files: groups routines by target file, writes together - sync_skip config: "Never" option remembers files to skip - --force flag skips interactive prompts - --format flag rewrites all files with configured formatting - Comment removal: removes COMMENT ON when DB has no comment - Ctrl+C handling in prompts - Fix backfillConfig duplicate sync_skip entries Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 27 ++-- src/cli.ts | 14 +- src/commands/sync.ts | 304 ++++++++++++++++++++++++++++++++++++++---- src/config.ts | 6 + src/parser/compare.ts | 70 ++++++++++ src/parser/fix.ts | 123 ++++++++++++++++- 6 files changed, 506 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index cecc476..c2d4481 100644 --- a/README.md +++ b/README.md @@ -47,19 +47,28 @@ Extract database schema and routines into project files (DB → Files): - Dumps the full schema to `migrations_dir/schema.sql` (DDL for tables, types, etc.) - Extracts each routine (function, procedure, or other configured types) into individual `.sql` files in `routines_dir` -- Applies configurable formatting (see `[format]` options) +- Applies configurable formatting to new files (see `[format]` options) - Organizes files into subdirectories based on `group_order` (by API type, schema, name segment, or object kind) - Supports `VIEW` extraction when added to `routine_types` -- On re-sync, updates existing files in place and reports created/updated/unchanged counts - -Selective sync updates only specific aspects of existing source files without overwriting them: +- **Interactive by default** — shows each change and prompts before writing: + - `Y` (default) — apply this change + - `n` — skip this file + - `N` — skip and remember (adds to `sync_skip` in config, skipped in future syncs) + - `a` — apply all remaining changes without prompting + - `q` — quit immediately +- **Functional comparison** — existing files are only updated when there's a real difference (definition, comments, grants), not just formatting. User formatting is preserved for unchanged files. +- Handles multi-routine files — multiple routines in one file are synced together | Flag | Description | |------|-------------| -| `--comments` | Surgically insert or update `COMMENT ON` statements from the database | -| `--grants` | Update `GRANT`/`REVOKE` statements from the database | -| `--definitions` | Update routine definitions from the database | -| `--all` | Apply all selective updates above | +| `--force`, `-f` | Skip interactive prompts, write all changes immediately | +| `--format` | Rewrite all files using configured format options (normalizes formatting) | +| `--comments` | Patch only `COMMENT ON` statements in existing files (combinable) | +| `--grants` | Patch only `GRANT`/`REVOKE` statements in existing files (combinable) | +| `--definitions` | Patch only routine definitions in existing files (combinable) | +| `--all` | Patch comments, grants, and definitions | + +Note: `--format` cannot be combined with `--comments`/`--grants`/`--definitions`. ### `pgdev diff` @@ -175,6 +184,7 @@ internal_dir = "" group_segment = 0 skip_prefixes = [] group_order = [] +sync_skip = [] # SQL formatting options (applied during sync) [format] @@ -266,6 +276,7 @@ Project directories and sync/diff settings. | `group_segment` | `0` | Name segment index for the "name" grouping dimension (0 = disabled). Splits on `_` after skipping common prefixes | | `skip_prefixes` | `[]` | Prefixes to skip when extracting group segment (e.g. `["get", "set", "delete"]`). Uses built-in defaults when empty | | `group_order` | `[]` | Directory nesting order. Available dimensions: `"type"`, `"schema"`, `"name"`, `"kind"`. Empty = flat directory | +| `sync_skip` | `[]` | Files to skip during sync (relative paths, managed via interactive sync's "Never" option) | **Directory grouping dimensions:** diff --git a/src/cli.ts b/src/cli.ts index 07d3db6..d14443c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -430,10 +430,14 @@ ${pc.bold("Usage:")} ${pc.bold("Commands:")} config Interactive TUI for tools, NpgsqlRest config, and project setup sync Extract routines and schema from database into project files - --comments Patch comments into existing files (no overwrite) - --grants Patch grants into existing files (no overwrite) - --definitions Patch definitions into existing files (no overwrite) - --all Patch all of the above into existing files + Interactive by default — shows changes and prompts before writing + --force, -f Skip interactive prompts, write all changes immediately + --format Rewrite all files using configured format options + --comments Patch only comments into existing files (combinable) + --grants Patch only grants into existing files (combinable) + --definitions Patch only definitions into existing files (combinable) + --all Patch comments, grants, and definitions + Note: --format cannot be combined with patch flags diff Compare project files against database (read-only) --script [file] Generate SQL migration script for all differences exec Run a SQL statement via psql @@ -521,6 +525,8 @@ export async function run(): Promise { comments: args.includes("--comments") || args.includes("--all"), grants: args.includes("--grants") || args.includes("--all"), definitions: args.includes("--definitions") || args.includes("--all"), + format: args.includes("--format"), + force: args.includes("--force") || args.includes("-f"), }; await syncCommand(config, syncFlags); break; diff --git a/src/commands/sync.ts b/src/commands/sync.ts index 7fd290c..de511e3 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -1,7 +1,7 @@ import { resolve } from "node:path"; import { existsSync, mkdirSync, unlinkSync } from "node:fs"; import { tmpdir } from "node:os"; -import { type PgdevConfig } from "../config.ts"; +import { type PgdevConfig, updateConfigArray } from "../config.ts"; import { resolveConnection } from "./exec.ts"; import { splitCommand } from "../cli.ts"; import { error, success, pc, formatCmd } from "../utils/terminal.ts"; @@ -9,14 +9,37 @@ import { findSqlFiles } from "../utils/files.ts"; import { parseRoutines, unquoteIdent } from "../parser/routine.ts"; import { isApiRoutine, getGroupDir, formatRoutines, configToFormatOptions, DEFAULT_SKIP_PREFIXES } from "../parser/formatter.ts"; import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; -import { commentsDiffer } from "../parser/compare.ts"; -import { applyCommentFixes } from "../parser/fix.ts"; +import { commentsDiffer, parsedRoutinesDiffer } from "../parser/compare.ts"; +import { applyCommentFixes, applyBodyFixes, applyGrantFixes, removeComments } from "../parser/fix.ts"; import type { ParsedRoutine } from "../parser/routine.ts"; +import { bodyHash } from "../parser/catalog.ts"; + +type SyncAction = "yes" | "no" | "never" | "all" | "all-create" | "all-update" | "quit"; + +/** + * Prompt user for sync action. + * Ctrl+C / null input → quit. + */ +function askSyncAction(): SyncAction { + const input = prompt(` ${pc.dim("[Y]es / [n]o / [N]ever / [a]ll / [c]reate all / [u]pdate all / [q]uit")}`); + if (input === null) return "quit"; // Ctrl+C or Ctrl+D + const answer = input.trim().toLowerCase(); + if (answer === "" || answer === "y" || answer === "yes") return "yes"; + if (answer === "n" || answer === "no") return "no"; + if (answer.startsWith("ne") || answer === "never") return "never"; + if (answer === "a" || answer === "all") return "all"; + if (answer === "c" || answer === "create all") return "all-create"; + if (answer === "u" || answer === "update all") return "all-update"; + if (answer === "q" || answer === "quit") return "quit"; + return "yes"; // default +} export interface SyncFlags { comments: boolean; grants: boolean; definitions: boolean; + format: boolean; + force: boolean; } function cleanRestoreOutput(sql: string): string { @@ -207,6 +230,9 @@ async function selectiveSync(config: PgdevConfig, flags: SyncFlags): Promise { // Selective sync mode — only update specific aspects of existing files if (flags?.comments || flags?.grants || flags?.definitions) { + if (flags.format) { + console.error(pc.yellow("Warning: --format is ignored when using --comments, --grants, or --definitions.")); + } return selectiveSync(config, flags); } @@ -372,9 +398,18 @@ export async function syncCommand(config: PgdevConfig, flags?: SyncFlags): Promi if (routineGroups.length > 0) { const routineTocFile = resolve(tmpdir(), `pgdev-routine-toc-${Date.now()}.list`); try { - let created = 0; - let updated = 0; - let unchanged = 0; + const formatOpts = configToFormatOptions(config.format); + + // Collect original file contents for unchanged comparison + const existingFileContents = new Map(); + for (const file of existingFiles) { + existingFileContents.set(file, await Bun.file(file).text()); + } + + // First pass: extract each routine and group by target file + const forceFormat = flags?.format ?? false; + const fileRoutines = new Map(); + for (const group of routineGroups) { await Bun.write(routineTocFile, group.tocLines.join("\n") + "\n"); @@ -397,26 +432,17 @@ export async function syncCommand(config: PgdevConfig, flags?: SyncFlags): Promi } const cleaned = cleanRestoreOutput(rStdout); - const formatOpts = configToFormatOptions(config.format); const parsed = parseRoutines(cleaned, { grants: config.project.grants }); const routineSql = parsed.length > 0 ? formatRoutines(parsed, formatOpts) : cleaned; - // Strip quotes from TOC name for lookups/filenames (parser stores bare names) const bareName = unquoteIdent(group.name).bare; const existing = existingRoutines.get(bareName); - if (existing && existing.content.trimEnd() === routineSql.trimEnd()) { - // Content identical — skip - unchanged++; - if (config.verbose) { - console.error(pc.dim(` ${bareName} (unchanged)`)); - } - continue; - } - - // Write to existing file path if routine exists, otherwise new file + // Determine target file let outFile: string; + let isNew: boolean; if (existing) { outFile = existing.file; + isNew = false; } else { // Build target directory from group_order dimensions let targetDir = fullRoutinesDir; @@ -437,27 +463,255 @@ export async function syncCommand(config: PgdevConfig, flags?: SyncFlags): Promi } if (targetDir !== fullRoutinesDir) mkdirSync(targetDir, { recursive: true }); outFile = resolve(targetDir, `${bareName}.sql`); + isNew = true; } - await Bun.write(outFile, routineSql); - if (existing) { - updated++; + // Collect routine SQL and parsed data by target file + let entry = fileRoutines.get(outFile); + if (!entry) { + entry = { sqls: [], parsed: [], isNew }; + fileRoutines.set(outFile, entry); + } + entry.sqls.push(routineSql); + entry.parsed.push(...parsed); + } + + // Second pass: determine changes, prompt interactively, write + let created = 0; + let updated = 0; + let unchanged = 0; + let skipped = 0; + let aborted = false; + const interactive = !(flags?.force); + let autoCreate = false; // auto-approve all creates + let autoUpdate = false; // auto-approve all updates + const syncSkip = new Set(config.project.sync_skip); + const newSkips: string[] = []; + + for (const [outFile, { sqls, parsed: dbParsed, isNew }] of fileRoutines) { + const combined = sqls.join("\n"); + const relPath = outFile.slice(process.cwd().length + 1); + const originalContent = existingFileContents.get(outFile); + + // Check sync_skip list + if (syncSkip.has(relPath)) { + skipped++; if (config.verbose) { - console.error(pc.yellow(` ${bareName} (updated)`)); + console.error(pc.dim(` ${relPath} (skipped — in sync_skip)`)); + } + continue; + } + + // Determine if file needs writing and describe changes + if (originalContent != null) { + if (forceFormat) { + if (originalContent.trimEnd() === combined.trimEnd()) { + unchanged++; + if (config.verbose) { + console.error(pc.dim(` ${relPath} (unchanged)`)); + } + continue; + } + } else { + const fileParsed = parseRoutines(originalContent, { grants: config.project.grants }); + if (fileParsed.length === dbParsed.length) { + let allMatch = true; + for (let i = 0; i < fileParsed.length; i++) { + if (parsedRoutinesDiffer(fileParsed[i], dbParsed[i], { ignoreBodyWhitespace: config.project.ignore_body_whitespace })) { + allMatch = false; + break; + } + } + if (allMatch) { + unchanged++; + if (config.verbose) { + console.error(pc.dim(` ${relPath} (unchanged)`)); + } + continue; + } + } + } + } + + // Build change description and prompt + if (interactive && !(isNew && autoCreate) && !(!isNew && autoUpdate)) { + if (isNew) { + console.log(`\n${pc.green("CREATE")} ${pc.bold(relPath)}`); + for (const r of dbParsed) { + const qual = r.schema ? `${r.schema}.${r.name}` : r.name; + console.log(` ${pc.green("+")} ${qual} ${pc.dim(`[${r.type}]`)}`); + } + } else { + console.log(`\n${pc.yellow("UPDATE")} ${pc.bold(relPath)}`); + const fileParsed = parseRoutines(originalContent!, { grants: config.project.grants }); + for (const dbr of dbParsed) { + const qual = dbr.schema ? `${dbr.schema}.${dbr.name}` : dbr.name; + const match = fileParsed.find((fp) => fp.name === dbr.name && fp.schema === dbr.schema); + if (!match) { + console.log(` ${pc.green("+")} ${qual} ${pc.dim("[new routine]")}`); + } else { + const changes: string[] = []; + if (parsedRoutinesDiffer( + { ...match, comment: null, grants: [] }, + { ...dbr, comment: null, grants: [] }, + { ignoreBodyWhitespace: config.project.ignore_body_whitespace }, + )) { + changes.push("definition"); + } + if ((match.comment ?? null) !== (dbr.comment ?? null)) { + changes.push("comment"); + } + if (match.grants.length !== dbr.grants.length || + match.grants.some((g, i) => + g.privilege !== dbr.grants[i]?.privilege || + g.grantee !== dbr.grants[i]?.grantee || + g.isGrant !== dbr.grants[i]?.isGrant)) { + changes.push("grants"); + } + if (changes.length > 0) { + console.log(` ${pc.yellow("~")} ${qual} ${pc.dim(`[${changes.join(", ")}]`)}`); + } + } + if (forceFormat) { + console.log(` ${pc.dim(" (reformatting)")}`); + } + } + } + + const action = askSyncAction(); + if (action === "quit") { + aborted = true; + break; } + if (action === "never") { + skipped++; + newSkips.push(relPath); + console.log(pc.dim(` → Added to sync_skip`)); + continue; + } + if (action === "no") { + skipped++; + continue; + } + if (action === "all") { + autoCreate = true; + autoUpdate = true; + } else if (action === "all-create") { + autoCreate = true; + } else if (action === "all-update") { + autoUpdate = true; + } + } + + if (isNew || forceFormat) { + // New file or --format: write full formatted output + await Bun.write(outFile, combined); } else { + // Existing file: apply surgical patches per routine + let patched = originalContent!; + const fileParsed = parseRoutines(patched, { grants: config.project.grants }); + + const bodyFixes: { routine: ParsedRoutine; catalogBody: string }[] = []; + const commentFixes: { routine: ParsedRoutine; catalogComment: string }[] = []; + const commentRemovals: ParsedRoutine[] = []; + const grantFixes: { routine: ParsedRoutine; catalogGrants: ParsedRoutine["grants"] }[] = []; + + for (const dbr of dbParsed) { + const match = fileParsed.find((fp) => fp.name === dbr.name && fp.schema === dbr.schema); + if (!match) continue; // new routine in file — can't patch surgically + + // Body + if (dbr.body != null && match.body != null) { + const ignoreWs = config.project.ignore_body_whitespace; + if (bodyHash(match.body, ignoreWs) !== bodyHash(dbr.body, ignoreWs)) { + bodyFixes.push({ routine: match, catalogBody: dbr.body }); + } + } + + // Comment + if ((match.comment ?? null) !== (dbr.comment ?? null)) { + if (dbr.comment != null) { + commentFixes.push({ routine: match, catalogComment: dbr.comment }); + } else { + commentRemovals.push(match); + } + } + + // Grants + if (config.project.grants) { + const grantsDiff = match.grants.length !== dbr.grants.length || + match.grants.some((g, i) => + g.privilege !== dbr.grants[i]?.privilege || + g.grantee !== dbr.grants[i]?.grantee || + g.isGrant !== dbr.grants[i]?.isGrant); + if (grantsDiff) { + grantFixes.push({ routine: match, catalogGrants: dbr.grants }); + } + } + } + + // Check for routines in DB but not in file (can't patch, need full write) + const hasNewRoutines = dbParsed.some((dbr) => + !fileParsed.find((fp) => fp.name === dbr.name && fp.schema === dbr.schema)); + + if (hasNewRoutines) { + // Fall back to full write for files with new routines + await Bun.write(outFile, combined); + } else { + // Apply surgical patches + if (bodyFixes.length > 0) { + const r = applyBodyFixes(patched, bodyFixes); + patched = r.content; + } + if (commentRemovals.length > 0) { + const r = removeComments(patched, commentRemovals); + patched = r.content; + } + if (commentFixes.length > 0) { + const r = applyCommentFixes(patched, commentFixes, formatOpts); + patched = r.content; + } + if (grantFixes.length > 0) { + const r = applyGrantFixes(patched, grantFixes, formatOpts); + patched = r.content; + } + if (patched !== originalContent) { + await Bun.write(outFile, patched); + } + } + } + + if (isNew) { created++; - if (config.verbose) { - console.error(pc.green(` ${bareName} (created)`)); + if (!interactive && config.verbose) { + console.error(pc.green(` ${relPath} (created)`)); + } + } else { + updated++; + if (!interactive && config.verbose) { + console.error(pc.yellow(` ${relPath} (updated)`)); } } } + // Persist new sync_skip entries + if (newSkips.length > 0) { + const allSkips = [...config.project.sync_skip, ...newSkips]; + await updateConfigArray("project", "sync_skip", allSkips); + } + + if (aborted) { + console.log(pc.yellow("\nSync aborted.")); + } + const parts: string[] = []; if (created > 0) parts.push(pc.green(`${created} created`)); if (updated > 0) parts.push(pc.yellow(`${updated} updated`)); if (unchanged > 0) parts.push(`${unchanged} unchanged`); - console.log(success(`Routines in ${pc.bold(routinesDir + "/")}: ${parts.join(", ")}`)); + if (skipped > 0) parts.push(pc.dim(`${skipped} skipped`)); + if (parts.length > 0) { + console.log(success(`Routines in ${pc.bold(routinesDir + "/")}: ${parts.join(", ")}`)); + } } finally { try { unlinkSync(routineTocFile); } catch {} } diff --git a/src/config.ts b/src/config.ts index 5867ce0..47d561a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -40,6 +40,8 @@ export interface ProjectConfig { skip_prefixes: string[]; /** Directory nesting order. Available: "type", "schema", "name", "kind" */ group_order: GroupDimension[]; + /** Files to skip during sync (relative paths, set via "Never" in interactive mode) */ + sync_skip: string[]; } export interface FormatConfig { @@ -100,6 +102,7 @@ const defaults: PgdevConfig = { group_segment: 0, skip_prefixes: [], group_order: [], + sync_skip: [], }, format: { lowercase: true, @@ -423,6 +426,7 @@ const EXPECTED_KEYS: { section: string; key: string; raw: string }[] = [ { section: "project", key: "skip_prefixes", raw: "# Prefixes to skip when grouping by name segment (empty = use built-in defaults)\n# skip_prefixes = [\"get\", \"set\", \"delete\", \"insert\", \"update\", \"create\", \"remove\", \"find\", \"list\", \"is\", \"has\", \"check\", \"count\", \"compute\", \"run\", \"do\", \"send\"]\nskip_prefixes = []" }, { section: "project", key: "routine_types", raw: "# Object types to extract into individual files (excluded from schema.sql)\nroutine_types = [\"FUNCTION\", \"PROCEDURE\"]" }, { section: "project", key: "group_order", raw: "# Directory nesting order. Each element adds a subdirectory level.\n# Available: \"type\" (api/internal), \"schema\", \"name\" (name segment), \"kind\" (function/procedure)\n# Example: [\"type\", \"schema\", \"name\"] → api/myschema/auth/get_auth_login.sql\ngroup_order = []" }, + { section: "project", key: "sync_skip", raw: "# Files to skip during sync (relative paths, managed via interactive sync)\nsync_skip = []" }, // [format] { section: "format", key: "lowercase", raw: "# Lowercase SQL keywords in formatted output\nlowercase = true" }, { section: "format", key: "param_style", raw: '# Parameter layout: "inline" or "multiline"\nparam_style = "multiline"' }, @@ -584,6 +588,8 @@ routine_types = ["FUNCTION", "PROCEDURE"] # Available: "type" (api/internal), "schema", "name" (name segment), "kind" (function/procedure) # Example: ["type", "schema", "name"] → api/myschema/auth/get_auth_login.sql group_order = [] +# Files to skip during sync (relative paths, managed via interactive sync) +sync_skip = [] # SQL formatter options for routine files generated by sync [format] diff --git a/src/parser/compare.ts b/src/parser/compare.ts index 0477457..49dea26 100644 --- a/src/parser/compare.ts +++ b/src/parser/compare.ts @@ -264,6 +264,76 @@ export function grantsDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): bo return false; } +/** + * Compare two ParsedRoutine objects (e.g. file vs pg_dump output). + * Returns true if they differ functionally (ignoring formatting). + */ +export function parsedRoutinesDiffer(a: ParsedRoutine, b: ParsedRoutine, options?: DiffOptions): boolean { + if (a.type !== b.type) return true; + + // Parameters + if (a.parameters.length !== b.parameters.length) return true; + for (let i = 0; i < a.parameters.length; i++) { + if ((a.parameters[i].name ?? null) !== (b.parameters[i].name ?? null)) return true; + if (normalizeType(a.parameters[i].type) !== normalizeType(b.parameters[i].type)) return true; + } + + // Returns + if (parsedReturnsDiffer(a.returns, b.returns)) return true; + + // Body + if (bodyDiffers(a.body, b.body, options?.ignoreBodyWhitespace)) return true; + + // Attributes — normalize both to catalog form and compare + const attrsA = attributesToCatalog(a); + const attrsB = attributesToCatalog(b); + if (attrsA.language !== attrsB.language) return true; + if (attrsA.volatility !== attrsB.volatility) return true; + if (attrsA.strict !== attrsB.strict) return true; + if (attrsA.securityDefiner !== attrsB.securityDefiner) return true; + if (attrsA.parallel !== attrsB.parallel) return true; + if (attrsA.leakproof !== attrsB.leakproof) return true; + if (attrsA.cost !== attrsB.cost) return true; + if (attrsA.rows !== attrsB.rows) return true; + if (attrsA.config.length !== attrsB.config.length) return true; + for (let i = 0; i < attrsA.config.length; i++) { + if (attrsA.config[i] !== attrsB.config[i]) return true; + } + + // Comment + if ((a.comment ?? null) !== (b.comment ?? null)) return true; + + // Grants + if (a.grants.length !== b.grants.length) return true; + for (let i = 0; i < a.grants.length; i++) { + if (a.grants[i].privilege !== b.grants[i].privilege) return true; + if (a.grants[i].grantee !== b.grants[i].grantee) return true; + if (a.grants[i].isGrant !== b.grants[i].isGrant) return true; + } + + return false; +} + +function parsedReturnsDiffer(a: ParsedRoutine["returns"], b: ParsedRoutine["returns"]): boolean { + if (a == null && b == null) return false; + if (a == null || b == null) return true; + + if (a.setof !== b.setof) return true; + if (normalizeType(a.type ?? "") !== normalizeType(b.type ?? "")) return true; + + // TABLE columns + if ((a.table == null) !== (b.table == null)) return true; + if (a.table && b.table) { + if (a.table.length !== b.table.length) return true; + for (let i = 0; i < a.table.length; i++) { + if (a.table[i].name !== b.table[i].name) return true; + if (normalizeType(a.table[i].type) !== normalizeType(b.table[i].type)) return true; + } + } + + return false; +} + function returnsDiffer(parsed: ParsedRoutine, catalog: CatalogRoutine): boolean { const pr = parsed.returns; const cr = catalog.returns; diff --git a/src/parser/fix.ts b/src/parser/fix.ts index 9e0d96f..27da6a1 100644 --- a/src/parser/fix.ts +++ b/src/parser/fix.ts @@ -1,6 +1,6 @@ import type { ParsedRoutine } from "./routine.ts"; import { quoteIdent } from "./routine.ts"; -import { formatComment, type FormatOptions } from "./formatter.ts"; +import { formatComment, formatGrants, qualifiedName, type FormatOptions } from "./formatter.ts"; function escapeRegex(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -100,3 +100,124 @@ export function applyCommentFixes( return { content: result, count }; } + +/** + * Remove COMMENT ON statements for routines that have no comment in the database. + */ +export function removeComments( + content: string, + routines: ParsedRoutine[], +): { content: string; count: number } { + let result = content; + let count = 0; + + for (const routine of routines) { + const commentRe = buildCommentOnRegex(routine); + const before = result; + // Remove the COMMENT ON statement and any surrounding blank lines + result = result.replace(commentRe, ""); + // Clean up extra blank lines left behind + result = result.replace(/\n{3,}/g, "\n\n"); + if (result !== before) count++; + } + + return { content: result, count }; +} + +/** + * Build a regex that matches a routine's dollar-quoted body (AS $tag$...$tag$;). + */ +function buildBodyRegex(r: ParsedRoutine): RegExp { + const schema = r.schema + ? `(?:${escapeRegex(quoteIdent(r.schema, r.schemaQuoted ?? false))}|${escapeRegex(r.schema)})\\.` + : ""; + const name = `(?:${escapeRegex(quoteIdent(r.name, r.nameQuoted ?? false))}|${escapeRegex(r.name)})`; + // Match CREATE ... name( ... AS $tag$ ... $tag$; + return new RegExp( + `(\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\s+${schema}${name}\\s*\\([\\s\\S]*?\\bAS\\s+)(\\$[a-zA-Z_0-9]*\\$)([\\s\\S]*?)\\2(\\s*;)`, + "gi", + ); +} + +/** + * Apply body fixes to a file. Replaces the body content between dollar-quote tags. + */ +export function applyBodyFixes( + content: string, + fixes: { routine: ParsedRoutine; catalogBody: string }[], +): { content: string; count: number } { + let result = content; + let count = 0; + + for (const { routine, catalogBody } of fixes) { + const bodyRe = buildBodyRegex(routine); + const before = result; + result = result.replace(bodyRe, (_match, prefix, openTag, _oldBody, suffix) => { + return `${prefix}${openTag}${catalogBody}${openTag}${suffix}`; + }); + if (result !== before) count++; + } + + return { content: result, count }; +} + +/** + * Build a regex that matches GRANT/REVOKE statements for a routine. + */ +function buildGrantRevokeRegex(r: ParsedRoutine): RegExp { + const schema = r.schema + ? `(?:${escapeRegex(quoteIdent(r.schema, r.schemaQuoted ?? false))}|${escapeRegex(r.schema)})\\.` + : ""; + const name = `(?:${escapeRegex(quoteIdent(r.name, r.nameQuoted ?? false))}|${escapeRegex(r.name)})`; + return new RegExp( + `\\b(?:GRANT|REVOKE)\\s+(?:EXECUTE|ALL(?:\\s+PRIVILEGES)?)\\s+ON\\s+(?:FUNCTION|PROCEDURE)\\s+${schema}${name}\\s*\\([^)]*\\)\\s+(?:TO|FROM)\\s+[^;]+;[ \\t]*\\n?`, + "gi", + ); +} + +/** + * Apply grant fixes to a file. Replaces all GRANT/REVOKE statements for each routine. + */ +export function applyGrantFixes( + content: string, + fixes: { routine: ParsedRoutine; catalogGrants: ParsedRoutine["grants"] }[], + formatOpts: FormatOptions, +): { content: string; count: number } { + let result = content; + let count = 0; + + for (const { routine, catalogGrants } of fixes) { + // Remove existing GRANT/REVOKE statements + const grantRe = buildGrantRevokeRegex(routine); + const stripped = result.replace(grantRe, ""); + + // Format new grants + const withGrants: ParsedRoutine = { ...routine, grants: catalogGrants }; + const grantLines = formatGrants(withGrants, formatOpts); + + if (grantLines.length === 0 && stripped === result) continue; // no change + + if (grantLines.length > 0) { + // Insert after routine body end (or after COMMENT ON if present) + const commentRe = buildCommentOnRegex(routine); + const commentMatch = commentRe.exec(stripped); + const bodyEnd = findRoutineBodyEnd(stripped, routine); + + let insertPos: number; + if (commentMatch) { + insertPos = commentMatch.index + commentMatch[0].length; + } else if (bodyEnd !== -1) { + insertPos = bodyEnd; + } else { + continue; // can't find where to insert + } + + result = stripped.substring(0, insertPos) + "\n\n" + grantLines.join("\n") + stripped.substring(insertPos); + } else { + result = stripped; + } + count++; + } + + return { content: result, count }; +} From 834c89e740cef3732205fe9b5d4f459a417ae95b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sun, 15 Mar 2026 14:49:48 +0100 Subject: [PATCH 9/9] Add migration system with project_dir, TOML headers, history tracking, and resolver - Replace routines_dir + migrations_dir with single project_dir - Schema dump is now V000_schema.sql with interactive prompt in sync - New files get pgdev TOML header (type, version, run_before, rerun_with) - Header parser supports two formats: line comments (-- [pgdev]) and block comments (/* --- [pgdev] --- */) - File scanner classifies files as routine/versioned/repeatable by header, naming convention, or parser detection - Resolver computes execution plan: hash/version diff, rerun_with cascade (transitive), run_before topological sort - History module reads migration state from database comment or dedicated table - diff --script generates migration scripts using the full pipeline - Flexible file references: bare name, filename, relative path, version number - 91 new tests (473 total), all passing Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 96 ++++- src/cli.ts | 3 +- src/commands/config.ts | 34 +- src/commands/diff.ts | 216 +++++----- src/commands/sync.ts | 78 +++- src/config.ts | 67 +++- src/parser/header.ts | 248 ++++++++++++ src/parser/history.ts | 103 +++++ src/parser/parser-tests/header.test.ts | 421 ++++++++++++++++++++ src/parser/parser-tests/history.test.ts | 204 ++++++++++ src/parser/parser-tests/resolver.test.ts | 476 +++++++++++++++++++++++ src/parser/parser-tests/scanner.test.ts | 266 +++++++++++++ src/parser/resolver.ts | 260 +++++++++++++ src/parser/scanner.ts | 212 ++++++++++ 14 files changed, 2504 insertions(+), 180 deletions(-) create mode 100644 src/parser/header.ts create mode 100644 src/parser/history.ts create mode 100644 src/parser/parser-tests/header.test.ts create mode 100644 src/parser/parser-tests/history.test.ts create mode 100644 src/parser/parser-tests/resolver.test.ts create mode 100644 src/parser/parser-tests/scanner.test.ts create mode 100644 src/parser/resolver.ts create mode 100644 src/parser/scanner.ts diff --git a/README.md b/README.md index c2d4481..4013e83 100644 --- a/README.md +++ b/README.md @@ -39,16 +39,17 @@ Sections: - **NpgsqlRest** — detect or install NpgsqlRest (npm, bun, standalone binary, or Docker) - **PostgreSQL Tools** — detect or install psql, pg_dump, pg_restore (Homebrew, apt, apk, dnf) - **NpgsqlRest Config Files** — create and manage NpgsqlRest JSON config files (production, development, local) with a TUI editor for connection strings, config settings, and more -- **pgdev Environment** — configure env file, database connection, and project directories (migrations, routines, tests, schemas) +- **pgdev Environment** — configure env file, database connection, and project settings (project directory, tests, schemas) ### `pgdev sync` Extract database schema and routines into project files (DB → Files): -- Dumps the full schema to `migrations_dir/schema.sql` (DDL for tables, types, etc.) -- Extracts each routine (function, procedure, or other configured types) into individual `.sql` files in `routines_dir` +- Dumps the full schema to `project_dir/V000_schema.sql` (DDL for tables, types, etc.) — prompted separately in interactive mode +- Extracts each routine (function, procedure, or other configured types) into individual `.sql` files in `project_dir` - Applies configurable formatting to new files (see `[format]` options) - Organizes files into subdirectories based on `group_order` (by API type, schema, name segment, or object kind) +- New files include a pgdev TOML header with migration metadata (`type`, `version`, `run_before`, `rerun_with`) - Supports `VIEW` extraction when added to `routine_types` - **Interactive by default** — shows each change and prompts before writing: - `Y` (default) — apply this change @@ -74,7 +75,7 @@ Note: `--format` cannot be combined with `--comments`/`--grants`/`--definitions` Compare project SQL files against the live database (read-only): -- Parses all `.sql` files in `routines_dir` and fetches routine metadata from `pg_catalog` +- Parses all `.sql` files in `project_dir` and fetches routine metadata from `pg_catalog` - Reports routines that need creating, updating, or dropping - Compares definition (parameters, return type, body, attributes), comments, and optionally grants - Supports `ignore_body_whitespace` for whitespace-insensitive body comparison @@ -82,7 +83,70 @@ Compare project SQL files against the live database (read-only): | Flag | Description | |------|-------------| -| `--script [file]` | Generate a SQL migration script (procedural `DO` block) for all differences. Optionally specify output file path; defaults to a temp file. | +| `--script [file]` | Generate a SQL migration script based on the full migration plan. Scans all project files, checks history, resolves dependencies, and produces a procedural `DO` block. Optionally specify output file path; defaults to a temp file. | + +### Migration System + +pgdev includes a file-based migration system that tracks three types of SQL files in `project_dir`: + +| Type | Naming Convention | Behavior | +|------|------------------|----------| +| **Routine** | `*.sql` with valid routine content | Synced from DB, executed when content hash changes | +| **Versioned** | `V__.sql` | Execute once per version number | +| **Repeatable** | `R__.sql` | Execute once per content hash change | + +#### File Classification + +Files are classified by priority: + +1. **TOML header** — explicit `type` or `version` in the pgdev header overrides everything +2. **Naming convention** — filename prefix (`V`/`R` + separator) determines type +3. **Parser detection** — files containing valid routine definitions are classified as routines +4. **Unrecognized** — warning issued, file skipped + +#### TOML Header + +SQL files can include a pgdev metadata header at the top of the file. Two formats are supported: + +**Format 1** — line comments: +```sql +-- [pgdev] +-- type = "routine" +-- run_before = "R__create_views" +``` + +**Format 2** — block comment with `---` delimiters: +```sql +/* +--- +[pgdev] +type = "routine" +# version = "" +# run_before = "" +# rerun_with = [] +--- +*/ +``` + +| Field | Type | Description | +|-------|------|-------------| +| `type` | `"routine"` \| `"repeatable"` \| `"versioned"` | Overrides naming convention | +| `version` | `string` | Version number (implies `type = "versioned"`) | +| `run_before` | `string` | Execute this file before the referenced file | +| `rerun_with` | `string` \| `string[]` | Re-execute this file whenever any referenced file executes, even if unchanged | + +**File references** in `run_before` and `rerun_with` support flexible formats: +- Bare name: `schema` (stripped of prefix and extension) +- Filename: `V000_schema.sql` or `V000_schema` +- Relative path: `test/V000_schema.sql`, `./test/V000_schema.sql`, `/test/V000_schema.sql` +- Version number: `000` (for versioned migrations) + +#### History Tracking + +Migration history is tracked in one of two modes: + +- **Comment mode** (default) — stores JSON in `COMMENT ON DATABASE`, scoped by `project_name`. Zero database footprint. +- **Table mode** — stores history in a dedicated table per project. ### `pgdev exec ` @@ -172,8 +236,8 @@ password = "{PGPASSWORD}" # Project directories and settings [project] -routines_dir = "" -migrations_dir = "" +project_dir = "" +project_name = "" tests_dir = "" schemas = [] grants = false @@ -185,6 +249,12 @@ group_segment = 0 skip_prefixes = [] group_order = [] sync_skip = [] +up_prefix = "V" +repeatable_prefix = "R" +separator = "__" +history_mode = "comment" +history_schema = "pgdev" +history_table = "" # SQL formatting options (applied during sync) [format] @@ -260,12 +330,12 @@ Database connection for pgdev tools. Two modes: ### `[project]` -Project directories and sync/diff settings. +Project directory and sync/diff/migration settings. | Key | Default | Description | |-----|---------|-------------| -| `routines_dir` | `""` | Directory for extracted SQL routines | -| `migrations_dir` | `""` | Directory for migration scripts (schema.sql is written here) | +| `project_dir` | `""` | Directory for all project SQL files (routines, schema, migrations) | +| `project_name` | `""` | Project name — scopes migration history; required when `history_mode = "comment"` | | `tests_dir` | `""` | Directory for SQL test files | | `schemas` | `[]` | Schemas to include (empty = all non-system schemas) | | `grants` | `false` | Include GRANT/REVOKE statements in sync and diff | @@ -277,6 +347,12 @@ Project directories and sync/diff settings. | `skip_prefixes` | `[]` | Prefixes to skip when extracting group segment (e.g. `["get", "set", "delete"]`). Uses built-in defaults when empty | | `group_order` | `[]` | Directory nesting order. Available dimensions: `"type"`, `"schema"`, `"name"`, `"kind"`. Empty = flat directory | | `sync_skip` | `[]` | Files to skip during sync (relative paths, managed via interactive sync's "Never" option) | +| `up_prefix` | `"V"` | Filename prefix for versioned (up) migrations | +| `repeatable_prefix` | `"R"` | Filename prefix for repeatable migrations | +| `separator` | `"__"` | Separator between prefix/version and name in migration filenames | +| `history_mode` | `"comment"` | Migration history tracking: `"comment"` (database comment) or `"table"` (dedicated table) | +| `history_schema` | `"pgdev"` | Schema for history table (table mode only) | +| `history_table` | `""` | Table name for history (table mode only, defaults to `"{project_name}_history"`) | **Directory grouping dimensions:** diff --git a/src/cli.ts b/src/cli.ts index d14443c..97dfafa 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -248,8 +248,7 @@ async function printStatus(): Promise { // Project directories const dirs = [ - { label: "routines", path: config.project.routines_dir }, - { label: "migrations", path: config.project.migrations_dir }, + { label: "project", path: config.project.project_dir }, { label: "tests", path: config.project.tests_dir }, ]; console.log(); diff --git a/src/commands/config.ts b/src/commands/config.ts index 604fd51..83ade91 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -1999,9 +1999,6 @@ function validateProjectDir( try { const stat = statSync(abs); if (!stat.isDirectory()) return `"${dir}" exists but is not a directory`; - // If existing, must be empty - const entries = readdirSync(abs); - if (entries.length > 0) return `"${dir}" is not empty`; } catch { // Doesn't exist yet — that's fine } @@ -2017,7 +2014,7 @@ function validateProjectDir( } // Can't overlap with other project dirs - const PROJECT_KEYS = ["routines_dir", "migrations_dir", "tests_dir"] as const; + const PROJECT_KEYS = ["project_dir", "tests_dir"] as const; for (const otherKey of PROJECT_KEYS) { if (otherKey === key) continue; const otherDir = config.project[otherKey]; @@ -2030,7 +2027,7 @@ function validateProjectDir( } async function handleProjectDir( - key: "routines_dir" | "migrations_dir" | "tests_dir", + key: "project_dir" | "tests_dir", label: string, config: PgdevConfig, ): Promise { @@ -2074,7 +2071,7 @@ function projectDirStatus(value: string): string { } function projectStatus(config: PgdevConfig): string { - const set = [config.project.routines_dir, config.project.migrations_dir, config.project.tests_dir].filter(Boolean); + const set = [config.project.project_dir, config.project.tests_dir].filter(Boolean); if (set.length === 0) return "not configured"; return `${set.length} dir${set.length > 1 ? "s" : ""} configured`; } @@ -2116,16 +2113,10 @@ async function editProjectDirectories(config: PgdevConfig): Promise { title: "", items: [ { - key: "routines_dir", - label: "Routines directory", - value: projectDirStatus(currentConfig.project.routines_dir), - help: "Directory for SQL files containing PostgreSQL functions and procedures.\nThese define the REST API surface exposed by NpgsqlRest.", - }, - { - key: "migrations_dir", - label: "Migrations directory", - value: projectDirStatus(currentConfig.project.migrations_dir), - help: "Directory for versioned migration SQL scripts.\nSupports up/down, repeatable before/after, ordering by convention or config.", + key: "project_dir", + label: "Project directory", + value: projectDirStatus(currentConfig.project.project_dir), + help: "Directory for SQL source files: routines, schema, and versioned migrations.\nRoutines are organized into subdirectories by group_order.\nSchema is stored as V000_schema.sql in the root.", }, { key: "tests_dir", @@ -2146,10 +2137,9 @@ async function editProjectDirectories(config: PgdevConfig): Promise { if (choice.type === "item") { lastSelected = choice.key; - const key = choice.key as "routines_dir" | "migrations_dir" | "tests_dir"; + const key = choice.key as "project_dir" | "tests_dir"; const labels: Record = { - routines_dir: "Routines directory", - migrations_dir: "Migrations directory", + project_dir: "Project directory", tests_dir: "Tests directory", }; lastStatus = await handleProjectDir(key, labels[key], currentConfig); @@ -2231,13 +2221,13 @@ export async function configCommand(config: PgdevConfig): Promise { key: "api_dir", label: "API routines dir", value: currentConfig.project.api_dir || pc.dim("(none)"), - help: "Subdirectory within routines_dir for API (HTTP endpoint) routines.\nA routine is an API routine if its comment contains HTTP at the start or start of a line.\nLeave empty to place all routines directly in routines_dir.", + help: "Subdirectory within project_dir for API (HTTP endpoint) routines.\nA routine is an API routine if its comment contains HTTP at the start or start of a line.\nLeave empty to place all routines directly in project_dir.", }, { key: "internal_dir", label: "Internal routines dir", value: currentConfig.project.internal_dir || pc.dim("(none)"), - help: "Subdirectory within routines_dir for internal (non-API) routines.\nLeave empty to place all routines directly in routines_dir.", + help: "Subdirectory within project_dir for internal (non-API) routines.\nLeave empty to place all routines directly in project_dir.", }, { key: "group_segment", @@ -2261,7 +2251,7 @@ export async function configCommand(config: PgdevConfig): Promise { key: "group_order", label: "Group order", value: currentConfig.project.group_order.length > 0 ? currentConfig.project.group_order.join(", ") : pc.dim("flat"), - help: "Directory nesting order. Each element adds a subdirectory level.\nAvailable: type (api/internal), schema, name (name segment), kind (function/procedure).\nExample: type, schema, name → api/myschema/auth/routine.sql\nEmpty = flat (all files in routines_dir).", + help: "Directory nesting order. Each element adds a subdirectory level.\nAvailable: type (api/internal), schema, name (name segment), kind (function/procedure).\nExample: type, schema, name → api/myschema/auth/routine.sql\nEmpty = flat (all files in project_dir).", }, ], }, diff --git a/src/commands/diff.ts b/src/commands/diff.ts index cc1c60e..cad038c 100644 --- a/src/commands/diff.ts +++ b/src/commands/diff.ts @@ -7,7 +7,10 @@ import { findSqlFiles } from "../utils/files.ts"; import { parseRoutines, type ParsedRoutine } from "../parser/routine.ts"; import { fetchCatalogMetadata, type CatalogRoutine } from "../parser/catalog.ts"; import { routinesDiffer, commentsDiffer, grantsDiffer, type DiffOptions } from "../parser/compare.ts"; -import { formatRoutine, formatComment, formatGrants, qualifiedName, configToFormatOptions } from "../parser/formatter.ts"; +import { scanProjectFiles } from "../parser/scanner.ts"; +import { fetchHistory } from "../parser/history.ts"; +import { resolveExecutionPlan } from "../parser/resolver.ts"; +import { stripPgdevHeader } from "../parser/header.ts"; export interface DiffFlags { script: boolean; @@ -41,17 +44,11 @@ function catalogDisplayKey(r: CatalogRoutine): string { return `${r.schema}.${r.name}(${params.join(", ")})`; } -/** Build qualified name for DROP statements from catalog routine. */ -function catalogQualifiedSig(r: CatalogRoutine): string { - const params = r.parameters.map((p) => p.type).join(", "); - return `${r.schema}.${r.name}(${params})`; -} - export async function diffCommand(config: PgdevConfig, flags?: DiffFlags): Promise { - const { routines_dir, schemas, grants, ignore_body_whitespace } = config.project; + const { project_dir, schemas, grants, ignore_body_whitespace } = config.project; - if (!routines_dir) { - console.error(pc.red("routines_dir is not configured. Run pgdev config to set it.")); + if (!project_dir) { + console.error(pc.red("project_dir is not configured. Run pgdev config to set it.")); process.exit(1); } @@ -60,11 +57,11 @@ export async function diffCommand(config: PgdevConfig, flags?: DiffFlags): Promi process.exit(1); } - const fullDir = resolve(process.cwd(), routines_dir); + const fullDir = resolve(process.cwd(), project_dir); let isDir = false; try { isDir = statSync(fullDir).isDirectory(); } catch {} if (!isDir) { - console.error(pc.red(`Routines directory not found: ${routines_dir}`)); + console.error(pc.red(`Project directory not found: ${project_dir}`)); process.exit(1); } @@ -73,7 +70,7 @@ export async function diffCommand(config: PgdevConfig, flags?: DiffFlags): Promi const sqlFiles = findSqlFiles(fullDir); if (sqlFiles.length === 0) { s.stop(); - console.log(pc.yellow("No .sql files found in " + routines_dir)); + console.log(pc.yellow("No .sql files found in " + project_dir)); return; } @@ -216,112 +213,107 @@ export async function diffCommand(config: PgdevConfig, flags?: DiffFlags): Promi // Generate migration script if (flags?.script) { - const formatOpts = configToFormatOptions(config.format); - const date = new Date(); - const ident = date.toISOString().replace(/[-:.ZT]/g, ""); - const tag = `$migration_${ident}$`; - const lines: string[] = []; - let migrationIdx = 0; - - lines.push("do"); - lines.push(tag); - lines.push("declare ___clock timestamp with time zone;"); - lines.push("begin"); - lines.push("--"); - lines.push("-- Migration file generated by pgdev"); - lines.push(`-- Date: ${date.toISOString()}`); - lines.push("--"); - lines.push(""); + await generateMigrationScript(config, fullDir, flags); + } +} - // Create new routines - for (const { file, routine } of needCreating) { - migrationIdx++; - const display = parsedDisplayKey(routine, defaultSchema); - lines.push("--"); - lines.push(`-- Migration ${migrationIdx}`); - lines.push(`-- Script: ${file}`); - lines.push(`-- Type: CREATE`); - lines.push("--"); - lines.push("___clock = clock_timestamp();"); - lines.push(`-- Migration ${migrationIdx} start`); - lines.push(formatRoutine(routine, formatOpts)); - lines.push(`-- Migration ${migrationIdx} end`); - lines.push(`raise info 'Migration ${migrationIdx}: CREATE ${display} completed in % (${file})', clock_timestamp() - ___clock;`); - lines.push(""); - } +/** + * Generate a migration script based on the scanner/resolver pipeline. + * Scans all project files, checks history, resolves execution order, + * and generates a DO block script. + */ +async function generateMigrationScript(config: PgdevConfig, projectDir: string, flags: DiffFlags): Promise { + const s2 = spinner("Scanning project files..."); + + const scanResult = scanProjectFiles(projectDir, { + upPrefix: config.project.up_prefix, + repeatablePrefix: config.project.repeatable_prefix, + separator: config.project.separator, + }); + + // Show scan warnings + for (const w of scanResult.warnings) { + console.log(` ${pc.yellow("!")} ${w.file}: ${pc.dim(w.message)}`); + } - // Update changed routines - for (const { file, changes, routine } of needUpdating) { - migrationIdx++; - const display = parsedDisplayKey(routine, defaultSchema); - lines.push("--"); - lines.push(`-- Migration ${migrationIdx}`); - lines.push(`-- Script: ${file}`); - lines.push(`-- Type: UPDATE (${changes.join(", ")})`); - lines.push("--"); - lines.push("___clock = clock_timestamp();"); - lines.push(`-- Migration ${migrationIdx} start`); - - if (changes.includes("definition")) { - lines.push(formatRoutine(routine, { ...formatOpts, createOrReplace: true })); - } + s2.update("Fetching migration history..."); - if (changes.includes("comment")) { - const commentSql = formatComment(routine, formatOpts); - if (commentSql) { - lines.push(commentSql); - } else { - // File has no comment — remove from database - const kw = (w: string) => formatOpts.lowercase ? w.toLowerCase() : w; - const typeKw = kw(routine.type === "function" ? "FUNCTION" : "PROCEDURE"); - const qn = qualifiedName(routine); - const sig = routine.parameters.map((p) => formatOpts.lowercase ? p.type.toLowerCase() : p.type).join(", "); - lines.push(`${kw("COMMENT ON")} ${typeKw} ${qn}(${sig}) ${kw("IS")} NULL;`); - } - lines.push(""); - } + const histResult = await fetchHistory(config); + if (!histResult.ok) { + s2.stop(); + console.error(pc.red(histResult.error)); + return; + } - if (changes.includes("grants")) { - const grantSql = formatGrants(routine, formatOpts); - if (grantSql.length > 0) { - lines.push(grantSql.join("\n")); - lines.push(""); - } - } + s2.stop(); - lines.push(`-- Migration ${migrationIdx} end`); - lines.push(`raise info 'Migration ${migrationIdx}: UPDATE ${display} (${changes.join(", ")}) completed in % (${file})', clock_timestamp() - ___clock;`); - lines.push(""); - } + const plan = resolveExecutionPlan(scanResult.files, histResult.entries); - // Drop routines only in database - for (const { catalog: cat } of needDropping) { - migrationIdx++; - const typeKw = formatOpts.lowercase ? cat.type : cat.type.toUpperCase(); - const sig = catalogQualifiedSig(cat); - const dropKw = formatOpts.lowercase ? "drop" : "DROP"; - const ifExistsKw = formatOpts.lowercase ? "if exists" : "IF EXISTS"; - const display = `${cat.schema}.${cat.name}(${cat.parameters.map((p) => p.type).join(", ")})`; - - lines.push("--"); - lines.push(`-- Migration ${migrationIdx}`); - lines.push(`-- Type: DROP`); - lines.push("--"); - lines.push("___clock = clock_timestamp();"); - lines.push(`-- Migration ${migrationIdx} start`); - lines.push(`${dropKw} ${typeKw} ${ifExistsKw} ${sig};`); - lines.push(`-- Migration ${migrationIdx} end`); - lines.push(`raise info 'Migration ${migrationIdx}: DROP ${display} completed in %', clock_timestamp() - ___clock;`); - lines.push(""); - } + // Show resolver warnings + for (const w of plan.warnings) { + console.log(` ${pc.yellow("!")} ${w.file}: ${pc.dim(w.message)}`); + } + + if (plan.files.length === 0) { + console.log(pc.dim("No migration script generated — nothing to execute.")); + return; + } - lines.push("end;"); - lines.push(`${tag};`); + // Report what will be in the script + console.log(`\n${pc.bold(`Migration plan (${plan.files.length} file${plan.files.length > 1 ? "s" : ""}):`)}`) + for (const f of plan.files) { + const typeTag = f.type === "versioned" ? pc.cyan(`v${f.version}`) : + f.type === "repeatable" ? pc.magenta("repeatable") : + pc.blue("routine"); + const reasonTag = f.reason === "new" ? pc.green("new") : + f.reason === "changed" ? pc.yellow("changed") : + pc.dim("cascade"); + console.log(` ${typeTag} ${f.relPath} ${reasonTag}`); + } + + // Generate DO block script + const date = new Date(); + const ident = date.toISOString().replace(/[-:.ZT]/g, ""); + const tag = `$migration_${ident}$`; + const lines: string[] = []; + let migrationIdx = 0; + + lines.push("do"); + lines.push(tag); + lines.push("declare ___clock timestamp with time zone;"); + lines.push("begin"); + lines.push("--"); + lines.push("-- Migration file generated by pgdev"); + lines.push(`-- Date: ${date.toISOString()}`); + lines.push("--"); + lines.push(""); + + for (const file of plan.files) { + migrationIdx++; + const sql = stripPgdevHeader(file.content).trim(); + const typeLabel = file.type === "versioned" ? `VERSIONED (v${file.version})` : + file.type === "repeatable" ? "REPEATABLE" : "ROUTINE"; - const scriptFile = flags.scriptFile - ? resolve(process.cwd(), flags.scriptFile) - : resolve(tmpdir(), `migration_${ident}.sql`); - await Bun.write(scriptFile, lines.join("\n") + "\n"); - console.log(`\n${pc.bold("Migration script:")} ${scriptFile}`); + lines.push("--"); + lines.push(`-- Migration ${migrationIdx}`); + lines.push(`-- Script: ${file.relPath}`); + lines.push(`-- Type: ${typeLabel}`); + lines.push(`-- Reason: ${file.reason}`); + lines.push("--"); + lines.push("___clock = clock_timestamp();"); + lines.push(`-- Migration ${migrationIdx} start`); + lines.push(sql); + lines.push(`-- Migration ${migrationIdx} end`); + lines.push(`raise info 'Migration ${migrationIdx}: ${typeLabel} ${file.relPath} completed in % (${file.reason})', clock_timestamp() - ___clock;`); + lines.push(""); } + + lines.push("end;"); + lines.push(`${tag};`); + + const scriptFile = flags.scriptFile + ? resolve(process.cwd(), flags.scriptFile) + : resolve(tmpdir(), `migration_${ident}.sql`); + await Bun.write(scriptFile, lines.join("\n") + "\n"); + console.log(`\n${pc.bold("Migration script:")} ${scriptFile}`); } diff --git a/src/commands/sync.ts b/src/commands/sync.ts index de511e3..d9426f8 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -14,6 +14,32 @@ import { applyCommentFixes, applyBodyFixes, applyGrantFixes, removeComments } fr import type { ParsedRoutine } from "../parser/routine.ts"; import { bodyHash } from "../parser/catalog.ts"; +/** Generate the default pgdev TOML header block for new files. */ +function pgdevHeader(type: "routine" | "versioned", version?: string): string { + const typeValue = version ? "versioned" : type; + const versionLine = version + ? `version = "${version}"` + : `# version = ""`; + return `/* +--- +[pgdev] +# Migration type: "routine" or "repeatable" or "versioned" +# For versioned, set version instead (implies versioned automatically) +type = "${typeValue}" + +# Version number (implies type = "versioned"), e.g. version = "0001" +${versionLine} + +# Execute this file before the referenced file in the migration script +# run_before = "" + +# Re-execute this file whenever any of the referenced files are executed, even if unchanged +# rerun_with = [] +--- +*/ +`; +} + type SyncAction = "yes" | "no" | "never" | "all" | "all-create" | "all-update" | "quit"; /** @@ -126,10 +152,10 @@ export function parseRoutineGroups( * by comparing parsed routines against the database catalog. */ async function selectiveSync(config: PgdevConfig, flags: SyncFlags): Promise { - const { routines_dir, schemas, grants } = config.project; + const { project_dir, schemas, grants } = config.project; - if (!routines_dir) { - console.error(error("No routines_dir configured. Run pgdev config to set it up.")); + if (!project_dir) { + console.error(error("No project_dir configured. Run pgdev config to set it up.")); process.exit(1); } @@ -138,15 +164,15 @@ async function selectiveSync(config: PgdevConfig, flags: SyncFlags): Promise 0) parts.push(`${unchanged} unchanged`); if (skipped > 0) parts.push(pc.dim(`${skipped} skipped`)); if (parts.length > 0) { - console.log(success(`Routines in ${pc.bold(routinesDir + "/")}: ${parts.join(", ")}`)); + console.log(success(`Routines in ${pc.bold(projectDir + "/")}: ${parts.join(", ")}`)); } } finally { try { unlinkSync(routineTocFile); } catch {} diff --git a/src/config.ts b/src/config.ts index 47d561a..75bee01 100644 --- a/src/config.ts +++ b/src/config.ts @@ -26,13 +26,13 @@ export interface CommandsConfig { export type GroupDimension = "type" | "schema" | "name" | "kind"; export interface ProjectConfig { - routines_dir: string; - migrations_dir: string; + project_dir: string; + project_name: string; tests_dir: string; schemas: string[]; grants: boolean; ignore_body_whitespace: boolean; - /** Object types to extract into individual files (excluded from schema.sql) */ + /** Object types to extract into individual files (excluded from V000_schema.sql) */ routine_types: string[]; api_dir: string; internal_dir: string; @@ -42,6 +42,18 @@ export interface ProjectConfig { group_order: GroupDimension[]; /** Files to skip during sync (relative paths, set via "Never" in interactive mode) */ sync_skip: string[]; + /** Migration file prefix for versioned (up) migrations */ + up_prefix: string; + /** Migration file prefix for repeatable migrations */ + repeatable_prefix: string; + /** Separator between prefix/version and name in migration filenames */ + separator: string; + /** History tracking mode */ + history_mode: "comment" | "table"; + /** Schema for history table (table mode only) */ + history_schema: string; + /** Table name for history (table mode only, defaults to "{project_name}_history") */ + history_table: string; } export interface FormatConfig { @@ -90,8 +102,8 @@ const defaults: PgdevConfig = { connection_name: "Default", }, project: { - routines_dir: "", - migrations_dir: "", + project_dir: "", + project_name: "", tests_dir: "", schemas: [], grants: false, @@ -103,6 +115,12 @@ const defaults: PgdevConfig = { skip_prefixes: [], group_order: [], sync_skip: [], + up_prefix: "V", + repeatable_prefix: "R", + separator: "__", + history_mode: "comment", + history_schema: "pgdev", + history_table: "", }, format: { lowercase: true, @@ -414,19 +432,25 @@ const EXPECTED_KEYS: { section: string; key: string; raw: string }[] = [ // [commands] { section: "commands", key: "schemas_query", raw: `schemas_query = "${defaults.commands.schemas_query}"` }, // [project] - { section: "project", key: "routines_dir", raw: 'routines_dir = ""' }, - { section: "project", key: "migrations_dir", raw: 'migrations_dir = ""' }, + { section: "project", key: "project_dir", raw: 'project_dir = ""' }, + { section: "project", key: "project_name", raw: '# Project name — scopes migration history; required when history_mode = "comment"\nproject_name = ""' }, { section: "project", key: "tests_dir", raw: 'tests_dir = ""' }, { section: "project", key: "schemas", raw: "schemas = []" }, { section: "project", key: "grants", raw: "# Track GRANT/REVOKE statements for routines\ngrants = false" }, { section: "project", key: "ignore_body_whitespace", raw: "# Ignore whitespace differences in routine bodies when comparing\nignore_body_whitespace = false" }, - { section: "project", key: "api_dir", raw: "# Subdirectory within routines_dir for API (HTTP endpoint) routines\napi_dir = \"\"" }, - { section: "project", key: "internal_dir", raw: "# Subdirectory within routines_dir for internal (non-API) routines\ninternal_dir = \"\"" }, + { section: "project", key: "api_dir", raw: "# Subdirectory within project_dir for API (HTTP endpoint) routines\napi_dir = \"\"" }, + { section: "project", key: "internal_dir", raw: "# Subdirectory within project_dir for internal (non-API) routines\ninternal_dir = \"\"" }, { section: "project", key: "group_segment", raw: "# Group routines into subdirs by name segment (0 = disabled, 1 = first segment)\ngroup_segment = 0" }, { section: "project", key: "skip_prefixes", raw: "# Prefixes to skip when grouping by name segment (empty = use built-in defaults)\n# skip_prefixes = [\"get\", \"set\", \"delete\", \"insert\", \"update\", \"create\", \"remove\", \"find\", \"list\", \"is\", \"has\", \"check\", \"count\", \"compute\", \"run\", \"do\", \"send\"]\nskip_prefixes = []" }, - { section: "project", key: "routine_types", raw: "# Object types to extract into individual files (excluded from schema.sql)\nroutine_types = [\"FUNCTION\", \"PROCEDURE\"]" }, + { section: "project", key: "routine_types", raw: "# Object types to extract into individual files (excluded from V000_schema.sql)\nroutine_types = [\"FUNCTION\", \"PROCEDURE\"]" }, { section: "project", key: "group_order", raw: "# Directory nesting order. Each element adds a subdirectory level.\n# Available: \"type\" (api/internal), \"schema\", \"name\" (name segment), \"kind\" (function/procedure)\n# Example: [\"type\", \"schema\", \"name\"] → api/myschema/auth/get_auth_login.sql\ngroup_order = []" }, { section: "project", key: "sync_skip", raw: "# Files to skip during sync (relative paths, managed via interactive sync)\nsync_skip = []" }, + { section: "project", key: "up_prefix", raw: '# Filename prefix for versioned (up) migrations, e.g. V001__schema.sql\nup_prefix = "V"' }, + { section: "project", key: "repeatable_prefix", raw: '# Filename prefix for repeatable migrations, e.g. R__seed_data.sql\nrepeatable_prefix = "R"' }, + { section: "project", key: "separator", raw: '# Separator between prefix/version and name in migration filenames\nseparator = "__"' }, + { section: "project", key: "history_mode", raw: '# Migration history tracking: "comment" (database comment) or "table" (dedicated table)\nhistory_mode = "comment"' }, + { section: "project", key: "history_schema", raw: '# Schema for history table (table mode only)\nhistory_schema = "pgdev"' }, + { section: "project", key: "history_table", raw: '# Table name for history (table mode only, defaults to "{project_name}_history")\nhistory_table = ""' }, // [format] { section: "format", key: "lowercase", raw: "# Lowercase SQL keywords in formatted output\nlowercase = true" }, { section: "format", key: "param_style", raw: '# Parameter layout: "inline" or "multiline"\nparam_style = "multiline"' }, @@ -564,8 +588,9 @@ password = "{PGPASSWORD}" # Leave empty to skip; directories are created when first needed [project] -routines_dir = "" -migrations_dir = "" +project_dir = "" +# Project name — scopes migration history; required when history_mode = "comment" +project_name = "" tests_dir = "" # Schemas used by this project (empty = all non-system schemas) schemas = [] @@ -573,16 +598,16 @@ schemas = [] grants = false # Ignore whitespace differences in routine bodies when comparing ignore_body_whitespace = false -# Subdirectory within routines_dir for API (HTTP endpoint) routines +# Subdirectory within project_dir for API (HTTP endpoint) routines api_dir = "" -# Subdirectory within routines_dir for internal (non-API) routines +# Subdirectory within project_dir for internal (non-API) routines internal_dir = "" # Group routines into subdirs by name segment (0 = disabled, 1 = first segment) group_segment = 0 # Prefixes to skip when grouping by name segment (empty = use built-in defaults) # skip_prefixes = ["get", "set", "delete", "insert", "update", "create", "remove", "find", "list", "is", "has", "check", "count", "compute", "run", "do", "send"] skip_prefixes = [] -# Object types to extract into individual files (excluded from schema.sql) +# Object types to extract into individual files (excluded from V000_schema.sql) routine_types = ["FUNCTION", "PROCEDURE"] # Directory nesting order. Each element adds a subdirectory level. # Available: "type" (api/internal), "schema", "name" (name segment), "kind" (function/procedure) @@ -590,6 +615,18 @@ routine_types = ["FUNCTION", "PROCEDURE"] group_order = [] # Files to skip during sync (relative paths, managed via interactive sync) sync_skip = [] +# Filename prefix for versioned (up) migrations, e.g. V001__schema.sql +up_prefix = "V" +# Filename prefix for repeatable migrations, e.g. R__seed_data.sql +repeatable_prefix = "R" +# Separator between prefix/version and name in migration filenames +separator = "__" +# Migration history tracking: "comment" (database comment) or "table" (dedicated table) +history_mode = "comment" +# Schema for history table (table mode only) +history_schema = "pgdev" +# Table name for history (table mode only, defaults to "{project_name}_history") +history_table = "" # SQL formatter options for routine files generated by sync [format] diff --git a/src/parser/header.ts b/src/parser/header.ts new file mode 100644 index 0000000..3fde621 --- /dev/null +++ b/src/parser/header.ts @@ -0,0 +1,248 @@ +/** + * Parse pgdev TOML headers from SQL files. + * + * Supports two formats at the top of file: + * + * Format 1 — line comments: + * -- [pgdev] + * -- type = "routine" + * -- run_before = "R__create_views" + * + * Format 2 — block comment with --- delimiters: + * /* + * --- + * [pgdev] + * type = "routine" + * --- + * *​/ + */ + +export interface PgdevHeader { + type?: "routine" | "repeatable" | "versioned"; + version?: string; + run_before?: string; + rerun_with?: string[]; +} + +/** + * Parse the pgdev TOML header from the top of a SQL file. + * Returns null if no header is found. + */ +export function parsePgdevHeader(content: string): PgdevHeader | null { + const trimmed = content.trimStart(); + + // Try Format 2 first (block comment with --- delimiters) + const format2 = parseFormat2(trimmed); + if (format2 !== null) return format2; + + // Try Format 1 (line comments) + const format1 = parseFormat1(trimmed); + if (format1 !== null) return format1; + + return null; +} + +/** + * Format 1: line comments starting with -- [pgdev] + * + * -- [pgdev] + * -- key = "value" + * -- key2 = "value2" + */ +function parseFormat1(content: string): PgdevHeader | null { + const lines = content.split("\n"); + + // Find -- [pgdev] line at the top (allow leading blank lines/comments) + let startIdx = -1; + for (let i = 0; i < lines.length; i++) { + const stripped = lines[i].trim(); + if (!stripped || (stripped.startsWith("--") && !stripped.includes("[pgdev]"))) continue; + if (/^--\s*\[pgdev\]\s*$/.test(stripped)) { + startIdx = i; + break; + } + break; // non-comment, non-blank line — stop looking + } + + if (startIdx === -1) return null; + + // Collect subsequent -- lines as TOML content + const tomlLines: string[] = ["[pgdev]"]; + for (let i = startIdx + 1; i < lines.length; i++) { + const stripped = lines[i].trim(); + if (stripped.startsWith("--")) { + // Remove the -- prefix and optional leading space + const tomlLine = stripped.replace(/^--\s?/, ""); + tomlLines.push(tomlLine); + } else { + break; + } + } + + return parseTomlBlock(tomlLines.join("\n")); +} + +/** + * Format 2: block comment with --- delimiters + * + * /* + * --- + * [pgdev] + * key = "value" + * --- + * *​/ + * + * Or with content before the --- delimiter: + * /* + * regular comment + * --- + * [pgdev] + * key = "value" + * --- + * *​/ + */ +function parseFormat2(content: string): PgdevHeader | null { + // Must start with /* (allowing whitespace) + if (!content.startsWith("/*")) return null; + + // Find the closing */ + const closeIdx = content.indexOf("*/"); + if (closeIdx === -1) return null; + + const block = content.slice(2, closeIdx); + const lines = block.split("\n").map((l) => l.trim()); + + // Find --- delimited section containing [pgdev] + let sectionStart = -1; + let sectionEnd = -1; + for (let i = 0; i < lines.length; i++) { + if (lines[i] === "---") { + if (sectionStart === -1) { + sectionStart = i; + } else { + sectionEnd = i; + break; + } + } + } + + if (sectionStart === -1 || sectionEnd === -1) return null; + + const sectionLines = lines.slice(sectionStart + 1, sectionEnd); + const sectionText = sectionLines.join("\n"); + + // Must contain [pgdev] + if (!sectionText.includes("[pgdev]")) return null; + + return parseTomlBlock(sectionText); +} + +/** + * Parse a TOML block and extract pgdev header fields. + */ +function parseTomlBlock(toml: string): PgdevHeader | null { + let parsed: Record; + try { + parsed = Bun.TOML.parse(toml) as Record; + } catch { + return null; + } + + const pgdev = parsed.pgdev as Record | undefined; + if (!pgdev) return null; + + const header: PgdevHeader = {}; + + if (typeof pgdev.type === "string") { + if (pgdev.type === "routine" || pgdev.type === "repeatable" || pgdev.type === "versioned") { + header.type = pgdev.type; + } + } + + if (typeof pgdev.version === "string" && pgdev.version !== "") { + header.version = pgdev.version; + } + + if (typeof pgdev.run_before === "string" && pgdev.run_before !== "") { + header.run_before = pgdev.run_before; + } + + if (pgdev.rerun_with != null) { + if (typeof pgdev.rerun_with === "string") { + header.rerun_with = pgdev.rerun_with ? [pgdev.rerun_with] : []; + } else if (Array.isArray(pgdev.rerun_with)) { + header.rerun_with = pgdev.rerun_with.filter((v): v is string => typeof v === "string" && v !== ""); + } + } + + // Return null if nothing was actually parsed + if (header.type === undefined && header.version === undefined && + header.run_before === undefined && header.rerun_with === undefined) { + return null; + } + + return header; +} + +/** + * Strip the pgdev header block from file content, returning only the SQL. + * Handles both Format 1 (line comments) and Format 2 (block comment with --- delimiters). + */ +export function stripPgdevHeader(content: string): string { + const trimmed = content.trimStart(); + const leadingWs = content.length - trimmed.length; + + // Format 2: block comment with --- and [pgdev] + if (trimmed.startsWith("/*")) { + const closeIdx = trimmed.indexOf("*/"); + if (closeIdx !== -1) { + const block = trimmed.slice(2, closeIdx); + const lines = block.split("\n").map((l) => l.trim()); + // Check if this block contains --- delimited [pgdev] section + let hasPgdev = false; + let inSection = false; + for (const line of lines) { + if (line === "---") { + inSection = !inSection; + continue; + } + if (inSection && line === "[pgdev]") { + hasPgdev = true; + break; + } + } + if (hasPgdev) { + // Strip the entire block comment (including */ and trailing newline) + const afterClose = closeIdx + 2; + let rest = trimmed.slice(afterClose); + // Remove leading newline after */ + if (rest.startsWith("\n")) rest = rest.slice(1); + return rest; + } + } + } + + // Format 1: -- [pgdev] line comments + const lines = trimmed.split("\n"); + let startIdx = -1; + for (let i = 0; i < lines.length; i++) { + const stripped = lines[i].trim(); + if (!stripped || (stripped.startsWith("--") && !stripped.includes("[pgdev]"))) continue; + if (/^--\s*\[pgdev\]\s*$/.test(stripped)) { + startIdx = i; + break; + } + break; + } + + if (startIdx === -1) return content; + + // Find end of -- comment block + let endIdx = startIdx + 1; + for (; endIdx < lines.length; endIdx++) { + if (!lines[endIdx].trim().startsWith("--")) break; + } + + const remaining = lines.slice(endIdx).join("\n"); + return remaining.startsWith("\n") ? remaining.slice(1) : remaining; +} diff --git a/src/parser/history.ts b/src/parser/history.ts new file mode 100644 index 0000000..45b1f82 --- /dev/null +++ b/src/parser/history.ts @@ -0,0 +1,103 @@ +/** + * Migration history — read/write from database comment or table. + */ + +import type { PgdevConfig } from "../config.ts"; +import { runPsqlQuery } from "../commands/exec.ts"; +import type { HistoryEntry } from "./resolver.ts"; + +export type HistoryResult = + | { ok: true; entries: HistoryEntry[] } + | { ok: false; error: string }; + +/** + * Fetch migration history from the configured storage mode. + */ +export async function fetchHistory(config: PgdevConfig): Promise { + if (config.project.history_mode === "table") { + return fetchHistoryFromTable(config); + } + return fetchHistoryFromComment(config); +} + +/** + * Fetch history from database comment. + * The comment is JSON stored under: {"pgdev": {"": {"migrations": [...]}}} + */ +async function fetchHistoryFromComment(config: PgdevConfig): Promise { + const projectName = config.project.project_name; + if (!projectName) { + return { ok: false, error: 'project_name is required when history_mode = "comment".' }; + } + + // Get current database comment + const sql = `SELECT shobj_description(oid, 'pg_database') FROM pg_database WHERE datname = current_database()`; + const result = await runPsqlQuery(config, sql); + + if (!result.ok) { + return { ok: false, error: result.error }; + } + + const comment = result.rows[0] ?? ""; + if (!comment) { + return { ok: true, entries: [] }; + } + + try { + const data = JSON.parse(comment); + const pgdev = data?.pgdev; + if (!pgdev || typeof pgdev !== "object") { + return { ok: true, entries: [] }; + } + const project = pgdev[projectName]; + if (!project || !Array.isArray(project.migrations)) { + return { ok: true, entries: [] }; + } + return { ok: true, entries: project.migrations as HistoryEntry[] }; + } catch { + // Comment exists but isn't valid JSON — no pgdev history + return { ok: true, entries: [] }; + } +} + +/** + * Fetch history from a dedicated table. + */ +async function fetchHistoryFromTable(config: PgdevConfig): Promise { + const schema = config.project.history_schema || "pgdev"; + const table = config.project.history_table || + (config.project.project_name ? `${config.project.project_name}_history` : "migration_history"); + + // Check if table exists + const existsSql = `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = '${schema}' AND table_name = '${table}')`; + const existsResult = await runPsqlQuery(config, existsSql); + + if (!existsResult.ok) { + return { ok: false, error: existsResult.error }; + } + + if (existsResult.rows[0] !== "t") { + // Table doesn't exist yet — no history + return { ok: true, entries: [] }; + } + + // Fetch all entries + const sql = `SELECT name, type, version, hash FROM ${schema}.${table} ORDER BY installed_on`; + const result = await runPsqlQuery(config, sql); + + if (!result.ok) { + return { ok: false, error: result.error }; + } + + const entries: HistoryEntry[] = result.rows.map((row) => { + const [name, type, version, hash] = row.split("|"); + return { + name, + type, + version: version || undefined, + hash, + }; + }); + + return { ok: true, entries }; +} diff --git a/src/parser/parser-tests/header.test.ts b/src/parser/parser-tests/header.test.ts new file mode 100644 index 0000000..306e2e4 --- /dev/null +++ b/src/parser/parser-tests/header.test.ts @@ -0,0 +1,421 @@ +import { describe, test, expect } from "bun:test"; +import { parsePgdevHeader, stripPgdevHeader } from "../header.ts"; + +describe("parsePgdevHeader", () => { + describe("returns null for no header", () => { + test("empty string", () => { + expect(parsePgdevHeader("")).toBeNull(); + }); + + test("plain SQL with no header", () => { + expect(parsePgdevHeader("CREATE FUNCTION foo() RETURNS void AS $$ BEGIN END; $$ LANGUAGE plpgsql;")).toBeNull(); + }); + + test("regular SQL comment without pgdev", () => { + expect(parsePgdevHeader("-- This is a regular comment\nCREATE FUNCTION foo() RETURNS void;")).toBeNull(); + }); + + test("block comment without pgdev section", () => { + expect(parsePgdevHeader("/*\nregular comment\n*/\nCREATE FUNCTION foo();")).toBeNull(); + }); + + test("block comment with --- but no [pgdev]", () => { + expect(parsePgdevHeader("/*\n---\nsome = \"toml\"\n---\n*/\nSELECT 1;")).toBeNull(); + }); + }); + + describe("Format 1 — line comments", () => { + test("basic type", () => { + const content = `-- [pgdev] +-- type = "routine" +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + }); + + test("repeatable type", () => { + const content = `-- [pgdev] +-- type = "repeatable" +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("repeatable"); + }); + + test("versioned with version", () => { + const content = `-- [pgdev] +-- version = "001" +CREATE TABLE foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.version).toBe("001"); + }); + + test("type + version", () => { + const content = `-- [pgdev] +-- type = "versioned" +-- version = "002" +CREATE TABLE foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("versioned"); + expect(header!.version).toBe("002"); + }); + + test("run_before", () => { + const content = `-- [pgdev] +-- type = "routine" +-- run_before = "R__create_views" +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.run_before).toBe("R__create_views"); + }); + + test("rerun_with as string", () => { + const content = `-- [pgdev] +-- type = "routine" +-- rerun_with = "R__extensions" +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.rerun_with).toEqual(["R__extensions"]); + }); + + test("rerun_with as array", () => { + const content = `-- [pgdev] +-- type = "routine" +-- rerun_with = ["R__extensions", "V001__schema"] +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.rerun_with).toEqual(["R__extensions", "V001__schema"]); + }); + + test("all fields", () => { + const content = `-- [pgdev] +-- type = "routine" +-- run_before = "R__views" +-- rerun_with = ["R__types", "R__extensions"] +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.run_before).toBe("R__views"); + expect(header!.rerun_with).toEqual(["R__types", "R__extensions"]); + }); + + test("stops at non-comment line", () => { + const content = `-- [pgdev] +-- type = "routine" +CREATE FUNCTION foo(); +-- run_before = "should_not_be_parsed"`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.run_before).toBeUndefined(); + }); + + test("with TOML comments", () => { + const content = `-- [pgdev] +-- # This is a TOML comment +-- type = "repeatable" +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("repeatable"); + }); + + test("extra spaces around [pgdev]", () => { + const content = `-- [pgdev] +-- type = "routine" +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + }); + }); + + describe("Format 2 — block comment with --- delimiters", () => { + test("basic type", () => { + const content = `/* +--- +[pgdev] +type = "routine" +--- +*/ +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + }); + + test("with regular comment before ---", () => { + const content = `/* +This is a regular comment about the file. +It can span multiple lines. +--- +[pgdev] +type = "repeatable" +--- +*/ +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("repeatable"); + }); + + test("versioned with version", () => { + const content = `/* +--- +[pgdev] +type = "versioned" +version = "000" +--- +*/ +CREATE TABLE foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("versioned"); + expect(header!.version).toBe("000"); + }); + + test("all fields", () => { + const content = `/* +--- +[pgdev] +type = "routine" +run_before = "R__views" +rerun_with = ["R__types"] +--- +*/ +CREATE FUNCTION foo();`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.run_before).toBe("R__views"); + expect(header!.rerun_with).toEqual(["R__types"]); + }); + + test("with TOML comments inside", () => { + const content = `/* +--- +[pgdev] +# Migration type +type = "routine" +# Version number +# version = "" +--- +*/ +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.version).toBeUndefined(); + }); + + test("empty rerun_with array", () => { + const content = `/* +--- +[pgdev] +type = "routine" +rerun_with = [] +--- +*/ +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.rerun_with).toEqual([]); + }); + + test("rerun_with as single string", () => { + const content = `/* +--- +[pgdev] +type = "routine" +rerun_with = "R__extensions" +--- +*/ +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.rerun_with).toEqual(["R__extensions"]); + }); + + test("matches the sync-generated header format", () => { + const content = `/* +--- +[pgdev] +# Migration type: "routine" or "repeatable" or "versioned" +# For versioned, set version instead (implies versioned automatically) +type = "routine" + +# Version number (implies type = "versioned"), e.g. version = "0001" +# version = "" + +# Execute this file before the referenced file in the migration script +# run_before = "" + +# Re-execute this file whenever any of the referenced files are executed, even if unchanged +# rerun_with = [] +--- +*/ +drop function if exists public.my_func(); +create function public.my_func() returns void as $$ begin end; $$ language plpgsql;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.version).toBeUndefined(); + expect(header!.run_before).toBeUndefined(); + expect(header!.rerun_with).toBeUndefined(); + }); + + test("versioned sync-generated header", () => { + const content = `/* +--- +[pgdev] +# Migration type: "routine" or "repeatable" or "versioned" +# For versioned, set version instead (implies versioned automatically) +type = "versioned" + +# Version number (implies type = "versioned"), e.g. version = "0001" +version = "000" + +# Execute this file before the referenced file in the migration script +# run_before = "" + +# Re-execute this file whenever any of the referenced files are executed, even if unchanged +# rerun_with = [] +--- +*/ +CREATE TABLE foo (id serial);`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("versioned"); + expect(header!.version).toBe("000"); + }); + }); + + describe("edge cases", () => { + test("leading whitespace before header", () => { + const content = ` +-- [pgdev] +-- type = "routine" +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + }); + + test("Format 2 without closing --- returns null", () => { + const content = `/* +--- +[pgdev] +type = "routine" +*/ +SELECT 1;`; + expect(parsePgdevHeader(content)).toBeNull(); + }); + + test("invalid TOML returns null", () => { + const content = `-- [pgdev] +-- type = not_quoted +SELECT 1;`; + expect(parsePgdevHeader(content)).toBeNull(); + }); + + test("unknown type value is ignored", () => { + const content = `-- [pgdev] +-- type = "unknown" +SELECT 1;`; + expect(parsePgdevHeader(content)).toBeNull(); + }); + + test("empty version string is ignored", () => { + const content = `-- [pgdev] +-- type = "routine" +-- version = "" +SELECT 1;`; + const header = parsePgdevHeader(content); + expect(header).not.toBeNull(); + expect(header!.type).toBe("routine"); + expect(header!.version).toBeUndefined(); + }); + + test("[pgdev] not at top of file returns null", () => { + const content = `CREATE FUNCTION foo(); +-- [pgdev] +-- type = "routine"`; + expect(parsePgdevHeader(content)).toBeNull(); + }); + + test("Format 2 block comment not at start returns null", () => { + const content = `SELECT 1; +/* +--- +[pgdev] +type = "routine" +--- +*/`; + expect(parsePgdevHeader(content)).toBeNull(); + }); + }); +}); + +describe("stripPgdevHeader", () => { + test("strips Format 2 block comment header", () => { + const content = `/* +--- +[pgdev] +type = "routine" +--- +*/ +CREATE FUNCTION foo();`; + expect(stripPgdevHeader(content)).toBe("CREATE FUNCTION foo();"); + }); + + test("strips Format 1 line comment header", () => { + const content = `-- [pgdev] +-- type = "routine" +CREATE FUNCTION foo();`; + expect(stripPgdevHeader(content)).toBe("CREATE FUNCTION foo();"); + }); + + test("returns content unchanged when no header", () => { + const content = "CREATE FUNCTION foo();"; + expect(stripPgdevHeader(content)).toBe("CREATE FUNCTION foo();"); + }); + + test("strips sync-generated header", () => { + const content = `/* +--- +[pgdev] +# Migration type: "routine" or "repeatable" or "versioned" +# For versioned, set version instead (implies versioned automatically) +type = "routine" + +# Version number (implies type = "versioned"), e.g. version = "0001" +# version = "" + +# Execute this file before the referenced file in the migration script +# run_before = "" + +# Re-execute this file whenever any of the referenced files are executed, even if unchanged +# rerun_with = [] +--- +*/ +drop function if exists foo(); +create function foo() returns void as $$ begin end; $$ language plpgsql;`; + const stripped = stripPgdevHeader(content); + expect(stripped).toStartWith("drop function"); + expect(stripped).not.toContain("[pgdev]"); + }); + + test("preserves non-pgdev block comments", () => { + const content = `/* regular comment */ +CREATE FUNCTION foo();`; + expect(stripPgdevHeader(content)).toBe(content); + }); +}); diff --git a/src/parser/parser-tests/history.test.ts b/src/parser/parser-tests/history.test.ts new file mode 100644 index 0000000..5c37c74 --- /dev/null +++ b/src/parser/parser-tests/history.test.ts @@ -0,0 +1,204 @@ +import { describe, test, expect, beforeAll } from "bun:test"; +import { createTestDb, loadTestConfig, query, runSetupScript } from "../../test/db.ts"; +import { fetchHistory } from "../history.ts"; +import type { PgdevConfig } from "../../config.ts"; +import { loadConfig } from "../../config.ts"; + +let baseConfig: PgdevConfig; +let testConfig: Awaited>; + +beforeAll(async () => { + await createTestDb(); + await runSetupScript(); + testConfig = await loadTestConfig(); + baseConfig = await loadConfig(); + + // Override connection to use test database + baseConfig.connection = { + host: testConfig.host, + port: testConfig.port, + database: testConfig.database, + username: testConfig.user, + password: testConfig.password, + }; +}); + +describe("fetchHistory — comment mode", () => { + test("returns empty entries when no comment exists", async () => { + const config = { + ...baseConfig, + project: { ...baseConfig.project, history_mode: "comment" as const, project_name: "test_project" }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries).toEqual([]); + } + }); + + test("returns error when project_name is empty", async () => { + const config = { + ...baseConfig, + project: { ...baseConfig.project, history_mode: "comment" as const, project_name: "" }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("project_name"); + } + }); + + test("reads history from database comment", async () => { + const projectName = "history_test_read"; + const migrations = [ + { name: "V001 schema", type: "VERSIONED", version: "001", hash: "abc123" }, + { name: "R seed", type: "REPEATABLE", hash: "def456" }, + ]; + const commentData = JSON.stringify({ pgdev: { [projectName]: { migrations } } }); + await query(`COMMENT ON DATABASE "${testConfig.database}" IS '${commentData.replace(/'/g, "''")}'`); + + const config = { + ...baseConfig, + project: { ...baseConfig.project, history_mode: "comment" as const, project_name: projectName }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries.length).toBe(2); + expect(result.entries[0].name).toBe("V001 schema"); + expect(result.entries[0].type).toBe("VERSIONED"); + expect(result.entries[0].version).toBe("001"); + expect(result.entries[0].hash).toBe("abc123"); + expect(result.entries[1].name).toBe("R seed"); + } + + // Clean up + await query(`COMMENT ON DATABASE "${testConfig.database}" IS NULL`); + }); + + test("returns empty for non-JSON database comment", async () => { + await query(`COMMENT ON DATABASE "${testConfig.database}" IS 'just a plain text comment'`); + + const config = { + ...baseConfig, + project: { ...baseConfig.project, history_mode: "comment" as const, project_name: "some_project" }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries).toEqual([]); + } + + // Clean up + await query(`COMMENT ON DATABASE "${testConfig.database}" IS NULL`); + }); + + test("returns empty when project_name not in comment", async () => { + const commentData = JSON.stringify({ pgdev: { other_project: { migrations: [{ name: "x", type: "VERSIONED", hash: "y" }] } } }); + await query(`COMMENT ON DATABASE "${testConfig.database}" IS '${commentData.replace(/'/g, "''")}'`); + + const config = { + ...baseConfig, + project: { ...baseConfig.project, history_mode: "comment" as const, project_name: "my_project" }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries).toEqual([]); + } + + // Clean up + await query(`COMMENT ON DATABASE "${testConfig.database}" IS NULL`); + }); +}); + +describe("fetchHistory — table mode", () => { + test("returns empty entries when table does not exist", async () => { + const config = { + ...baseConfig, + project: { + ...baseConfig.project, + history_mode: "table" as const, + history_schema: "pgdev_test_hist", + history_table: "nonexistent_history", + }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries).toEqual([]); + } + }); + + test("reads history from table", async () => { + // Create schema and table + await query(`CREATE SCHEMA IF NOT EXISTS pgdev_test_hist`); + await query(`CREATE TABLE pgdev_test_hist.test_history ( + name text NOT NULL, + type text NOT NULL, + version text, + hash text NOT NULL, + installed_by text NOT NULL DEFAULT current_user, + installed_on timestamptz NOT NULL DEFAULT now(), + execution_time interval NOT NULL DEFAULT '0'::interval, + PRIMARY KEY (name, type) + )`); + await query(`INSERT INTO pgdev_test_hist.test_history (name, type, version, hash) VALUES + ('V001 schema', 'VERSIONED', '001', 'abc123'), + ('R seed', 'REPEATABLE', NULL, 'def456')`); + + const config = { + ...baseConfig, + project: { + ...baseConfig.project, + history_mode: "table" as const, + history_schema: "pgdev_test_hist", + history_table: "test_history", + }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries.length).toBe(2); + expect(result.entries[0].name).toBe("V001 schema"); + expect(result.entries[0].type).toBe("VERSIONED"); + expect(result.entries[0].version).toBe("001"); + expect(result.entries[1].name).toBe("R seed"); + expect(result.entries[1].type).toBe("REPEATABLE"); + } + }); + + test("derives table name from project_name", async () => { + await query(`CREATE SCHEMA IF NOT EXISTS pgdev_test_hist`); + await query(`CREATE TABLE IF NOT EXISTS pgdev_test_hist.myapp_history ( + name text NOT NULL, + type text NOT NULL, + version text, + hash text NOT NULL, + installed_by text NOT NULL DEFAULT current_user, + installed_on timestamptz NOT NULL DEFAULT now(), + execution_time interval NOT NULL DEFAULT '0'::interval, + PRIMARY KEY (name, type) + )`); + await query(`INSERT INTO pgdev_test_hist.myapp_history (name, type, version, hash) VALUES + ('V001 init', 'VERSIONED', '001', 'xyz') + ON CONFLICT DO NOTHING`); + + const config = { + ...baseConfig, + project: { + ...baseConfig.project, + history_mode: "table" as const, + history_schema: "pgdev_test_hist", + history_table: "", + project_name: "myapp", + }, + }; + const result = await fetchHistory(config); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.entries.length).toBe(1); + expect(result.entries[0].name).toBe("V001 init"); + } + }); +}); diff --git a/src/parser/parser-tests/resolver.test.ts b/src/parser/parser-tests/resolver.test.ts new file mode 100644 index 0000000..60e8cee --- /dev/null +++ b/src/parser/parser-tests/resolver.test.ts @@ -0,0 +1,476 @@ +import { describe, test, expect } from "bun:test"; +import { resolveExecutionPlan, type HistoryEntry } from "../resolver.ts"; +import type { ProjectFile } from "../scanner.ts"; + +/** Helper to create a minimal ProjectFile for testing. */ +function makeFile(overrides: Partial & { relPath: string; type: ProjectFile["type"] }): ProjectFile { + const filename = overrides.relPath.split("/").pop()!; + return { + path: `/project/${overrides.relPath}`, + relPath: overrides.relPath, + filename: overrides.filename ?? filename, + type: overrides.type, + version: overrides.version, + name: overrides.name ?? filename.replace(/\.sql$/i, "").replace(/[^a-zA-Z0-9]/g, " ").trim(), + header: overrides.header ?? null, + content: overrides.content ?? "SELECT 1;", + hash: overrides.hash ?? `hash_${overrides.relPath}`, + }; +} + +describe("resolveExecutionPlan", () => { + describe("basic execution set", () => { + test("new versioned file is included", () => { + const files = [makeFile({ relPath: "V001__schema.sql", type: "versioned", version: "001" })]; + const result = resolveExecutionPlan(files, []); + expect(result.files.length).toBe(1); + expect(result.files[0].reason).toBe("new"); + }); + + test("versioned file already in history is excluded", () => { + const files = [makeFile({ relPath: "V001__schema.sql", type: "versioned", version: "001", name: "V001 schema" })]; + const history: HistoryEntry[] = [{ name: "V001 schema", type: "VERSIONED", version: "001", hash: "old" }]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(0); + }); + + test("new repeatable file is included", () => { + const files = [makeFile({ relPath: "R__seed.sql", type: "repeatable", name: "R seed" })]; + const result = resolveExecutionPlan(files, []); + expect(result.files.length).toBe(1); + expect(result.files[0].reason).toBe("new"); + }); + + test("repeatable file with same hash is excluded", () => { + const files = [makeFile({ relPath: "R__seed.sql", type: "repeatable", name: "R seed", hash: "abc123" })]; + const history: HistoryEntry[] = [{ name: "R seed", type: "REPEATABLE", hash: "abc123" }]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(0); + }); + + test("repeatable file with changed hash is included", () => { + const files = [makeFile({ relPath: "R__seed.sql", type: "repeatable", name: "R seed", hash: "new_hash" })]; + const history: HistoryEntry[] = [{ name: "R seed", type: "REPEATABLE", hash: "old_hash" }]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(1); + expect(result.files[0].reason).toBe("changed"); + }); + + test("new routine file is included", () => { + const files = [makeFile({ relPath: "api/add.sql", type: "routine", name: "add" })]; + const result = resolveExecutionPlan(files, []); + expect(result.files.length).toBe(1); + expect(result.files[0].reason).toBe("new"); + }); + + test("routine file with same hash is excluded", () => { + const files = [makeFile({ relPath: "api/add.sql", type: "routine", name: "add", hash: "same" })]; + const history: HistoryEntry[] = [{ name: "add", type: "ROUTINE", hash: "same" }]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(0); + }); + + test("routine file with changed hash is included", () => { + const files = [makeFile({ relPath: "api/add.sql", type: "routine", name: "add", hash: "new" })]; + const history: HistoryEntry[] = [{ name: "add", type: "ROUTINE", hash: "old" }]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(1); + expect(result.files[0].reason).toBe("changed"); + }); + }); + + describe("ordering", () => { + test("versioned files come before repeatable and routine", () => { + const files = [ + makeFile({ relPath: "api/add.sql", type: "routine", name: "add" }), + makeFile({ relPath: "R__seed.sql", type: "repeatable", name: "R seed" }), + makeFile({ relPath: "V001__schema.sql", type: "versioned", version: "001", name: "V001 schema" }), + ]; + const result = resolveExecutionPlan(files, []); + expect(result.files[0].type).toBe("versioned"); + expect(result.files[1].type).toBe("repeatable"); + expect(result.files[2].type).toBe("routine"); + }); + + test("versioned files sorted by version numerically", () => { + const files = [ + makeFile({ relPath: "V010__ten.sql", type: "versioned", version: "010", name: "V010 ten" }), + makeFile({ relPath: "V002__two.sql", type: "versioned", version: "002", name: "V002 two" }), + makeFile({ relPath: "V001__one.sql", type: "versioned", version: "001", name: "V001 one" }), + ]; + const result = resolveExecutionPlan(files, []); + expect(result.files.map((f) => f.version)).toEqual(["001", "002", "010"]); + }); + + test("repeatable and routine files sorted by name", () => { + const files = [ + makeFile({ relPath: "api/subtract.sql", type: "routine", name: "subtract" }), + makeFile({ relPath: "api/add.sql", type: "routine", name: "add" }), + makeFile({ relPath: "R__zebra.sql", type: "repeatable", name: "R zebra" }), + makeFile({ relPath: "R__alpha.sql", type: "repeatable", name: "R alpha" }), + ]; + const result = resolveExecutionPlan(files, []); + expect(result.files.map((f) => f.name)).toEqual(["R alpha", "R zebra", "add", "subtract"]); + }); + }); + + describe("run_before ordering", () => { + test("run_before places file before its target", () => { + const files = [ + makeFile({ + relPath: "R__types.sql", + type: "repeatable", + name: "R types", + header: { run_before: "R__views.sql" }, + }), + makeFile({ relPath: "R__views.sql", type: "repeatable", name: "R views" }), + ]; + const result = resolveExecutionPlan(files, []); + const names = result.files.map((f) => f.name); + expect(names.indexOf("R types")).toBeLessThan(names.indexOf("R views")); + }); + + test("run_before with filename stem reference", () => { + const files = [ + makeFile({ + relPath: "R__types.sql", + type: "repeatable", + name: "R types", + header: { run_before: "R__views" }, + }), + makeFile({ relPath: "R__views.sql", type: "repeatable", name: "R views" }), + ]; + const result = resolveExecutionPlan(files, []); + const names = result.files.map((f) => f.name); + expect(names.indexOf("R types")).toBeLessThan(names.indexOf("R views")); + }); + + test("run_before target not in execution set is ignored", () => { + const files = [ + makeFile({ + relPath: "R__types.sql", + type: "repeatable", + name: "R types", + hash: "new", + header: { run_before: "R__not_executing" }, + }), + ]; + const history: HistoryEntry[] = []; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(1); + expect(result.warnings.length).toBe(0); + }); + + test("circular run_before produces warning", () => { + const files = [ + makeFile({ + relPath: "A.sql", + type: "repeatable", + name: "A", + header: { run_before: "B.sql" }, + }), + makeFile({ + relPath: "B.sql", + type: "repeatable", + name: "B", + header: { run_before: "A.sql" }, + }), + ]; + const result = resolveExecutionPlan(files, []); + expect(result.files.length).toBe(2); + expect(result.warnings.some((w) => w.message.includes("Circular"))).toBe(true); + }); + }); + + describe("rerun_with cascading", () => { + test("file cascades when referenced file is executing", () => { + const files = [ + makeFile({ relPath: "R__types.sql", type: "repeatable", name: "R types", hash: "changed" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["R__types.sql"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "R types", type: "REPEATABLE", hash: "old" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(2); + const views = result.files.find((f) => f.name === "R views"); + expect(views).toBeDefined(); + expect(views!.reason).toBe("cascade"); + }); + + test("file does not cascade when referenced file is NOT executing", () => { + const files = [ + makeFile({ relPath: "R__types.sql", type: "repeatable", name: "R types", hash: "same" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["R__types.sql"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "R types", type: "REPEATABLE", hash: "same" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(0); + }); + + test("transitive cascade: A triggers B triggers C", () => { + const files = [ + makeFile({ relPath: "A.sql", type: "repeatable", name: "A", hash: "changed" }), + makeFile({ + relPath: "B.sql", + type: "repeatable", + name: "B", + hash: "same", + header: { rerun_with: ["A.sql"] }, + }), + makeFile({ + relPath: "C.sql", + type: "repeatable", + name: "C", + hash: "same", + header: { rerun_with: ["B.sql"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "A", type: "REPEATABLE", hash: "old" }, + { name: "B", type: "REPEATABLE", hash: "same" }, + { name: "C", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(3); + expect(result.files.find((f) => f.name === "B")!.reason).toBe("cascade"); + expect(result.files.find((f) => f.name === "C")!.reason).toBe("cascade"); + }); + + test("rerun_with by filename stem", () => { + const files = [ + makeFile({ relPath: "R__types.sql", type: "repeatable", name: "R types", hash: "changed" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["R__types"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "R types", type: "REPEATABLE", hash: "old" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(2); + }); + + test("rerun_with with multiple references — any match triggers", () => { + const files = [ + makeFile({ relPath: "A.sql", type: "repeatable", name: "A", hash: "same" }), + makeFile({ relPath: "B.sql", type: "repeatable", name: "B", hash: "changed" }), + makeFile({ + relPath: "C.sql", + type: "repeatable", + name: "C", + hash: "same", + header: { rerun_with: ["A.sql", "B.sql"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "A", type: "REPEATABLE", hash: "same" }, + { name: "B", type: "REPEATABLE", hash: "old" }, + { name: "C", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(2); // B (changed) + C (cascade) + expect(result.files.find((f) => f.name === "C")!.reason).toBe("cascade"); + }); + }); + + describe("flexible file references", () => { + test("rerun_with by bare name (stripped prefix)", () => { + const files = [ + makeFile({ relPath: "V000__schema.sql", type: "versioned", version: "000", name: "V000 schema", hash: "changed" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["schema"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "V000 schema", type: "VERSIONED", version: "000", hash: "old" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + // V000 is versioned and already in history, so it won't re-run + // But if it were new/changed, bare name should match + }); + + test("rerun_with by relative path with ./", () => { + const files = [ + makeFile({ relPath: "R__types.sql", type: "repeatable", name: "R types", hash: "changed" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["./R__types.sql"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "R types", type: "REPEATABLE", hash: "old" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(2); + expect(result.files.find((f) => f.name === "R views")!.reason).toBe("cascade"); + }); + + test("rerun_with by relative path with /", () => { + const files = [ + makeFile({ relPath: "R__types.sql", type: "repeatable", name: "R types", hash: "changed" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["/R__types.sql"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "R types", type: "REPEATABLE", hash: "old" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(2); + }); + + test("run_before by version number", () => { + const files = [ + makeFile({ + relPath: "R__types.sql", + type: "repeatable", + name: "R types", + header: { run_before: "001" }, + }), + makeFile({ relPath: "V001__schema.sql", type: "versioned", version: "001", name: "V001 schema" }), + ]; + const result = resolveExecutionPlan(files, []); + const names = result.files.map((f) => f.name); + expect(names.indexOf("R types")).toBeLessThan(names.indexOf("V001 schema")); + }); + + test("run_before by bare name", () => { + const files = [ + makeFile({ + relPath: "R__types.sql", + type: "repeatable", + name: "R types", + header: { run_before: "views" }, + }), + makeFile({ relPath: "R__views.sql", type: "repeatable", name: "R views" }), + ]; + const result = resolveExecutionPlan(files, []); + const names = result.files.map((f) => f.name); + expect(names.indexOf("R types")).toBeLessThan(names.indexOf("R views")); + }); + + test("rerun_with by version number for versioned files", () => { + const files = [ + makeFile({ relPath: "V002__add_col.sql", type: "versioned", version: "002", name: "V002 add col" }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["002"] }, + }), + ]; + const history: HistoryEntry[] = [ + { name: "R views", type: "REPEATABLE", hash: "same" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(2); + expect(result.files.find((f) => f.name === "R views")!.reason).toBe("cascade"); + }); + }); + + describe("combined scenarios", () => { + test("full scenario: versioned + repeatable + routine + cascade + ordering", () => { + const files = [ + makeFile({ relPath: "V001__init.sql", type: "versioned", version: "001", name: "V001 init" }), + makeFile({ relPath: "V002__tables.sql", type: "versioned", version: "002", name: "V002 tables" }), + makeFile({ + relPath: "R__types.sql", + type: "repeatable", + name: "R types", + hash: "changed", + header: { run_before: "R__views.sql" }, + }), + makeFile({ + relPath: "R__views.sql", + type: "repeatable", + name: "R views", + hash: "same", + header: { rerun_with: ["R__types.sql"] }, + }), + makeFile({ relPath: "api/add.sql", type: "routine", name: "add", hash: "same" }), + ]; + const history: HistoryEntry[] = [ + { name: "V001 init", type: "VERSIONED", version: "001", hash: "x" }, + { name: "R types", type: "REPEATABLE", hash: "old" }, + { name: "R views", type: "REPEATABLE", hash: "same" }, + { name: "add", type: "ROUTINE", hash: "same" }, + ]; + + const result = resolveExecutionPlan(files, history); + + // V001 already executed, V002 is new + // R__types changed, R__views cascades + // add is unchanged + expect(result.files.length).toBe(3); + + const names = result.files.map((f) => f.name); + expect(names).toContain("V002 tables"); + expect(names).toContain("R types"); + expect(names).toContain("R views"); + + // V002 must come first (versioned before repeatable) + expect(names[0]).toBe("V002 tables"); + // R types must come before R views (run_before) + expect(names.indexOf("R types")).toBeLessThan(names.indexOf("R views")); + }); + + test("empty history — all files execute", () => { + const files = [ + makeFile({ relPath: "V001__init.sql", type: "versioned", version: "001", name: "V001 init" }), + makeFile({ relPath: "R__seed.sql", type: "repeatable", name: "R seed" }), + makeFile({ relPath: "api/add.sql", type: "routine", name: "add" }), + ]; + const result = resolveExecutionPlan(files, []); + expect(result.files.length).toBe(3); + }); + + test("all files up to date — nothing executes", () => { + const files = [ + makeFile({ relPath: "V001__init.sql", type: "versioned", version: "001", name: "V001 init", hash: "h1" }), + makeFile({ relPath: "R__seed.sql", type: "repeatable", name: "R seed", hash: "h2" }), + ]; + const history: HistoryEntry[] = [ + { name: "V001 init", type: "VERSIONED", version: "001", hash: "h1" }, + { name: "R seed", type: "REPEATABLE", hash: "h2" }, + ]; + const result = resolveExecutionPlan(files, history); + expect(result.files.length).toBe(0); + }); + }); +}); diff --git a/src/parser/parser-tests/scanner.test.ts b/src/parser/parser-tests/scanner.test.ts new file mode 100644 index 0000000..319821d --- /dev/null +++ b/src/parser/parser-tests/scanner.test.ts @@ -0,0 +1,266 @@ +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { scanProjectFiles, type ScanOptions } from "../scanner.ts"; + +const testDir = resolve(tmpdir(), `pgdev-scanner-test-${Date.now()}`); + +const defaultOpts: ScanOptions = { + upPrefix: "V", + repeatablePrefix: "R", + separator: "__", +}; + +function writeFile(relPath: string, content: string): void { + const fullPath = resolve(testDir, relPath); + const dir = fullPath.slice(0, fullPath.lastIndexOf("/")); + mkdirSync(dir, { recursive: true }); + writeFileSync(fullPath, content); +} + +beforeAll(() => { + mkdirSync(testDir, { recursive: true }); + + // Versioned files + writeFile("V000__schema.sql", `/* +--- +[pgdev] +type = "versioned" +version = "000" +--- +*/ +CREATE TABLE users (id serial);`); + + writeFile("V001__add_email.sql", `CREATE TABLE emails (id serial);`); + + // Repeatable file + writeFile("R__seed_data.sql", `INSERT INTO users (id) VALUES (1);`); + + // Routine file in subdirectory (implicit detection) + writeFile("api/mathmodule/add.sql", `CREATE OR REPLACE FUNCTION mathmodule.add(a int, b int) RETURNS int AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`); + + // Routine file with explicit header + writeFile("api/mathmodule/subtract.sql", `/* +--- +[pgdev] +type = "routine" +--- +*/ +CREATE OR REPLACE FUNCTION mathmodule.subtract(a int, b int) RETURNS int AS $$ BEGIN RETURN a - b; END; $$ LANGUAGE plpgsql;`); + + // Explicit header overriding naming convention + writeFile("R__actually_versioned.sql", `/* +--- +[pgdev] +version = "099" +--- +*/ +ALTER TABLE users ADD COLUMN name text;`); + + // Contradictory header: version + repeatable + writeFile("bad_contradictory.sql", `/* +--- +[pgdev] +type = "repeatable" +version = "001" +--- +*/ +SELECT 1;`); + + // Explicit routine type but no valid routine + writeFile("bad_routine.sql", `/* +--- +[pgdev] +type = "routine" +--- +*/ +SELECT 1;`); + + // Unrecognized file — no header, no prefix, no routine + writeFile("random_notes.sql", `-- just some notes +SELECT current_timestamp;`); + + // Versioned header without version and no filename convention + writeFile("bad_versioned.sql", `/* +--- +[pgdev] +type = "versioned" +--- +*/ +SELECT 1;`); + + // Routine with run_before and rerun_with + writeFile("api/mathmodule/multiply.sql", `/* +--- +[pgdev] +type = "routine" +run_before = "R__seed_data" +rerun_with = ["R__seed_data"] +--- +*/ +CREATE OR REPLACE FUNCTION mathmodule.multiply(a int, b int) RETURNS int AS $$ BEGIN RETURN a * b; END; $$ LANGUAGE plpgsql;`); + + // Repeatable with explicit header + writeFile("R__views.sql", `/* +--- +[pgdev] +type = "repeatable" +rerun_with = "R__seed_data" +--- +*/ +CREATE OR REPLACE VIEW v_users AS SELECT * FROM users;`); +}); + +afterAll(() => { + rmSync(testDir, { recursive: true, force: true }); +}); + +describe("scanProjectFiles", () => { + test("classifies versioned files by naming convention", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const v001 = result.files.find((f) => f.filename === "V001__add_email.sql"); + expect(v001).toBeDefined(); + expect(v001!.type).toBe("versioned"); + expect(v001!.version).toBe("001"); + }); + + test("classifies versioned files by header", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const v000 = result.files.find((f) => f.filename === "V000__schema.sql"); + expect(v000).toBeDefined(); + expect(v000!.type).toBe("versioned"); + expect(v000!.version).toBe("000"); + }); + + test("classifies repeatable files by naming convention", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const r = result.files.find((f) => f.filename === "R__seed_data.sql"); + expect(r).toBeDefined(); + expect(r!.type).toBe("repeatable"); + expect(r!.version).toBeUndefined(); + }); + + test("classifies implicit routine files", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const add = result.files.find((f) => f.filename === "add.sql"); + expect(add).toBeDefined(); + expect(add!.type).toBe("routine"); + }); + + test("classifies explicit routine files", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const sub = result.files.find((f) => f.filename === "subtract.sql"); + expect(sub).toBeDefined(); + expect(sub!.type).toBe("routine"); + }); + + test("header overrides naming convention", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const f = result.files.find((f) => f.filename === "R__actually_versioned.sql"); + expect(f).toBeDefined(); + expect(f!.type).toBe("versioned"); + expect(f!.version).toBe("099"); + }); + + test("warns on contradictory header (version + repeatable)", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const w = result.warnings.find((w) => w.file === "bad_contradictory.sql"); + expect(w).toBeDefined(); + expect(w!.message).toContain("Contradictory"); + expect(result.files.find((f) => f.filename === "bad_contradictory.sql")).toBeUndefined(); + }); + + test("warns on explicit routine type with no valid routine", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const w = result.warnings.find((w) => w.file === "bad_routine.sql"); + expect(w).toBeDefined(); + expect(w!.message).toContain("no valid routine"); + expect(result.files.find((f) => f.filename === "bad_routine.sql")).toBeUndefined(); + }); + + test("warns on unrecognized files", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const w = result.warnings.find((w) => w.file === "random_notes.sql"); + expect(w).toBeDefined(); + expect(w!.message).toContain("not recognized"); + }); + + test("warns on versioned header without version", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const w = result.warnings.find((w) => w.file === "bad_versioned.sql"); + expect(w).toBeDefined(); + expect(w!.message).toContain("no version found"); + }); + + test("preserves header fields (run_before, rerun_with)", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const mul = result.files.find((f) => f.filename === "multiply.sql"); + expect(mul).toBeDefined(); + expect(mul!.header).not.toBeNull(); + expect(mul!.header!.run_before).toBe("R__seed_data"); + expect(mul!.header!.rerun_with).toEqual(["R__seed_data"]); + }); + + test("normalizes rerun_with string to array", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const views = result.files.find((f) => f.filename === "R__views.sql"); + expect(views).toBeDefined(); + expect(views!.header!.rerun_with).toEqual(["R__seed_data"]); + }); + + test("computes SHA-256 hash for each file", () => { + const result = scanProjectFiles(testDir, defaultOpts); + for (const f of result.files) { + expect(f.hash).toMatch(/^[0-9a-f]{64}$/); + } + }); + + test("sets relPath relative to project dir", () => { + const result = scanProjectFiles(testDir, defaultOpts); + const add = result.files.find((f) => f.filename === "add.sql"); + expect(add).toBeDefined(); + expect(add!.relPath).toBe("api/mathmodule/add.sql"); + }); + + test("custom prefixes and separator", () => { + // Create files with custom convention + writeFile("UP_001-schema.sql", `CREATE TABLE test (id int);`); + writeFile("REP-init.sql", `INSERT INTO test VALUES (1);`); + + const customOpts: ScanOptions = { + upPrefix: "UP_", + repeatablePrefix: "REP", + separator: "-", + }; + + const result = scanProjectFiles(testDir, customOpts); + const up = result.files.find((f) => f.filename === "UP_001-schema.sql"); + expect(up).toBeDefined(); + expect(up!.type).toBe("versioned"); + expect(up!.version).toBe("001"); + + const rep = result.files.find((f) => f.filename === "REP-init.sql"); + expect(rep).toBeDefined(); + expect(rep!.type).toBe("repeatable"); + }); + + test("detectRoutines = false skips routine parsing", () => { + const result = scanProjectFiles(testDir, { ...defaultOpts, detectRoutines: false }); + // add.sql has no header and no naming convention — without routine detection it's unrecognized + const add = result.files.find((f) => f.filename === "add.sql"); + expect(add).toBeUndefined(); + const w = result.warnings.find((w) => w.file === "api/mathmodule/add.sql"); + expect(w).toBeDefined(); + }); + + test("total file count matches expected", () => { + const result = scanProjectFiles(testDir, defaultOpts); + // Valid files: V000, V001, R__seed_data, add, subtract, R__actually_versioned, multiply, R__views + // + UP_001 and REP (from custom prefix test) — these won't match default opts + // UP_001-schema.sql and REP-init.sql with default opts: unrecognized + expect(result.files.length).toBe(8); + // Warnings: bad_contradictory, bad_routine, random_notes, bad_versioned, UP_001, REP + expect(result.warnings.length).toBe(6); + }); +}); diff --git a/src/parser/resolver.ts b/src/parser/resolver.ts new file mode 100644 index 0000000..1197915 --- /dev/null +++ b/src/parser/resolver.ts @@ -0,0 +1,260 @@ +/** + * Resolve which project files need execution and in what order. + * + * 1. Compare scanned files against history to determine what needs executing + * 2. Apply rerun_with cascading (if a referenced file runs, cascade to dependents) + * 3. Apply run_before ordering (topological sort) + */ + +import type { ProjectFile, FileType } from "./scanner.ts"; + +export interface HistoryEntry { + name: string; + type: string; // "VERSIONED" | "REPEATABLE" | "ROUTINE" + version?: string; + hash: string; +} + +export interface ResolvedFile extends ProjectFile { + /** Reason this file was included in the execution set */ + reason: "new" | "changed" | "cascade"; +} + +export interface ResolveResult { + /** Files to execute, in order */ + files: ResolvedFile[]; + /** Warnings from resolution */ + warnings: { file: string; message: string }[]; +} + +/** + * Normalize FileType to history type string. + */ +function toHistoryType(type: FileType): string { + return type.toUpperCase(); +} + +/** + * Match a project file to a history entry. + */ +function findHistoryEntry(file: ProjectFile, history: HistoryEntry[]): HistoryEntry | undefined { + const histType = toHistoryType(file.type); + return history.find((h) => h.name === file.name && h.type === histType); +} + +/** + * Determine which files need execution based on history. + */ +function computeExecutionSet( + files: ProjectFile[], + history: HistoryEntry[], +): Map { + const needsExec = new Map(); + + for (const file of files) { + const entry = findHistoryEntry(file, history); + + if (file.type === "versioned") { + // Versioned: execute if version not in history + if (!entry) { + needsExec.set(file.relPath, { file, reason: "new" }); + } + } else { + // Repeatable / routine: execute if hash changed or new + if (!entry) { + needsExec.set(file.relPath, { file, reason: "new" }); + } else if (entry.hash !== file.hash) { + needsExec.set(file.relPath, { file, reason: "changed" }); + } + } + } + + return needsExec; +} + +/** + * Build a lookup map from various reference formats to relPath. + * + * Supported reference forms: + * - relPath: "test/V000_schema.sql" + * - relPath with leading ./ or /: "./test/V000_schema.sql", "/test/V000_schema.sql" + * - filename with extension: "V000_schema.sql" + * - filename without extension: "V000_schema" + * - bare name (stripped of prefixes and extensions): "schema" + * - version number for versioned files: "000" + */ +function buildRefIndex(files: ProjectFile[]): Map { + const index = new Map(); + for (const f of files) { + // relPath as-is + index.set(f.relPath, f.relPath); + // relPath with leading ./ or / + index.set(`./${f.relPath}`, f.relPath); + index.set(`/${f.relPath}`, f.relPath); + // filename with extension + index.set(f.filename, f.relPath); + // filename without extension + const stem = f.filename.replace(/\.sql$/i, ""); + index.set(stem, f.relPath); + // bare name: strip prefix + separator from stem + // e.g. V000__schema → schema, R__seed_data → seed_data + const sepIdx = stem.indexOf("__"); + if (sepIdx !== -1) { + const bareName = stem.slice(sepIdx + 2); + if (bareName) { + // Only set if not already taken (first wins to avoid conflicts) + if (!index.has(bareName)) { + index.set(bareName, f.relPath); + } + } + } + // version number for versioned files + if (f.type === "versioned" && f.version) { + if (!index.has(f.version)) { + index.set(f.version, f.relPath); + } + } + } + return index; +} + +/** + * Apply rerun_with cascading: if any referenced file is in the execution set, + * add this file too. + */ +function applyCascade( + files: ProjectFile[], + needsExec: Map, +): void { + const relPathByRef = buildRefIndex(files); + + // Iterate until no more cascades (handles transitive chains) + let changed = true; + while (changed) { + changed = false; + for (const file of files) { + if (needsExec.has(file.relPath)) continue; + const rerunWith = file.header?.rerun_with; + if (!rerunWith || rerunWith.length === 0) continue; + + for (const ref of rerunWith) { + const resolvedRef = relPathByRef.get(ref); + if (resolvedRef && needsExec.has(resolvedRef)) { + needsExec.set(file.relPath, { file, reason: "cascade" }); + changed = true; + break; + } + } + } + } +} + +/** + * Apply run_before ordering via topological sort. + * Returns ordered files or adds warnings for cycles. + */ +function applyOrdering( + execFiles: ResolvedFile[], + allFiles: ProjectFile[], +): { ordered: ResolvedFile[]; warnings: { file: string; message: string }[] } { + const warnings: { file: string; message: string }[] = []; + + // Build lookup: various reference forms → index in execFiles + const refToRelPath = buildRefIndex(execFiles); + const relPathToIdx = new Map(); + for (let i = 0; i < execFiles.length; i++) { + relPathToIdx.set(execFiles[i].relPath, i); + } + + // Build adjacency: edges[i] = set of indices that must come after i + const n = execFiles.length; + const edges: Set[] = Array.from({ length: n }, () => new Set()); + const inDegree = new Array(n).fill(0); + + for (let i = 0; i < execFiles.length; i++) { + const runBefore = execFiles[i].header?.run_before; + if (!runBefore) continue; + + const targetRelPath = refToRelPath.get(runBefore); + const targetIdx = targetRelPath !== undefined ? relPathToIdx.get(targetRelPath) : undefined; + if (targetIdx !== undefined && targetIdx !== i) { + // i must run before targetIdx + if (!edges[i].has(targetIdx)) { + edges[i].add(targetIdx); + inDegree[targetIdx]++; + } + } + // If target not in execution set, ignore silently + } + + // Kahn's algorithm for topological sort + const queue: number[] = []; + for (let i = 0; i < n; i++) { + if (inDegree[i] === 0) queue.push(i); + } + + const ordered: ResolvedFile[] = []; + while (queue.length > 0) { + // Among nodes with 0 in-degree, pick the one with the lowest natural order + // (preserves stable sorting when no constraints exist) + queue.sort((a, b) => a - b); + const idx = queue.shift()!; + ordered.push(execFiles[idx]); + for (const neighbor of edges[idx]) { + inDegree[neighbor]--; + if (inDegree[neighbor] === 0) queue.push(neighbor); + } + } + + if (ordered.length < n) { + // Cycle detected — add remaining files with warning + for (let i = 0; i < n; i++) { + if (!ordered.includes(execFiles[i])) { + warnings.push({ + file: execFiles[i].relPath, + message: "Circular run_before dependency detected. Added in natural order.", + }); + ordered.push(execFiles[i]); + } + } + } + + return { ordered, warnings }; +} + +/** + * Resolve which files need execution and in what order. + */ +export function resolveExecutionPlan( + files: ProjectFile[], + history: HistoryEntry[], +): ResolveResult { + // Step 1: Determine base execution set + const needsExec = computeExecutionSet(files, history); + + // Step 2: Apply rerun_with cascading + applyCascade(files, needsExec); + + // Step 3: Sort by type priority + natural order before applying run_before + const execFiles: ResolvedFile[] = [...needsExec.values()].map(({ file, reason }) => ({ + ...file, + reason, + })); + + // Sort: versioned first (by version), then repeatable/routine (by name) + execFiles.sort((a, b) => { + const typeOrder = { versioned: 0, repeatable: 1, routine: 2 }; + const ta = typeOrder[a.type]; + const tb = typeOrder[b.type]; + if (ta !== tb) return ta - tb; + if (a.type === "versioned" && b.type === "versioned") { + return (a.version ?? "").localeCompare(b.version ?? "", undefined, { numeric: true }); + } + return a.name.localeCompare(b.name); + }); + + // Step 4: Apply run_before topological ordering + const { ordered, warnings } = applyOrdering(execFiles, files); + + return { files: ordered, warnings }; +} diff --git a/src/parser/scanner.ts b/src/parser/scanner.ts new file mode 100644 index 0000000..4de8fb2 --- /dev/null +++ b/src/parser/scanner.ts @@ -0,0 +1,212 @@ +/** + * Scan project_dir and classify SQL files as routine, versioned, or repeatable. + */ + +import { resolve } from "node:path"; +import { findSqlFiles } from "../utils/files.ts"; +import { parsePgdevHeader, type PgdevHeader } from "./header.ts"; +import { parseRoutines } from "./routine.ts"; + +export type FileType = "routine" | "versioned" | "repeatable"; + +export interface ProjectFile { + /** Absolute path */ + path: string; + /** Path relative to project_dir */ + relPath: string; + /** Filename without directory */ + filename: string; + /** Classified type */ + type: FileType; + /** Version string (for versioned files) */ + version?: string; + /** Migration name derived from filename */ + name: string; + /** Parsed pgdev header, if present */ + header: PgdevHeader | null; + /** File content */ + content: string; + /** Content hash (SHA-256) */ + hash: string; +} + +export interface ScanWarning { + file: string; + message: string; +} + +export interface ScanResult { + files: ProjectFile[]; + warnings: ScanWarning[]; +} + +export interface ScanOptions { + upPrefix: string; + repeatablePrefix: string; + separator: string; + /** Whether to parse routines for implicit detection (default: true) */ + detectRoutines?: boolean; +} + +/** + * Derive a human-readable migration name from a filename. + * Strips the extension and replaces non-alphanumeric chars with spaces. + */ +function deriveName(filename: string): string { + return filename.replace(/\.sql$/i, "").replace(/[^a-zA-Z0-9]/g, " ").trim().replace(/\s+/g, " "); +} + +/** + * Compute SHA-256 hash of content. + */ +function sha256(content: string): string { + const hasher = new Bun.CryptoHasher("sha256"); + hasher.update(content); + return hasher.digest("hex"); +} + +/** + * Try to classify a file by its filename prefix (naming convention). + * Returns the type and version (if versioned), or null if no convention matches. + */ +function classifyByPrefix( + filename: string, + opts: ScanOptions, +): { type: FileType; version?: string } | null { + const { upPrefix, repeatablePrefix, separator } = opts; + + // Check versioned: V__.sql + if (filename.startsWith(upPrefix)) { + const sepIdx = filename.indexOf(separator, upPrefix.length); + if (sepIdx !== -1) { + const version = filename.slice(upPrefix.length, sepIdx); + if (version.length > 0) { + return { type: "versioned", version }; + } + } + } + + // Check repeatable: R__.sql + if (filename.startsWith(repeatablePrefix)) { + const sepIdx = filename.indexOf(separator, repeatablePrefix.length); + if (sepIdx !== -1) { + return { type: "repeatable" }; + } + } + + return null; +} + +/** + * Scan project_dir and classify all SQL files. + */ +export function scanProjectFiles( + projectDir: string, + opts: ScanOptions, +): ScanResult { + const fullDir = resolve(projectDir); + const sqlFiles = findSqlFiles(fullDir); + const files: ProjectFile[] = []; + const warnings: ScanWarning[] = []; + const detectRoutines = opts.detectRoutines !== false; + + for (const filePath of sqlFiles) { + const relPath = filePath.slice(fullDir.length + 1); + const filename = filePath.split("/").pop()!; + const content = require("node:fs").readFileSync(filePath, "utf-8") as string; + const hash = sha256(content); + const header = parsePgdevHeader(content); + + let type: FileType | null = null; + let version: string | undefined; + + // Priority 1: Check for contradictory header (version + type = "repeatable") + if (header?.version && header?.type === "repeatable") { + warnings.push({ + file: relPath, + message: `Contradictory header: version "${header.version}" with type "repeatable". Skipping.`, + }); + continue; + } + + // Priority 2: Explicit type = "routine" but no valid routine + if (header?.type === "routine") { + if (detectRoutines) { + const routines = parseRoutines(content); + if (routines.length === 0) { + warnings.push({ + file: relPath, + message: `Header declares type "routine" but no valid routine found. Skipping.`, + }); + continue; + } + } + type = "routine"; + } + + // Priority 3: Explicit type from header + if (type === null && header?.version) { + type = "versioned"; + version = header.version; + } + if (type === null && header?.type === "repeatable") { + type = "repeatable"; + } + if (type === null && header?.type === "versioned") { + // versioned without version in header — check filename + const prefixResult = classifyByPrefix(filename, opts); + if (prefixResult?.type === "versioned") { + type = "versioned"; + version = prefixResult.version; + } else { + warnings.push({ + file: relPath, + message: `Header declares type "versioned" but no version found. Skipping.`, + }); + continue; + } + } + + // Priority 4: Naming convention + if (type === null) { + const prefixResult = classifyByPrefix(filename, opts); + if (prefixResult) { + type = prefixResult.type; + version = prefixResult.version; + } + } + + // Priority 5: Implicit routine detection + if (type === null && detectRoutines) { + const routines = parseRoutines(content); + if (routines.length > 0) { + type = "routine"; + } + } + + // Priority 6: Unrecognized + if (type === null) { + warnings.push({ + file: relPath, + message: `File type not recognized. Skipping.`, + }); + continue; + } + + const name = deriveName(filename); + + files.push({ + path: filePath, + relPath, + filename, + type, + version, + name, + header, + content, + hash, + }); + } + + return { files, warnings }; +}