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
Original file line number Diff line number Diff line change
Expand Up @@ -553,9 +553,13 @@ export type InferSelectResult<TEntity, TSelect> = TSelect extends undefined
? K extends keyof TEntity
? NonNullable<TEntity[K]> extends ConnectionResult<infer NodeType>
? ConnectionResult<InferSelectResult<NodeType, NestedSelect>>
:
| InferSelectResult<NonNullable<TEntity[K]>, NestedSelect>
| (null extends TEntity[K] ? null : never)
: NonNullable<TEntity[K]> extends readonly (infer Item)[]
?
| InferSelectResult<NonNullable<Item>, NestedSelect>[]
| (null extends TEntity[K] ? null : never)
:
| InferSelectResult<NonNullable<TEntity[K]>, NestedSelect>
| (null extends TEntity[K] ? null : never)
: never
: K extends keyof TEntity
? TEntity[K]
Expand Down
120 changes: 120 additions & 0 deletions graphql/codegen/src/__tests__/codegen/cli-generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
Relations,
Table,
TypeRef,
TypeRegistry,
} from '../../types/schema';

const fieldTypes = {
Expand Down Expand Up @@ -281,6 +282,125 @@ describe('cli-generator without a create mutation', () => {
});
});

// A table shaped like the storage `File` type: no create mutation, a computed
// field that takes arguments, and computed fields with and without an object
// return type. None of the computed fields are in the patch type.
const computedFileTable = createTable({
name: 'Asset',
fields: [
{ name: 'id', type: fieldTypes.uuid },
{ name: 'filename', type: fieldTypes.string },
{ name: 'search', type: { gqlType: 'FullText', isArray: false } },
{ name: 'searchTsvRank', type: { gqlType: 'Float', isArray: false } },
{ name: 'downloadUrl', type: fieldTypes.string },
{
name: 'uploadUrl',
type: fieldTypes.string,
args: [{ name: 'width', type: createTypeRef('SCALAR', 'Int'), isRequired: false }],
},
{ name: 'uploadVersions', type: { gqlType: 'AssetVersion', isArray: true } },
],
query: {
all: 'assets',
one: 'asset',
create: null,
update: 'updateAsset',
delete: 'deleteAsset',
},
});

const computedFileRegistry: TypeRegistry = new Map([
[
'AssetPatch',
{
kind: 'INPUT_OBJECT',
name: 'AssetPatch',
inputFields: [
{ name: 'filename', type: createTypeRef('SCALAR', 'String') },
{ name: 'search', type: createTypeRef('SCALAR', 'FullText') },
],
},
],
[
'AssetVersion',
{
kind: 'OBJECT',
name: 'AssetVersion',
fields: [
{ name: 'url', type: createTypeRef('NON_NULL', null, createTypeRef('SCALAR', 'String')) },
{ name: 'width', type: createTypeRef('SCALAR', 'Int') },
],
},
],
]);

describe('cli-generator with computed fields', () => {
const generateAssetCommand = (typeRegistry?: TypeRegistry): string => {
const { files } = generateCli({
tables: [computedFileTable],
customOperations: { queries: [], mutations: [] },
config: { cli: { toolName: 'myapp' } },
typeRegistry,
});
return files.find((f) => f.fileName === 'commands/asset.ts')!.content;
};

it('never selects a field that takes arguments as `field: true`', () => {
expect(generateAssetCommand(computedFileRegistry)).not.toContain('uploadUrl: true');
expect(generateAssetCommand()).not.toContain('uploadUrl: true');
});

it('leaves computed fields out of the default select', () => {
const content = generateAssetCommand(computedFileRegistry);
expect(content).toContain('filename: true');
expect(content).not.toContain('downloadUrl: true');
expect(content).not.toContain('uploadVersions: true');
expect(content).not.toContain('searchTsvRank: true');
});

it('derives update fields from the patch type when there is no create input', () => {
const content = generateAssetCommand(computedFileRegistry);
expect(content).toContain('filename: cleanedData.filename');
expect(content).not.toContain('cleanedData.downloadUrl');
expect(content).not.toContain('cleanedData.uploadUrl');
expect(content).not.toContain('cleanedData.uploadVersions');
expect(content).not.toContain("name: 'uploadUrl'");
expect(content).not.toContain("name: 'uploadVersions'");
expect(content).not.toContain("name: 'downloadUrl'");
});

it('keeps computed fields out of docs examples', () => {
const docs = [
generateOrmReadme([computedFileTable], [], computedFileRegistry),
generateHooksReadme([computedFileTable], [], computedFileRegistry),
...generateOrmSkills([computedFileTable], [], 'default', computedFileRegistry),
...generateHooksSkills([computedFileTable], [], 'default', computedFileRegistry),
].map((f) => f.content);
for (const content of docs) {
expect(content).not.toContain('uploadUrl: true');
expect(content).not.toContain('uploadVersions: true');
expect(content).not.toContain('uploadUrl: \'');
}
expect(docs[0]).toMatch(/`uploadUrl` \| String \| No/);
expect(docs[0]).toMatch(/`downloadUrl` \| String \| No/);
});

it('references the real tsvector rank field in search examples', () => {
const readme = generateCliReadme(
[computedFileTable],
[],
'myapp',
computedFileRegistry,
).content;
// `filename` and `searchTsvRank` exist on the table; `title`, `tsvRank`
// and `searchScore` do not
expect(readme).toContain('--where.search "search query" --select filename,searchTsvRank');
expect(readme).toContain('--where.unifiedSearch "search query" --select filename,searchTsvRank');
expect(readme).toContain('--limit 10 --select id,filename');
expect(readme).not.toMatch(/--select \S*\b(title|tsvRank|searchScore)\b/);
});
});

