Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .agents/skills/graphile-meta/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
}
}
Expand Down Expand Up @@ -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).

Expand Down
63 changes: 63 additions & 0 deletions graphile/graphile-meta/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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 }
}
}
}
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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
}
}
}
}"
Expand All @@ -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": [
{
Expand Down Expand Up @@ -533,6 +556,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
},
"unique": [],
},
"derivedFrom": null,
"description": null,
"fields": [
{
Expand Down Expand Up @@ -1069,6 +1093,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
"uniqueConstraints": [],
},
{
"companions": [],
"constraints": {
"foreignKey": [
{
Expand Down Expand Up @@ -1183,6 +1208,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
},
"unique": [],
},
"derivedFrom": null,
"description": null,
"fields": [
{
Expand Down Expand Up @@ -2148,6 +2174,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
"uniqueConstraints": [],
},
{
"companions": [],
"constraints": {
"foreignKey": [
{
Expand Down Expand Up @@ -2366,6 +2393,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
},
"unique": [],
},
"derivedFrom": null,
"description": null,
"fields": [
{
Expand Down Expand Up @@ -2905,6 +2933,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
"uniqueConstraints": [],
},
{
"companions": [],
"constraints": {
"foreignKey": [],
"primaryKey": {
Expand Down Expand Up @@ -2978,6 +3007,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
},
],
},
"derivedFrom": null,
"description": null,
"fields": [
{
Expand Down Expand Up @@ -3665,6 +3695,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
],
},
{
"companions": [],
"constraints": {
"foreignKey": [],
"primaryKey": {
Expand Down Expand Up @@ -3738,6 +3769,7 @@ exports[`MetaSchemaPlugin snapshot scenarios produces stable metadata for a mult
},
],
},
"derivedFrom": null,
"description": null,
"fields": [
{
Expand Down
71 changes: 70 additions & 1 deletion graphile/graphile-meta/__tests__/meta-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,8 @@ query MetaContract {
entityTable
source
}
derivedFrom { kind name tableName schemaName }
companions { kind name tableName schemaName }
}
}
}
Expand Down Expand Up @@ -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[] {
Expand Down Expand Up @@ -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({
Expand Down
64 changes: 64 additions & 0 deletions graphile/graphile-meta/src/companion-meta-builders.ts
Original file line number Diff line number Diff line change
@@ -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<string, TableMeta>();
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));
}
}
Loading
Loading