#!/usr/bin/env bun
/**
* Generates src/server/scoped-db/schema.gen.ts: the DDL each scoped Durable Object (RepoState, AccountState)
* creates in its own SQLite, derived from the D1 migrations, plus the SQL that selects one scope's rows from
* D1 for the one-time import. Foreign keys to tables that live elsewhere are dropped (the referenced row is in
* another object or the D1 directory); keys within a scope are kept.
*
* bun scripts/gen-scoped-schema.ts
*/
import { Database } from "bun:sqlite";
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
const ROOT = join(import.meta.dir, "..");
/**
* Access and social edges stay in the D1 directory on purpose: `collaborators`, `org_members`, `stars`,
* `watches` and `follows` are what "which repositories can this user see" and the social lists are computed
* from, and they are lookups rather than repository or account data.
*/
const SITE_IN_SCOPE = "site_id IN (SELECT id FROM sites WHERE repo_id = ?1 OR 'site:' || id = ?1)";
const IN_ISSUE = "issue_id IN (SELECT id FROM issues WHERE repo_id = ?1)";
/** Table → D1 WHERE clause selecting one repository's rows (`?1` is the repo id). */
export const REPO_TABLES: Record<string, string> = {
issues: "repo_id = ?1",
issues_fts: "repo_id = ?1",
comments: IN_ISSUE,
issue_events: IN_ISSUE,
labels: "repo_id = ?1",
issue_labels: IN_ISSUE,
milestones: "repo_id = ?1",
issue_types: "repo_id = ?1",
issue_assignees: IN_ISSUE,
pinned_issues: "repo_id = ?1",
reactions: `(subject_type IN ('issue') AND subject_id IN (SELECT id FROM issues WHERE repo_id = ?1))
OR (subject_type = 'comment' AND subject_id IN (SELECT c.id FROM comments c JOIN issues i ON i.id = c.issue_id WHERE i.repo_id = ?1))
OR (subject_type = 'review_comment' AND subject_id IN (SELECT rc.id FROM review_comments rc JOIN issues i ON i.id = rc.issue_id WHERE i.repo_id = ?1))
OR (subject_type IN ('discussion', 'discussion_comment') AND subject_id IN (
SELECT id FROM discussions WHERE repo_id = ?1
UNION SELECT dc.id FROM discussion_comments dc JOIN discussions d ON d.id = dc.discussion_id WHERE d.repo_id = ?1))`,