GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fork: CI check that refuses database schema and migration changes by scuttletoby · Pull Request #3 · scuttletoby/t3code

fork: CI check that refuses database schema and migration changes #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
scuttletoby merged 6 commits into main from fork/no-schema-changes
Nov 12, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

fork: CI check that refuses database schema and migration changes #3

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
2146267
fork: CI check that refuses database schema and migration changes
noreply Nov 12, 2026
e9afd0c
fork: schema check runs from the base branch and reads whole files
noreply Nov 12, 2026
a7328e4
fork: schema check judges its own files against the base's copy
noreply Nov 12, 2026
ca47142
fork: schema check guards re-exporting barrels and fails closed on un…
noreply Nov 12, 2026
dee218a
fork: schema check guards package.json and refuses imports it cannot …
noreply Nov 12, 2026
5c2688e
fork: schema check guards the importer's dependency specs and judges …
noreply Nov 12, 2026
File filter
Filter by extension


Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
fork: schema check judges its own files against the base's copy
- A check file or .gitattributes that the branch carries unchanged from
  the base passes. After main is rebased onto a new upstream release, a
  branch from the old main is told to rebase onto main (its commits are
  matched on main by author, author time and subject), never to merge
  past the red check.
- Package root imports (@t3tools/contracts) are followed to the files
  that declare the imported names, so migration 064's schemas in
  threadPullRequest.ts are covered while the rest of the package is not.
- Schema statements also match across SQL comments and string joins, and
  with upper-case keywords around an interpolation (CREATE ${kind}).
- parseRawDiff throws on output it cannot read; actions/checkout is
  pinned by commit SHA.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@noreply @claude
noreply and claude committed Nov 12, 2026
commit a7328e42ae42141a7a936b31473a2e7337c41a3f

There are no files selected for viewing

199 changes: 169 additions & 30 deletions 199 .github/scripts/fork-schema-check.cjs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Refuses fork changes to the database schema: T3 has no down-migrations, so a fork migration
// strands installs that return to upstream. Usage: fork-schema-check.cjs <base> <head>.
// Refused: migrations, schema setup and what they import; shipped files holding a schema statement
// (matched across lines); this check itself and .gitattributes. Files are read as git blobs.
// Refused: migrations, schema setup and what they import; shipped source files holding a schema
// statement; a PR copy of this check or of .gitattributes that differs from the base's copy; and a
// branch built on an old (since rebased) base. Files are read as git blobs.

const { execFileSync } = require("node:child_process");
const path = require("node:path");
Expand All @@ -23,21 +24,40 @@ const CHECK_FILES = [
];
const GITATTRIBUTES = /(^|\/)\.gitattributes$/;

