Skip to content
Open
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
16 changes: 12 additions & 4 deletions packages/1-framework/1-core/operations/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ export interface ReturnSpec {
}

export type SelfSpec =
| { readonly codecId: string; readonly traits?: never }
| { readonly traits: readonly string[]; readonly codecId?: never };
| { readonly codecId: string; readonly traits?: never; readonly many?: never }
| { readonly traits: readonly string[]; readonly codecId?: never; readonly many?: never }
| {
readonly many: true;
readonly elementTraits?: readonly string[];
readonly codecId?: never;
readonly traits?: never;
};

export interface OperationEntry {
readonly self?: SelfSpec;
Expand Down Expand Up @@ -42,10 +48,12 @@ export function createOperationRegistry<
if (descriptor.self) {
const hasCodecId = descriptor.self.codecId !== undefined;
const hasTraits = descriptor.self.traits !== undefined && descriptor.self.traits.length > 0;
if (!hasCodecId && !hasTraits) {
const hasMany = descriptor.self.many === true;
const targetCount = Number(hasCodecId) + Number(hasTraits) + Number(hasMany);
if (targetCount === 0) {
throw new Error(`Operation "${name}" self has neither codecId nor traits`);
}
if (hasCodecId && hasTraits) {
if (targetCount > 1) {
throw new Error(`Operation "${name}" self has both codecId and traits`);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,32 @@ describe('OperationRegistry', () => {
).not.toThrow();
});

it('accepts a list (many) self', () => {
const registry = createOperationRegistry();

expect(() => registry.register('has', descriptor({ self: { many: true } }))).not.toThrow();
});

it('accepts a list (many) self with elementTraits', () => {
const registry = createOperationRegistry();

expect(() =>
registry.register('has', descriptor({ self: { many: true, elementTraits: ['equality'] } })),
).not.toThrow();
});

it('throws when self combines many with codecId', () => {
const registry = createOperationRegistry();

expect(() =>
registry.register('bad', {
// @ts-expect-error — SelfSpec disallows many alongside codecId
self: { many: true, codecId: 'pg/text@1' },
impl: noopImpl,
}),
).toThrow('Operation "bad" self has both codecId and traits');
});

it('accepts self-less operation', () => {
const registry = createOperationRegistry();

Expand Down
3 changes: 2 additions & 1 deletion packages/2-sql/3-tooling/emitter/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,8 +587,9 @@ function generateTableLiteralType(table: StorageTable): string {
? `; readonly typeParams: ${serializeTypeParamsLiteral(col.typeParams)}`
: '';
const typeRefSpec = col.typeRef ? `; readonly typeRef: ${serializeValue(col.typeRef)}` : '';
const manySpec = col.many === true ? '; readonly many: true' : '';
columns.push(
`readonly ${colName}: { readonly nativeType: ${nativeType}; readonly codecId: ${codecId}; readonly nullable: ${nullable}${defaultSpec}${typeParamsSpec}${typeRefSpec} }`,
`readonly ${colName}: { readonly nativeType: ${nativeType}; readonly codecId: ${codecId}; readonly nullable: ${nullable}${manySpec}${defaultSpec}${typeParamsSpec}${typeRefSpec} }`,
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -919,4 +919,37 @@ describe('StorageColumnTypes', () => {
"readonly labels: ReadonlyArray<CodecTypes['pg/text@1']['input']> | null",
);
});

it('projects many: true onto the storage table column literal for a native many[] column', () => {
const contract = createContract({
models: {
Post: {
storage: { table: 'post', fields: { tags: { column: 'tags' } } },
fields: {
tags: { nullable: false, many: true, type: { kind: 'scalar', codecId: 'pg/text@1' } },
},
relations: {},
},
},
storage: {
tables: {
post: {
columns: {
tags: { nativeType: 'text', codecId: 'pg/text@1', nullable: false, many: true },
},
primaryKey: { columns: ['tags'] },
uniques: [],
indexes: [],
foreignKeys: [],
},
},
},
});

const dts = generateContractDts(contract, sqlEmission, [], testHashes);

expect(dts).toContain(
"readonly tags: { readonly nativeType: 'text'; readonly codecId: 'pg/text@1'; readonly nullable: false; readonly many: true }",
);
});
});
2 changes: 1 addition & 1 deletion packages/2-sql/4-lanes/relational-core/src/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export type Expression<T extends ScopeField> = QueryOperationReturn & {
buildAst(): AstExpression;
};

type CodecIdsWithTrait<
export type CodecIdsWithTrait<
CT extends Record<string, { readonly input: unknown }>,
RequiredTraits extends readonly string[],
> = {
Expand Down
78 changes: 54 additions & 24 deletions packages/2-sql/4-lanes/sql-builder/src/expression.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,38 @@
import type { QueryOperationTypesBase } from '@prisma-next/sql-contract/types';
import type {
CodecExpression,
CodecIdsWithTrait,
CodecValue,
Expression,
RawSqlTag,
ScalarListExpression,
TraitExpression,
} from '@prisma-next/sql-relational-core/expression';
import type { Expand, QueryContext, Scope, ScopeField, ScopeTable, Subquery } from './scope';

export type { CodecExpression, Expression, RawSqlTag, TraitExpression };

/**
* List-operand call signature for a comparison builtin. Applies when the
* receiver is a whole-list expression (`ScalarListExpression`, `many: true`)
* whose element codec carries every trait in `RequiredTraits` — `['equality']`
* for `eq`/`ne`, `['order']` for `gt`/`gte`/`lt`/`lte`. The value side accepts a
* matching list expression or a literal `readonly ElementValue[]`, and the whole
* comparison lowers to the same boolean expression the scalar path returns.
*
* Kept disjoint from the scalar signature by the `many` discriminant: a
* `ScalarListExpression` (`many: true`) never satisfies the scalar
* `CodecExpression` slot (`many?: never`) and vice-versa, so scalar-call
* inference is untouched.
*/
type ListComparison<
CT extends Record<string, { readonly input: unknown }>,
RequiredTraits extends readonly string[],
> = <CodecId extends CodecIdsWithTrait<CT, RequiredTraits>>(
a: ScalarListExpression<CodecId, boolean>,
b: ScalarListExpression<CodecId, boolean> | readonly CodecValue<CodecId, false, CT>[],
) => Expression<BooleanCodecType>;

export type BooleanCodecType = { codecId: 'pg/bool@1'; nullable: boolean };

export type WithField<Source, Field extends ScopeField, Alias extends string> = Expand<
Expand Down Expand Up @@ -61,30 +85,36 @@ type DeriveExtFunctions<OT extends QueryOperationTypesBase> = {
};

export type BuiltinFunctions<CT extends Record<string, { readonly input: unknown }>> = {
eq: <CodecId extends string>(
a: CodecExpression<CodecId, boolean, CT> | null,
b: CodecExpression<CodecId, boolean, CT> | null,
) => Expression<BooleanCodecType>;
ne: <CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT> | null,
b: CodecExpression<CodecId, N, CT> | null,
) => Expression<BooleanCodecType>;
gt: <CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>;
gte: <CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>;
lt: <CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>;
lte: <CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>;
eq: ListComparison<CT, ['equality']> &
(<CodecId extends string>(
a: CodecExpression<CodecId, boolean, CT> | null,
b: CodecExpression<CodecId, boolean, CT> | null,
) => Expression<BooleanCodecType>);
ne: ListComparison<CT, ['equality']> &
(<CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT> | null,
b: CodecExpression<CodecId, N, CT> | null,
) => Expression<BooleanCodecType>);
gt: ListComparison<CT, ['order']> &
(<CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>);
gte: ListComparison<CT, ['order']> &
(<CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>);
lt: ListComparison<CT, ['order']> &
(<CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>);
lte: ListComparison<CT, ['order']> &
(<CodecId extends string, N extends boolean>(
a: CodecExpression<CodecId, N, CT>,
b: CodecExpression<CodecId, N, CT>,
) => Expression<BooleanCodecType>);
and: (...ands: CodecExpression<'pg/bool@1', boolean, CT>[]) => Expression<BooleanCodecType>;
or: (...ors: CodecExpression<'pg/bool@1', boolean, CT>[]) => Expression<BooleanCodecType>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ import type {
ScalarListExpression,
} from '@prisma-next/sql-relational-core/expression';
import { expectTypeOf, test } from 'vitest';
import type { FieldProxy, Functions } from '../../src/expression';
import type { QueryContext, Scope } from '../../src/scope';
import type { BooleanCodecType, FieldProxy, Functions } from '../../src/expression';
import type { Scope } from '../../src/scope';

type CmpExpr = Expression<BooleanCodecType>;

type CT = {
'pg/int4@1': { input: number; output: number; traits: readonly ['equality', 'order'] };
'pg/text@1': { input: string; output: string; traits: readonly ['equality', 'textual'] };
'pg/bool@1': { input: boolean; output: boolean; traits: readonly ['equality'] };
'pg/int4@1': { input: number; output: number; traits: 'equality' | 'order' };
'pg/text@1': { input: string; output: string; traits: 'equality' | 'order' | 'textual' };
'pg/bool@1': { input: boolean; output: boolean; traits: 'equality' };
};

type BoolExpr = Expression<{ codecId: 'pg/bool@1'; nullable: false }>;
Expand All @@ -40,17 +42,24 @@ type QueryOps = {
};
};

// A scope shaped like a `Post` table: scalar `name`, list `tags String[]`.
// A scope shaped like a `Post` table: scalar `name`, list `tags String[]`,
// list `flags Boolean[]` (element codec lacks the `order` trait).
type PostColumns = {
name: { codecId: 'pg/text@1'; nullable: false };
id: { codecId: 'pg/int4@1'; nullable: false };
tags: { codecId: 'pg/text@1'; nullable: false; many: true };
flags: { codecId: 'pg/bool@1'; nullable: false; many: true };
};
type PostScope = Scope & {
topLevel: PostColumns;
namespaces: { Post: PostColumns };
};

type QC = QueryContext & {
// Structurally a `QueryContext`, but `codecTypes` is the concrete `CT` (no
// `CodecTypesBase` index-signature intersection) so trait resolution
// (`CodecIdsWithTrait`) sees the exact codec ids — matching how a real emitted
// contract threads its concrete `CodecTypes`.
type QC = {
codecTypes: CT;
capabilities: Record<string, Record<string, boolean>>;
queryOperationTypes: QueryOps;
Expand Down Expand Up @@ -79,3 +88,40 @@ test('the list op rejects a scalar receiver and a wrong-typed element', () => {
// @ts-expect-error -- element must be text, not a number
fns.has(f.tags, 5);
});

test('equality builtins accept whole-list operands (literal array or list expression)', () => {
expectTypeOf(fns.eq(f.tags, ['a', 'b'])).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.eq(f.tags, f.tags)).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.ne(f.tags, ['a'])).toEqualTypeOf<CmpExpr>();
// a Boolean[] list is comparable by equality (bool carries the `equality` trait)
fns.eq(f.flags, [true]);
});

test('ordering builtins accept whole-list operands over an orderable element', () => {
expectTypeOf(fns.gt(f.tags, ['a'])).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.gte(f.tags, f.tags)).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.lt(f.tags, ['z'])).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.lte(f.tags, ['z'])).toEqualTypeOf<CmpExpr>();
});

test('comparison builtins reject a wrong-typed list element', () => {
// @ts-expect-error -- tags is a text list; the array elements must be strings
fns.eq(f.tags, [5]);
// @ts-expect-error -- tags is a text list; the array elements must be strings
fns.gt(f.tags, [5]);
});

test('ordering builtins reject a list whose element lacks the `order` trait', () => {
// @ts-expect-error -- flags is a Boolean[]; bool lacks the `order` trait
fns.gt(f.flags, [true]);
// @ts-expect-error -- flags is a Boolean[]; bool lacks the `order` trait
fns.lt(f.flags, f.flags);
});

test('scalar comparison calls are unchanged by the list overloads', () => {
expectTypeOf(fns.eq(f.id, 1)).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.gt(f.id, 1)).toEqualTypeOf<CmpExpr>();
expectTypeOf(fns.eq(f.name, 'x')).toEqualTypeOf<CmpExpr>();
// @ts-expect-error -- id is an int scalar; a string is not a valid operand
fns.eq(f.id, 'nope');
});
Loading
Loading