describe('cli docs generator', () => {
it('generates CLI README', () => {
const readme = generateCliReadme([carTable, driverTable], allCustomOps, 'myapp');
Expand Down
104 changes: 104 additions & 0 deletions graphql/codegen/src/__tests__/codegen/computed-fields.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/**
* ORM types for computed fields: a field that takes arguments and/or returns
* an object type cannot be selected as `field: true`.
*/
import { generateInputTypesFile } from '../../core/codegen/orm/input-types-generator';
import type { Table, TypeRef, TypeRegistry } from '../../types/schema';

const ref = (kind: TypeRef['kind'], name: string | null, ofType?: TypeRef): TypeRef => ({
kind,
name,
ofType,
});

const assetTable: Table = {
name: 'Asset',
fields: [
{ name: 'id', type: { gqlType: 'UUID', isArray: false } },
{ name: 'filename', type: { gqlType: 'String', isArray: false } },
{
name: 'uploadUrl',
type: { gqlType: 'String', isArray: false },
args: [{ name: 'width', type: ref('SCALAR', 'Int'), isRequired: false }],
},
{ name: 'uploadVersions', type: { gqlType: 'AssetVersion', isArray: true } },
{
name: 'uploadVersion',
type: { gqlType: 'AssetVersion', isArray: false },
args: [{ name: 'name', type: ref('SCALAR', 'String'), isRequired: true }],
},
],
relations: { belongsTo: [], hasOne: [], hasMany: [], manyToMany: [] },
query: {
all: 'assets',
one: 'asset',
create: null,
update: 'updateAsset',
delete: 'deleteAsset',
},
};

const registry: TypeRegistry = new Map([
[
'AssetPatch',
{
kind: 'INPUT_OBJECT',
name: 'AssetPatch',
inputFields: [{ name: 'filename', type: ref('SCALAR', 'String') }],
},
],
[
'AssetVersion',
{
kind: 'OBJECT',
name: 'AssetVersion',
fields: [
{ name: 'url', type: ref('NON_NULL', null, ref('SCALAR', 'String')) },
{ name: 'width', type: ref('SCALAR', 'Int') },
],
},
],
]);

const normalize = (code: string): string => code.replace(/\s+/g, ' ');

describe('ORM types for computed fields', () => {
const content = normalize(
generateInputTypesFile(registry, new Set(), [assetTable]).content,
);
const selectStart = content.indexOf('export type AssetSelect = {');
const selectType = content.slice(
selectStart,
content.indexOf('export ', selectStart + 1),
);

it('types a field with arguments as { args, select? }', () => {
expect(selectType).toContain(
'uploadUrl?: { args: { width?: number; }; select?: Record<string, boolean>; };',
);
});

it('requires a sub-selection for a field returning an object type', () => {
expect(selectType).toContain('uploadVersions?: { select: AssetVersionSelect; };');
expect(selectType).not.toContain('uploadVersions?: boolean');
expect(selectType).toContain(
'uploadVersion?: { args: { name: string; }; select: AssetVersionSelect; };',
);
});

it('emits the object type and its Select type instead of an unknown alias', () => {
expect(content).toContain('export interface AssetVersion {');
expect(content).toContain('export type AssetVersionSelect = {');
expect(content).not.toContain('export type AssetVersion = unknown');
});

it('keeps computed fields out of the patch type', () => {
const patch = content.slice(
content.indexOf('export interface AssetPatch {'),
content.indexOf('}', content.indexOf('export interface AssetPatch {')),
);
expect(patch).toContain('filename?:');
expect(patch).not.toContain('uploadUrl');
expect(patch).not.toContain('uploadVersions');
});
});
107 changes: 107 additions & 0 deletions graphql/codegen/src/__tests__/codegen/generated-skills.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';

import {
GENERATED_SKILL_MARKER,
removeStaleGeneratedSkills,
writeGeneratedSkills,
} from '../../core/output';

describe('generated skills', () => {
let skillsDir: string;

const write = (relativePath: string, content: string): string => {
const filePath = path.join(skillsDir, relativePath);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content);
return filePath;
};
const generatedSkill = `---\nname: x\n---\n\n${GENERATED_SKILL_MARKER}\n`;

beforeEach(() => {
skillsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegen-skills-test-'));
});

afterEach(() => {
fs.rmSync(skillsDir, { recursive: true, force: true });
});

it('leaves a generated skill directory with exactly the files it wrote', async () => {
const staleRef = write('orm-auth/references/request-upload-url.md', 'stale');
const staleNested = write('orm-auth/old/nested/file.md', 'stale');
write('orm-auth/SKILL.md', 'old');

const result = await writeGeneratedSkills(
[
{ path: 'orm-auth/SKILL.md', content: generatedSkill },
{ path: 'orm-auth/references/user.md', content: '# user\n' },
],
skillsDir,
);

expect(result.success).toBe(true);
expect(result.skillNames).toEqual(['orm-auth']);
expect(result.filesRemoved.sort()).toEqual([staleNested, staleRef].sort());
expect(fs.readdirSync(path.join(skillsDir, 'orm-auth')).sort()).toEqual([
'SKILL.md',
'references',
]);
expect(fs.readdirSync(path.join(skillsDir, 'orm-auth', 'references'))).toEqual([
'user.md',
]);
expect(fs.readFileSync(path.join(skillsDir, 'orm-auth', 'SKILL.md'), 'utf-8')).toBe(
generatedSkill,
);
});

it('does not touch sibling skill directories when writing', async () => {
const handWritten = write('pgpm/references/deploy.md', 'hand-written');
const otherGenerated = write('orm-admin/references/stale.md', 'other run');

await writeGeneratedSkills(
[{ path: 'orm-auth/SKILL.md', content: generatedSkill }],
skillsDir,
);

expect(fs.existsSync(handWritten)).toBe(true);
expect(fs.existsSync(otherGenerated)).toBe(true);
});

it('removes generated skills of targets that are no longer generated', () => {
write('orm-auth/SKILL.md', generatedSkill);
write('orm-public/SKILL.md', generatedSkill);
write('orm-public/references/user.md', '# user\n');

expect(removeStaleGeneratedSkills(skillsDir, ['orm-auth'])).toEqual(['orm-public']);
expect(fs.existsSync(path.join(skillsDir, 'orm-public'))).toBe(false);
expect(fs.existsSync(path.join(skillsDir, 'orm-auth', 'SKILL.md'))).toBe(true);
});

it('keeps generated skills of configured targets that were not regenerated', () => {
write('orm-auth/SKILL.md', generatedSkill);
write('orm-cluster/SKILL.md', generatedSkill);
write('orm-public/SKILL.md', generatedSkill);

expect(removeStaleGeneratedSkills(skillsDir, ['orm-auth'], ['cluster'])).toEqual([
'orm-public',
]);
expect(fs.existsSync(path.join(skillsDir, 'orm-cluster'))).toBe(true);
});

it('keeps hand-written skills and generated skills of other families', () => {
// same family prefix, but no generator marker
write('orm-guide/SKILL.md', '---\nname: orm-guide\n---\n\nHand-written.\n');
// generated, but by a run that produces a different family
write('hooks-public/SKILL.md', generatedSkill);
// unrelated hand-written skill
write('pgpm/SKILL.md', '---\nname: pgpm\n---\n');
// no SKILL.md at all
write('orm-notes/README.md', 'notes');

expect(removeStaleGeneratedSkills(skillsDir, ['orm-auth'])).toEqual([]);
for (const name of ['orm-guide', 'hooks-public', 'pgpm', 'orm-notes']) {
expect(fs.existsSync(path.join(skillsDir, name))).toBe(true);
}
});
});
Loading
Loading