diff --git a/.agents/skills/graphile-meta/SKILL.md b/.agents/skills/graphile-meta/SKILL.md index 25ebda2cd6..1704b4b36f 100644 --- a/.agents/skills/graphile-meta/SKILL.md +++ b/.agents/skills/graphile-meta/SKILL.md @@ -64,6 +64,8 @@ query { search { algorithms columns { name algorithm } hasUnifiedSearch config { boostRecent } } i18n { translationTable translatableFields { name type } } realtime { subscriptionFieldName } + derivedFrom { kind name tableName schemaName } + companions { kind name tableName schemaName } } } } @@ -105,6 +107,7 @@ MetaSchemaPlugin (plugin.ts) | **search** (algorithms, columns, unified, config) | `storage-search-meta-builders.ts` `buildSearchMeta` | tsvector/vector columns, `@bm25Index`, `@trgmSearch`, `@searchConfig` | | **i18n** (translation table, translatable fields) | `storage-search-meta-builders.ts` `buildI18nMeta` | `@i18n` tag + text/citext column intersection | | **realtime** (subscription field name) | `storage-search-meta-builders.ts` `buildRealtimeMeta` | `@realtime` tag | +| **derivedFrom / companions** (companion table links) | `companion-meta-builders.ts` `linkCompanionTables` (run in `collectTablesMeta`) | `@derivedFrom {kind, table, schema}` tag on the companion | The type contracts for all of these live in `types.ts` (`TableMeta` and friends). diff --git a/graphile/graphile-meta/README.md b/graphile/graphile-meta/README.md index 0e38e6758a..7ff67e6d00 100644 --- a/graphile/graphile-meta/README.md +++ b/graphile/graphile-meta/README.md @@ -25,6 +25,7 @@ Standard GraphQL introspection tells you about the GraphQL schema — `_meta` ad - **Inflection** — the type names and root field names PostGraphile generated (`tableType`, `allRows`, `connection`, `createInputType`, …) - **Root operations** — the query/mutation names for `all`, `one`, `create`, `update`, `delete` - **Feature metadata from smart tags** — `storage` (`@storageFiles` / `@storageBuckets`), `search` (tsvector/BM25/pg_trgm/pgvector columns), `i18n` (translation tables and translatable fields), and `realtime` (subscription field names) +- **Companion tables** — `derivedFrom` and `companions` link a history, translation, chunks or realtime subscriber table to the table it belongs to (`@derivedFrom` tag) The first `_meta` execution reconciles metadata against that request's final schema; subsequent requests for the same schema return the cached result. Schema construction also seeds the legacy metadata cache for existing codegen consumers. @@ -84,6 +85,8 @@ query { search { algorithms columns { name algorithm } hasUnifiedSearch } i18n { translationTable translatableFields { name type } } realtime { subscriptionFieldName } + derivedFrom { kind name tableName schemaName } + companions { kind name tableName schemaName } } } } @@ -116,6 +119,66 @@ Example response snippet: operation under `query` is `null` when that field was not emitted in the final GraphQL schema. +### Companion tables + +Some tables exist only to serve another table: its row history, its +translations, its embedding chunks, its realtime subscribers. `_meta` links +each of these **companions** to the **primary table** it belongs to, so a UI +can group them without guessing from table names (`posts_history`, +`posts_chunks`, ...). + +```graphql +query { + _meta { + tables { + name + derivedFrom { kind name } + companions { kind name } + } + } +} +``` + +```json +[ + { "name": "Post", "derivedFrom": null, + "companions": [ + { "kind": "history", "name": "PostHistory" }, + { "kind": "embedding_chunks", "name": "PostChunk" } + ] }, + { "name": "PostHistory", "derivedFrom": { "kind": "history", "name": "Post" }, "companions": [] }, + { "name": "PostChunk", "derivedFrom": { "kind": "embedding_chunks", "name": "Post" }, "companions": [] } +] +``` + +- **Primary tables** have `derivedFrom: null`. Show these as the top-level + list (navigation, table pickers). +- **A companion** has `derivedFrom` set to the table it belongs to. Show it + under that table, or hide it, instead of beside it. +- **`companions`** on a primary table lists its companions; it is `derivedFrom` + read from the other side, so either one gives the same grouping. +- **`kind`** says what the companion holds. Match on it as served: + `history`, `i18n`, `embedding_chunks`, `realtime`. New kinds can appear, so + treat an unknown kind as a generic companion rather than an error. +- **`name`** is the linked table's GraphQL type name, the same as `tables.name`, + so it is the key to look the other table up in the same response; + `tableName` / `schemaName` give its PostgreSQL identity. +- A link to a table this API does not expose is left out, so every + `derivedFrom` / `companions` entry names a table present in `tables`. + +This is not a foreign-key relation (those are in `relations`): a companion +link says the table is part of another table, not that its rows point at it. + +```typescript +const byName = new Map(tables.map((t) => [t.name, t])); +const primaryTables = tables.filter((t) => !t.derivedFrom); +const companionsOf = (table) => table.companions.map((c) => ({ ...c, table: byName.get(c.name) })); +``` + +The link comes from the database: constructive-db records each companion in +`metaschema_public.derives` and stamps a `@derivedFrom {kind, table, schema}` +smart tag on the companion table, which this plugin reads. + ### Form metadata These fields let a generic client build correct create and edit forms from `_meta` alone. Their GraphQL descriptions are public copy that says only what a client may rely on; the rules below are how the values are derived. diff --git a/graphile/graphile-meta/__tests__/__snapshots__/meta-schema.test.ts.snap b/graphile/graphile-meta/__tests__/__snapshots__/meta-schema.test.ts.snap index 8de09a5a59..55d5d8d104 100644 --- a/graphile/graphile-meta/__tests__/__snapshots__/meta-schema.test.ts.snap +++ b/graphile/graphile-meta/__tests__/__snapshots__/meta-schema.test.ts.snap @@ -2,6 +2,11 @@ exports[`MetaSchemaPlugin _meta query contract contains required selection paths 1`] = ` [ + "companions", + "companions.kind", + "companions.name", + "companions.schemaName", + "companions.tableName", "constraints", "constraints.foreignKey", "constraints.foreignKey.fields", @@ -15,6 +20,11 @@ exports[`MetaSchemaPlugin _meta query contract contains required selection paths "constraints.primaryKey.name", "constraints.unique", "constraints.unique.name", + "derivedFrom", + "derivedFrom.kind", + "derivedFrom.name", + "derivedFrom.schemaName", + "derivedFrom.tableName", "fields", "fields.columnName", "fields.enumValues", @@ -337,6 +347,18 @@ exports[`MetaSchemaPlugin _meta query contract has stable printed GraphQL text 1 entityTable source } + derivedFrom { + kind + name + tableName + schemaName + } + companions { + kind + name + tableName + schemaName + } } } }" @@ -345,6 +367,7 @@ exports[`MetaSchemaPlugin _meta query contract has stable printed GraphQL text 1 exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a multi-table scenario 1`] = ` [ { + "companions": [], "constraints": { "foreignKey": [ { @@ -533,6 +556,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult }, "unique": [], }, + "derivedFrom": null, "description": null, "fields": [ { @@ -1069,6 +1093,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult "uniqueConstraints": [], }, { + "companions": [], "constraints": { "foreignKey": [ { @@ -1183,6 +1208,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult }, "unique": [], }, + "derivedFrom": null, "description": null, "fields": [ { @@ -2148,6 +2174,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult "uniqueConstraints": [], }, { + "companions": [], "constraints": { "foreignKey": [ { @@ -2366,6 +2393,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult }, "unique": [], }, + "derivedFrom": null, "description": null, "fields": [ { @@ -2905,6 +2933,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult "uniqueConstraints": [], }, { + "companions": [], "constraints": { "foreignKey": [], "primaryKey": { @@ -2978,6 +3007,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult }, ], }, + "derivedFrom": null, "description": null, "fields": [ { @@ -3665,6 +3695,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult ], }, { + "companions": [], "constraints": { "foreignKey": [], "primaryKey": { @@ -3738,6 +3769,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult }, ], }, + "derivedFrom": null, "description": null, "fields": [ { diff --git a/graphile/graphile-meta/__tests__/meta-schema.test.ts b/graphile/graphile-meta/__tests__/meta-schema.test.ts index 2cd8b4ac0c..c5c3a2721f 100644 --- a/graphile/graphile-meta/__tests__/meta-schema.test.ts +++ b/graphile/graphile-meta/__tests__/meta-schema.test.ts @@ -437,6 +437,8 @@ query MetaContract { entityTable source } + derivedFrom { kind name tableName schemaName } + companions { kind name tableName schemaName } } } } @@ -535,7 +537,15 @@ const REQUIRED_META_QUERY_PATHS = [ 'scope.tier', 'scope.keyColumn', 'scope.entityTable', - 'scope.source' + 'scope.source', + 'derivedFrom.kind', + 'derivedFrom.name', + 'derivedFrom.tableName', + 'derivedFrom.schemaName', + 'companions.kind', + 'companions.name', + 'companions.tableName', + 'companions.schemaName' ]; function collectSelectionPaths(selections: readonly SelectionNode[], prefix = ''): string[] { @@ -2574,6 +2584,65 @@ describe('MetaSchemaPlugin', () => { }); }); + describe('companion tables', () => { + const tagged = (name: string, derivedFrom: unknown) => ({ + ...createMockCodec(name, { id: createMockAttribute('uuid') }), + extensions: { pg: { schemaName: 'app_public', name }, tags: { derivedFrom } } + }); + + it('links a companion to its source from the @derivedFrom tag', () => { + const build = createMockBuild({ + post: { codec: createMockCodec('post', { id: createMockAttribute('uuid') }) }, + post_history: { + codec: tagged('post_history', JSON.stringify({ kind: 'history', table: 'post', schema: 'app_public' })) + }, + post_chunks: { + codec: tagged('post_chunks', { kind: 'embedding_chunks', table: 'post', schema: 'app_public' }) + } + }); + const tables = callInitHook(build); + const post = tables.find((t: any) => t.tableName === 'post'); + const history = tables.find((t: any) => t.tableName === 'post_history'); + + expect(post.derivedFrom).toBeNull(); + expect(history.derivedFrom).toEqual({ + kind: 'history', name: post.name, tableName: 'post', schemaName: 'app_public' + }); + expect(post.companions.map((c: any) => [c.kind, c.tableName])).toEqual([ + ['history', 'post_history'], + ['embedding_chunks', 'post_chunks'] + ]); + expect(history.companions).toEqual([]); + }); + + it('leaves out a link to a table the API does not expose', () => { + const build = createMockBuild({ + post_history: { + codec: tagged('post_history', { kind: 'history', table: 'post', schema: 'app_private' }) + } + }); + expect(callInitHook(build)[0].derivedFrom).toBeNull(); + }); + + it('keeps schema and table apart when they contain dots', () => { + const build = createMockBuild({ + 'post.history': { codec: createMockCodec('post.history', { id: createMockAttribute('uuid') }) }, + history: { + codec: tagged('history', { kind: 'history', table: 'history', schema: 'app_public.post' }) + } + }); + const history = callInitHook(build).find((t: any) => t.tableName === 'history'); + expect(history.derivedFrom).toBeNull(); + }); + + it('rejects a malformed @derivedFrom tag', () => { + const build = createMockBuild({ + post_history: { codec: tagged('post_history', 'post') } + }); + expect(() => callInitHook(build)).toThrow(/@derivedFrom tag/); + }); + }); + describe('i18n metadata', () => { it('returns null i18n for tables without @i18n tag', () => { const build = createMockBuild({ diff --git a/graphile/graphile-meta/src/companion-meta-builders.ts b/graphile/graphile-meta/src/companion-meta-builders.ts new file mode 100644 index 0000000000..ecf45cb7b4 --- /dev/null +++ b/graphile/graphile-meta/src/companion-meta-builders.ts @@ -0,0 +1,64 @@ +import type { PgCodec, RelatedTableMeta, TableMeta } from './types'; + +interface DerivedFromTag { + kind: string; + table: string; + schema: string; +} + +/** + * Read a companion table's `@derivedFrom` smart tag. + * + * constructive-db stamps it from `metaschema_public.derives`, the record of + * which table a companion (history, translations, chunks, realtime + * subscribers) belongs to, as `{ kind, table, schema }`. A table without the + * tag is a primary table. + */ +function readDerivedFromTag(codec: PgCodec): DerivedFromTag | null { + const raw = (codec as any).extensions?.tags?.derivedFrom; + if (raw == null) return null; + + let parsed: any = raw; + if (typeof raw === 'string') { + try { + parsed = JSON.parse(raw); + } catch { + parsed = null; + } + } + + const { kind, table, schema } = parsed ?? {}; + if (typeof kind !== 'string' || typeof table !== 'string' || typeof schema !== 'string') { + throw new Error( + `@derivedFrom tag on codec "${codec.name}" must be {kind, table, schema}, got ${JSON.stringify(raw)}` + ); + } + return { kind, table, schema }; +} + +function relatedTable(kind: string, meta: TableMeta): RelatedTableMeta { + return { kind, name: meta.name, tableName: meta.tableName, schemaName: meta.schemaName }; +} + +/** + * Link every companion to the table it derives from: `derivedFrom` on the + * companion, and the inverse `companions` on the source, so the link is read + * once and reported from both sides. A link to a table this API does not + * expose is left out. + */ +export function linkCompanionTables(built: { codec: PgCodec; meta: TableMeta }[]): void { + const sqlKey = (schema: string, table: string) => JSON.stringify([schema, table]); + const bySqlName = new Map(); + for (const { meta } of built) { + bySqlName.set(sqlKey(meta.schemaName, meta.tableName), meta); + } + + for (const { codec, meta } of built) { + const tag = readDerivedFromTag(codec); + if (!tag) continue; + const source = bySqlName.get(sqlKey(tag.schema, tag.table)); + if (!source) continue; + meta.derivedFrom = relatedTable(tag.kind, source); + source.companions.push(relatedTable(tag.kind, meta)); + } +} diff --git a/graphile/graphile-meta/src/graphql-meta-field.ts b/graphile/graphile-meta/src/graphql-meta-field.ts index 8d4c5323cc..d3958e028c 100644 --- a/graphile/graphile-meta/src/graphql-meta-field.ts +++ b/graphile/graphile-meta/src/graphql-meta-field.ts @@ -425,6 +425,17 @@ function createMetaSchemaType(): GraphQLObjectType { }) }); + const MetaRelatedTableType = new GraphQLObjectType({ + name: 'MetaRelatedTable', + description: 'A companion link between two tables (history, translations, chunks, realtime subscribers)', + fields: () => ({ + kind: { type: nn(GraphQLString), description: "What the companion holds for its table ('history', 'i18n', 'embedding_chunks', 'realtime', ...)" }, + name: { type: nn(GraphQLString), description: 'GraphQL type name of the linked table' }, + tableName: { type: nn(GraphQLString), description: 'PostgreSQL name of the linked table' }, + schemaName: { type: nn(GraphQLString) } + }) + }); + const MetaTableType = new GraphQLObjectType({ name: 'MetaTable', description: 'Information about a database table', @@ -460,6 +471,8 @@ function createMetaSchemaType(): GraphQLObjectType { i18n: { type: MetaI18nType, description: 'i18n metadata (null if the table is not translatable)' }, realtime: { type: MetaRealtimeType, description: 'Realtime metadata (null if the table has no change subscriptions)' }, scope: { type: MetaScopeType, description: 'Provisioning scope metadata (null if the table has no scope)' }, + derivedFrom: { type: MetaRelatedTableType, description: 'The table this one is a companion of (null for a primary table)' }, + companions: { type: nnList(MetaRelatedTableType), description: 'Companion tables that belong to this one (empty for a companion or a table without companions)' }, isJunction: { type: nn(GraphQLBoolean), description: diff --git a/graphile/graphile-meta/src/table-meta-builder.ts b/graphile/graphile-meta/src/table-meta-builder.ts index 5d39ce2d6e..f83f53a97f 100644 --- a/graphile/graphile-meta/src/table-meta-builder.ts +++ b/graphile/graphile-meta/src/table-meta-builder.ts @@ -6,6 +6,7 @@ import { isNonNullType } from 'graphql'; +import { linkCompanionTables } from './companion-meta-builders'; import { buildForeignKeyConstraints, buildIndexes, @@ -230,7 +231,9 @@ function buildTableMeta( i18n, realtime, scope, - // Settled in collectTablesMeta once every table's relations are built. + // Settled in collectTablesMeta once every table is built. + derivedFrom: null, + companions: [], isJunction: false }; } @@ -282,5 +285,6 @@ export function collectTablesMeta( for (const { codec, meta } of built) { meta.isJunction = context.emittedJunctions.has(codec); } + linkCompanionTables(built); return built.map(({ meta }) => meta); } diff --git a/graphile/graphile-meta/src/types.ts b/graphile/graphile-meta/src/types.ts index ee6ade471e..d5fd2794da 100644 --- a/graphile/graphile-meta/src/types.ts +++ b/graphile/graphile-meta/src/types.ts @@ -25,6 +25,10 @@ export interface TableMeta { i18n: I18nMeta | null; realtime: RealtimeMeta | null; scope: ScopeMeta | null; + /** The table this one is a companion of, or null for a primary table. */ + derivedFrom: RelatedTableMeta | null; + /** The companion tables derived from this one. */ + companions: RelatedTableMeta[]; /** * Whether a reported many-to-many relation names this table as its junction, * either one the many-to-many plugin declares or one detected by @@ -131,6 +135,20 @@ export interface I18nMeta { translatableFields: I18nFieldMeta[]; } +/** + * A companion link between two tables: a history, translation, chunks or + * realtime subscriber table and the table it derives from. + */ +export interface RelatedTableMeta { + /** How the companion derives from its source ('history', 'i18n', 'embedding_chunks', 'realtime', ...) */ + kind: string; + /** GraphQL type name of the linked table */ + name: string; + /** PostgreSQL name of the linked table */ + tableName: string; + schemaName: string; +} + export interface RealtimeMeta { /** The generated subscription field name (e.g. onPostChanged) */ subscriptionFieldName: string; diff --git a/graphql/server-test/__tests__/__snapshots__/schema-snapshot.test.ts.snap b/graphql/server-test/__tests__/__snapshots__/schema-snapshot.test.ts.snap index eee794f27a..655c09014d 100644 --- a/graphql/server-test/__tests__/__snapshots__/schema-snapshot.test.ts.snap +++ b/graphql/server-test/__tests__/__snapshots__/schema-snapshot.test.ts.snap @@ -889,6 +889,23 @@ type MetaRefTable { name: String! } +""" +A companion link between two tables (history, translations, chunks, realtime subscribers) +""" +type MetaRelatedTable { + """ + What the companion holds for its table ('history', 'i18n', 'embedding_chunks', 'realtime', ...) + """ + kind: String! + + """GraphQL type name of the linked table""" + name: String! + schemaName: String! + + """PostgreSQL name of the linked table""" + tableName: String! +} + """Table relations""" type MetaRelations { belongsTo: [MetaBelongsToRelation!]! @@ -1046,8 +1063,15 @@ type MetaStorageUpload { """Information about a database table""" type MetaTable { + """ + Companion tables that belong to this one (empty for a companion or a table without companions) + """ + companions: [MetaRelatedTable!]! constraints: MetaConstraints! + """The table this one is a companion of (null for a primary table)""" + derivedFrom: MetaRelatedTable + """Description written for this table, or null""" description: String fields: [MetaField!]! diff --git a/graphql/test/__tests__/__snapshots__/graphile-test.test.ts.snap b/graphql/test/__tests__/__snapshots__/graphile-test.test.ts.snap index a8baac2d61..1cbb7e65be 100644 --- a/graphql/test/__tests__/__snapshots__/graphile-test.test.ts.snap +++ b/graphql/test/__tests__/__snapshots__/graphile-test.test.ts.snap @@ -1539,6 +1539,42 @@ based pagination. May not be used with \`last\`.", "ofType": null, }, }, + { + "args": [], + "deprecationReason": null, + "description": "The table this one is a companion of (null for a primary table)", + "isDeprecated": false, + "name": "derivedFrom", + "type": { + "kind": "OBJECT", + "name": "MetaRelatedTable", + "ofType": null, + }, + }, + { + "args": [], + "deprecationReason": null, + "description": "Companion tables that belong to this one (empty for a companion or a table without companions)", + "isDeprecated": false, + "name": "companions", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "OBJECT", + "name": "MetaRelatedTable", + "ofType": null, + }, + }, + }, + }, + }, { "args": [], "deprecationReason": null, @@ -4058,6 +4094,81 @@ based pagination. May not be used with \`last\`.", "name": "MetaScope", "possibleTypes": null, }, + { + "description": "A companion link between two tables (history, translations, chunks, realtime subscribers)", + "enumValues": null, + "fields": [ + { + "args": [], + "deprecationReason": null, + "description": "What the companion holds for its table ('history', 'i18n', 'embedding_chunks', 'realtime', ...)", + "isDeprecated": false, + "name": "kind", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null, + }, + }, + }, + { + "args": [], + "deprecationReason": null, + "description": "GraphQL type name of the linked table", + "isDeprecated": false, + "name": "name", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null, + }, + }, + }, + { + "args": [], + "deprecationReason": null, + "description": "PostgreSQL name of the linked table", + "isDeprecated": false, + "name": "tableName", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null, + }, + }, + }, + { + "args": [], + "deprecationReason": null, + "description": null, + "isDeprecated": false, + "name": "schemaName", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null, + }, + }, + }, + ], + "inputFields": null, + "interfaces": [], + "kind": "OBJECT", + "name": "MetaRelatedTable", + "possibleTypes": null, + }, { "description": "The root mutation type which contains root level fields which mutate data.", "enumValues": null,