// Schema statements in shipped source (tests may build their own tables). \s spans line breaks.
const SCHEMA_STATEMENT =
/\b(CREATE\s+(UNIQUE\s+)?(TABLE|INDEX|VIEW|TRIGGER|VIRTUAL\s+TABLE)|ALTER\s+TABLE|DROP\s+(TABLE|INDEX|VIEW|TRIGGER))\b/i;
// Schema statements in shipped source (tests may build their own tables). Between the keywords
// may stand line breaks, SQL comments and string joins ("CREATE " + "TABLE"). An interpolation
// where the object kind belongs (`CREATE ${kind}`) counts too, but only with upper-case keywords,
// so UI text such as `Create ${label}` stays free.
const GAP = String.raw`(?:\s|["'\x60+]|/\*[\s\S]*?\*/|--[^\n]*\n)+`;
const HOLE = String.raw`\$\{[^}]*\}`;
const SCHEMA_STATEMENTS = [
new RegExp(
String.raw`\b(?:CREATE${GAP}(?:UNIQUE${GAP})?(?:TABLE|INDEX|VIEW|TRIGGER|VIRTUAL${GAP}TABLE)|ALTER${GAP}TABLE|DROP${GAP}(?:TABLE|INDEX|VIEW|TRIGGER))\b`,
"i",
),
new RegExp(String.raw`\b(?:CREATE${GAP}(?:UNIQUE${GAP})?|ALTER${GAP}|DROP${GAP})${HOLE}`),
];
/** The first schema statement in `text`, or undefined. */
const schemaStatement = (text) =>
text === undefined
? undefined
: SCHEMA_STATEMENTS.map((pattern) => text.match(pattern)?.[0]).find(Boolean);
const SHIPPED_SOURCE = /^(apps|packages)\/.+\.(ts|tsx|mts|cts|js|mjs|cjs|sql)$/;
const TEST_SOURCE = /(\.test\.|\.spec\.|\.testkit\.|\/testkit\/|\/__tests__\/|\/test\/)/;
const SOURCE_EXTENSIONS = ["", ".ts", ".tsx", ".mts", ".js", "/index.ts", "/index.tsx"];
const PACKAGE_MANIFEST = /^(apps|packages)\/[^/]+\/package\.json$/;
const IMPORT_SPECIFIER = /\b(?:from|import|require)\s*\(?\s*["']([^"'\n]+)["']/g;
// `import { A, type B as C } from "x"` and `export { A } from "x"`: the names a static clause takes.
const IMPORT_CLAUSE =
/\b(?:import|export)\s+(?:type\s+)?([\w$*{}\s,]*?)\s*from\s*["']([^"'\n]+)["']/g;

const isTest = (file) => TEST_SOURCE.test(file);
const isShippedSource = (file) => SHIPPED_SOURCE.test(file) && !isTest(file);

/**
* Files the schema roots import, transitively: relative and package subpath imports. Package
* roots (`@t3tools/contracts`) re-export the whole package, so they are not followed.
* Files the schema roots import, transitively: relative and package subpath imports, and for a
* package root (`@t3tools/contracts`) the files that declare the names imported from it. The
* root's barrel itself is not added, so the rest of the package stays free to change.
* @param {{ files: string[]; has(file: string): boolean; read(file: string): string }} tree
* @returns {Set<string>}
*/
Expand All @@ -50,11 +70,13 @@ function schemaClosure(tree) {
while (queue.length > 0) {
const file = queue.pop();
const text = tree.read(file);
const names = importedNames(text);
for (const match of text.matchAll(IMPORT_SPECIFIER)) {
const target = resolveImport(tree, packages, file, match[1]);
if (target && !isTest(target) && !closure.has(target)) {
closure.add(target);
queue.push(target);
for (const target of resolveImport(tree, packages, file, match[1], names.get(match[1]))) {
if (!isTest(target) && !closure.has(target)) {
closure.add(target);
queue.push(target);
}
}
}
}
Expand All @@ -77,19 +99,93 @@ function packageDirectories(tree) {
return packages;
}

function resolveImport(tree, packages, from, specifier) {
/**
* Per specifier, the names static clauses take from it; `*` for a namespace or a clause it cannot
* read. A specifier with no entry (dynamic import, require, side-effect import) takes everything.
* @returns {Map<string, Set<string>>}
*/
function importedNames(text) {
const names = new Map();
for (const [, clause, specifier] of text.matchAll(IMPORT_CLAUSE)) {
const set = names.get(specifier) ?? new Set();
names.set(specifier, set);
const braces = clause.match(/\{([^}]*)\}/);
const outside = clause.replace(/\{[^}]*\}/, "").replace(/,/g, " ").trim();
if (/\*/.test(outside)) set.add("*");
else if (outside) set.add("default");
for (const part of braces ? braces[1].split(",") : []) {
const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim();
if (name) set.add(name);
}
if (!braces && !outside) set.add("*");
}
return names;
}

/** The files an import reaches: one file, or for a package root the files declaring `names`. */
function resolveImport(tree, packages, from, specifier, names) {
if (specifier.startsWith(".")) {
return resolveFile(tree, path.posix.join(path.posix.dirname(from), specifier));
const target = resolveFile(tree, path.posix.join(path.posix.dirname(from), specifier));
return target ? [target] : [];
}
const scoped = specifier.match(/^(@[^/]+\/[^/]+)\/(.+)$/);
const pkg = scoped && packages.get(scoped[1]);
if (!pkg || !pkg.exports || typeof pkg.exports !== "object") return undefined;
const entry = pkg.exports[`./${scoped[2]}`];
const parts = specifier.match(/^(@[^/]+\/[^/]+)(?:\/(.+))?$/);
const pkg = parts && packages.get(parts[1]);
if (!pkg || !pkg.exports) return [];
const exports =
typeof pkg.exports === "string" || "import" in pkg.exports || "default" in pkg.exports
? { ".": pkg.exports }
: pkg.exports;
const entry = exports[parts[2] ? `./${parts[2]}` : "."];
const target =
typeof entry === "string" ? entry : entry && (entry.import ?? entry.default ?? entry.types);
return typeof target === "string"
? resolveFile(tree, path.posix.join(pkg.dir, target))
: undefined;
const file =
typeof target === "string" ? resolveFile(tree, path.posix.join(pkg.dir, target)) : undefined;
if (!file) return [];
if (parts[2] || !names || names.has("*") || names.has("default")) return [file];
const found = new Set();
for (const name of names) declaringFiles(tree, packages, file, name, found, new Set());
return [...found];
}

/** Follows `export * from` and `export { name } from` until a file declares `name`. */
function declaringFiles(tree, packages, file, name, found, seen) {
if (seen.has(`${file}\0${name}`)) return;
seen.add(`${file}\0${name}`);
const text = tree.read(file);
const word = name.replace(/\$/g, "\\$");
const declares = new RegExp(
String.raw`\bexport\s+(?:declare\s+)?(?:abstract\s+)?(?:const|let|var|function\*?|class|type|interface|enum|namespace)\s+${word}(?![\w$])`,
);
const local = [...text.matchAll(/\bexport\s+(?:type\s+)?\{([^}]*)\}(?!\s*from)/g)].some(
(match) => match[1].split(",").some((part) => part.trim().split(/\s+as\s+/).pop() === name),
);
if (declares.test(text) || local) {
found.add(file);
return;
}
for (const match of text.matchAll(
/\bexport\s+(?:type\s+)?(\*(?:\s+as\s+([\w$]+))?|\{[^}]*\})\s*from\s*["']([^"'\n]+)["']/g,
)) {
const [, clause, namespace, specifier] = match;
const targets = resolveImport(tree, packages, file, specifier, new Set(["*"]));
if (clause.startsWith("*") && !namespace) {
for (const target of targets) declaringFiles(tree, packages, target, name, found, seen);
continue;
}
const exported = namespace
? namespace === name && "*"
: clause
.slice(1, -1)
.split(",")
.map((part) => part.trim().replace(/^type\s+/, "").split(/\s+as\s+/))
.find((pair) => (pair[1] ?? pair[0]).trim() === name)?.[0]
.trim();
if (!exported) continue;
for (const target of targets) {
if (exported === "*") found.add(target);
else declaringFiles(tree, packages, target, exported, found, seen);
}
}
}

