import type { Branch, Database } from "@neon/sdk"; import chalk from "chalk"; import { createPatch } from "diff"; import { sendError } from "../analytics.js"; import { isNeonApiError, messageFromBody } from "../api.js"; import { log } from "../log.js"; import type { BranchScopeProps } from "../types"; import { type BranchListing, listAllProjectBranchesWithAnnotations, resolveBranchFromProps, } from "../utils/enrichers.js"; import { type PointInTime, type PointInTimeBranchId, parsePointInTime, } from "../utils/point_in_time.js"; import { writer } from "../writer.js"; type SchemaDiffProps = BranchScopeProps & { branch?: string; baseBranch?: string; compareSource: string; database: string; /** The listing `parseSchemaDiffParams` fetched, reused by the handler. */ branchListing?: BranchListing; }; const COLORS = { added: chalk.green, removed: chalk.red, header: chalk.yellow, section: chalk.magenta, }; type ColorId = keyof typeof COLORS; export const schemaDiff = async (props: SchemaDiffProps) => { props.branch = props.baseBranch || props.branch; const { branchId: baseBranch, branch: baseBranchData, listing, } = await resolveBranchFromProps(props, props.branchListing); let pointInTime: PointInTimeBranchId = await parsePointInTime({ pointInTime: props.compareSource, targetBranchId: baseBranch, projectId: props.projectId, api: props.apiClient, branches: listing?.branches, targetBranch: baseBranchData, }); // Swap base and compare points if comparing with parent branch const comparingWithParent = props.compareSource.startsWith("^parent"); let baseBranchPoint: PointInTimeBranchId = { branchId: baseBranch, tag: "head", }; [baseBranchPoint, pointInTime] = comparingWithParent ? [pointInTime, baseBranchPoint] : [baseBranchPoint, pointInTime]; const baseDatabases = await fetchDatabases(baseBranch, props); if (props.database) { const database = baseDatabases.find( (db: Database) => db.name === props.database, ); if (!database) { throw new Error( `Database ${props.database} does not exist in base branch ${baseBranch}`, ); } const diff = await createSchemaDiff( baseBranchPoint, pointInTime, database, props, ); writer(props).text(colorize(diff.patch)); reportUnchanged( diff, [baseBranchPoint, pointInTime], database, props, listing, ); return; } await Promise.all( baseDatabases.map(async (database: Database) => { const diff = await createSchemaDiff( baseBranchPoint, pointInTime, database, props, ); writer(props).text(colorize(diff.patch)); reportUnchanged( diff, [baseBranchPoint, pointInTime], database, props, listing, ); }), ); }; /** The patch alone is two header lines when nothing differs, which reads like missing output. */ const reportUnchanged = ( diff: { unchanged: boolean }, [base, compare]: [PointInTimeBranchId, PointInTimeBranchId], database: Database, props: SchemaDiffProps, listing: BranchListing | undefined, ) => { if (!diff.unchanged || props.output !== "table") { return; } const label = (point: PointInTimeBranchId) => { const name = listing?.branches.find((b) => b.id === point.branchId)?.name ?? point.branchId; return point.tag === "lsn" ? `${name} at ${point.lsn}` : point.tag === "timestamp" ? `${name} at ${point.timestamp}` : name; }; log.info( `No schema differences for database ${database.name} between ${label(base)} and ${label(compare)}.`, ); }; const fetchDatabases = async (branch: string, props: SchemaDiffProps) => { return props.apiClient .listProjectBranchDatabases(props.projectId, branch) .then((response) => response.data.databases); }; const createSchemaDiff = async ( baseBranch: PointInTimeBranchId, pointInTime: PointInTimeBranchId, database: Database, props: SchemaDiffProps, ) => { const [baseSchema, compareSchema] = await Promise.all([ fetchSchema(baseBranch, database, props), fetchSchema(pointInTime, database, props), ]); return { patch: createPatch( `Database: ${database.name}`, baseSchema, compareSchema, generateHeader(baseBranch), generateHeader(pointInTime), ), unchanged: baseSchema === compareSchema, }; }; const fetchSchema = async ( pointInTime: PointInTimeBranchId, database: Database, props: SchemaDiffProps, ) => { try { const response = await props.apiClient.getProjectBranchSchema({ projectId: props.projectId, branchId: pointInTime.branchId, db_name: database.name, ...pointInTimeParams(pointInTime), }); return response.data.sql ?? ""; } catch (error) { if (isNeonApiError(error)) { sendError(error, "API_ERROR"); throw new Error( messageFromBody(error.data) ?? `Error while fetching schema for branch ${pointInTime.branchId}`, ); } throw error; } }; const colorize = (patch: string) => { return patch .replace(/^([^\n]+)\n([^\n]+)\n/m, "") // Remove first two lines .replace(/^-.*/gm, colorizer("removed")) .replace(/^\+.*/gm, colorizer("added")) .replace(/^@@.+@@.*/gm, colorizer("section")); }; const colorizer = (colorId: ColorId) => { // chalk 5 does not read NO_COLOR (https://no-color.org). if (process.env.NO_COLOR) { return (line: string) => line; } const color = COLORS[colorId]; return (line: string) => color(line); }; const pointInTimeParams = (pointInTime: PointInTime) => { switch (pointInTime.tag) { case "timestamp": return { timestamp: pointInTime.timestamp, }; case "lsn": return { lsn: pointInTime.lsn ?? undefined, }; default: return {}; } }; const generateHeader = (pointInTime: PointInTimeBranchId) => { const header = `(Branch: ${pointInTime.branchId}`; switch (pointInTime.tag) { case "timestamp": return `${header} at ${pointInTime.timestamp})`; case "lsn": return `${header} at ${pointInTime.lsn})`; default: return `${header})`; } }; /* The command has two positional optional arguments - [base-branch] and [compare-source] If only one argument is specified, we should consider it as `compare-source` and `base-branch` will be either read from context or the default branch of project. If no branches are specified, compare the context branch with its parent */ export const parseSchemaDiffParams = async (props: SchemaDiffProps) => { if (!props.compareSource) { if (props.baseBranch) { props.compareSource = props.baseBranch; props.baseBranch = props.branch; } else if (props.branch) { props.branchListing = await listAllProjectBranchesWithAnnotations( props.apiClient, props.projectId, ); const contextBranch = props.branchListing.branches.find( (b: Branch) => b.id === props.branch || b.name === props.branch, ); if (contextBranch?.parent_id == undefined) { throw new Error( `No branch specified. Your context branch (${props.branch}) has no parent, so no comparison is possible.`, ); } log.info( `No branches specified. Comparing your context branch '${props.branch}' with its parent`, ); props.compareSource = "^parent"; } else { props.branchListing = await listAllProjectBranchesWithAnnotations( props.apiClient, props.projectId, ); const defaultBranch = props.branchListing.branches.find( (b: Branch) => b.default, ); if (defaultBranch?.parent_id == undefined) { throw new Error( "No branch specified. Include a base branch or add a set-context branch to continue. Your default branch has no parent, so no comparison is possible.", ); } log.info( `No branches specified. Comparing default branch with its parent`, ); props.compareSource = "^parent"; } } return props; };