function resolveFile(tree, file) {
Expand All @@ -99,15 +195,31 @@ function resolveFile(tree, file) {
}

/**
* @param {ReadonlyArray<{ path: string; before?: string; after?: string }>} changes
* one entry per changed path; `before`/`after` are the file texts (undefined when absent)
* @param {{ closure: ReadonlySet<string>; baseHasCheck: boolean }} context
* @param {ReadonlyArray<{ path: string; before?: string; after?: string; sameAsBase?: boolean }>} changes
* one entry per path the branch changes since the merge-base; `before`/`after` are the file
* texts (undefined when absent); `sameAsBase` says the branch's copy equals the base's copy
* @param {{ closure: ReadonlySet<string>; baseHasCheck: boolean; staleCommits?: number }} context
* `staleCommits`: the branch's commits that the base already holds as rebased copies
* @returns {string[]} one reason per refused file
*/
function findSchemaChanges(changes, { closure, baseHasCheck }) {
function findSchemaChanges(changes, { closure, baseHasCheck, staleCommits = 0 }) {
const reasons = [];
const rebase =
"this branch is based on an old main that has since been rebased; rebase it onto main";
if (staleCommits > 0) {
reasons.push(
`${staleCommits} commit(s) of this branch are already on main as rebased copies, so ${rebase}.`,
);
}
for (const change of changes) {
const file = change.path;
const guarded = CHECK_FILES.includes(file) || GITATTRIBUTES.test(file);
// The branch carries main's copy (e.g. it branched before main was rebased): nothing to judge.
if (guarded && change.sameAsBase) continue;
if (guarded && staleCommits > 0) {
reasons.push(`${file}: differs from main's copy because ${rebase}.`);
continue;
}
if (CHECK_FILES.includes(file)) {
if (baseHasCheck) {
reasons.push(
Expand All @@ -130,11 +242,11 @@ function findSchemaChanges(changes, { closure, baseHasCheck }) {
}
if (!isShippedSource(file)) continue;
const statement = [change.after, change.before]
.map((text) => text?.match(SCHEMA_STATEMENT)?.[0])
.map(schemaStatement)
.find(Boolean);
if (statement) {
reasons.push(
`${file}: holds a schema statement (${statement.replace(/\s+/g, " ")}), so any change ` +
`${file}: holds a schema statement (${statement.replace(/[^\w${}]+/g, " ")}), so any change ` +
"to it may change the schema",
);
}
Expand All @@ -149,9 +261,13 @@ function findSchemaChanges(changes, { closure, baseHasCheck }) {
function parseRawDiff(raw) {
const fields = raw.split("\0");
const entries = [];
for (let index = 0; index + 1 < fields.length; index += 2) {
if (fields.at(-1) === "") fields.pop();
if (fields.length % 2 !== 0) throw new Error("cannot parse git diff --raw output (odd fields)");
for (let index = 0; index < fields.length; index += 2) {
const header = fields[index];
if (!header.startsWith(":")) break;
if (!/^:\d+ \d+ [0-9a-f]+ [0-9a-f]+ [A-Z]\d*$/.test(header)) {
throw new Error(`cannot parse git diff --raw record: ${JSON.stringify(header)}`);
}
const [oldMode, newMode, oldSha, newSha, status] = header.slice(1).split(" ");
if (/^[RC]/.test(status)) throw new Error(`unexpected rename in diff: ${header}`);
const blob = (mode, sha) => (/^10|^12/.test(mode) && !/^0+$/.test(sha) ? sha : undefined);
Expand Down Expand Up @@ -194,7 +310,27 @@ function readBlob(sha) {
}

function treeHas(rev, file) {
return git(["ls-tree", "--full-tree", "--name-only", rev, "--", file]).trim() === file;
return blobAt(rev, file) !== undefined;
}

/** The blob id of `file` in `rev`, or undefined when absent. */
function blobAt(rev, file) {
const record = git(["ls-tree", "-z", "--full-tree", rev, "--", file]).split("\0")[0];
const match = record.match(/^\d+ \w+ ([0-9a-f]+)\t(.+)$/s);
return match && match[2] === file ? match[1] : undefined;
}

/**
* The branch's commits (merge-base..head) that the base already holds as rebased copies, matched
* by author, author time and subject: a rebase keeps all three. Needs no file contents.
*/
function staleCommitCount(mergeBase, base, head) {
const ids = (range) =>
git(["log", "--no-merges", "--format=%an%x00%ae%x00%at%x00%s", range])
.split("\n")
.filter(Boolean);
const onBase = new Set(ids(`${mergeBase}..${base}`));
return ids(`${mergeBase}..${head}`).filter((id) => onBase.has(id)).length;
}

function main(argv) {
Expand All @@ -209,10 +345,12 @@ function main(argv) {
);
// Only shipped source is searched for statements, so only its texts are read.
const text = (entry, sha) => (sha && isShippedSource(entry.path) ? readBlob(sha) : undefined);
const guarded = (file) => CHECK_FILES.includes(file) || GITATTRIBUTES.test(file);
const changes = entries.map((entry) => ({
path: entry.path,
before: text(entry, entry.oldBlob),
after: text(entry, entry.newBlob),
sameAsBase: guarded(entry.path) ? blobAt(base, entry.path) === entry.newBlob : undefined,
}));
const closure = new Set([
...schemaClosure(readTree(mergeBase)),
Expand All @@ -221,6 +359,7 @@ function main(argv) {
const reasons = findSchemaChanges(changes, {
closure,
baseHasCheck: treeHas(base, CHECK_SCRIPT),
staleCommits: staleCommitCount(mergeBase, base, head),
});
if (reasons.length === 0) {
console.log(`No database schema changes (${changes.length} changed files checked).`);
Expand All @@ -231,7 +370,7 @@ function main(argv) {
return 1;
}

module.exports = { findSchemaChanges, parseRawDiff, schemaClosure, CHECK_FILES };
module.exports = { findSchemaChanges, parseRawDiff, schemaClosure, CHECK_FILES, schemaStatement };

if (require.main === module) {
process.exitCode = main(process.argv.slice(2));
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.