-
-
Notifications
You must be signed in to change notification settings - Fork 46
feat: JSON type replacement for Prisma TypedSQL queries #649
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
11
commits into
main
Choose a base branch
from
copilot/fix-conflicts-typedsql-update-main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
cba0da5
Initial plan
Copilot 9f5cb6a
feat: implement JSON type replacement for Prisma TypedSQL queries
Copilot 7d064af
refactor: inline column docs lookup, remove ColumnAnnotationMap and b…
Copilot 9c9df7b
feat: add PostgreSQL E2E tests for TypedSQL JSON type replacement
Copilot 490eef4
Merge branch 'main' into copilot/fix-conflicts-typedsql-update-main
arthurfiorette 331776e
fix: remove --skip-generate from prisma db push (not valid in Prisma 7)
Copilot 1b9c945
Merge branch 'main' into copilot/fix-conflicts-typedsql-update-main
arthurfiorette e8e6f46
feat: SQL-file @pjt-type annotations for complex TypedSQL queries + R…
Copilot 630ff5a
fix: Prisma 7 datasource URL → prisma.config.ts; fix biome formatting
Copilot 7ed5ab1
fix: add --sql flag to prisma generate in CI for TypedSQL file genera…
Copilot 38bf066
feat: run e2e-typedsql on ubuntu, macos, and windows
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| services: | ||
| postgres: | ||
| image: postgres:alpine | ||
| environment: | ||
| POSTGRES_USER: prisma | ||
| POSTGRES_PASSWORD: prisma | ||
| POSTGRES_DB: typedsql_test | ||
| ports: | ||
| - '5432:5432' | ||
| healthcheck: | ||
| test: ['CMD-SHELL', 'pg_isready -U prisma'] | ||
| interval: 5s | ||
| timeout: 5s | ||
| retries: 5 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| import type { SqlQueryOutput } from '@prisma/generator'; | ||
| import ts from 'typescript'; | ||
| import type { PrismaJsonTypesGeneratorConfig } from '../util/config'; | ||
| import { createType } from '../util/create-signature'; | ||
| import type { DeclarationWriter } from '../util/declaration-writer'; | ||
|
|
||
| /** | ||
| * Parses `-- @pjt-type column_name annotation` comments from a SQL source string. | ||
| * | ||
| * These per-file annotations let users type JSON columns in complex queries (joins, | ||
| * CTEs, column aliases) that don't map 1:1 to a Prisma model field. SQL-file | ||
| * annotations take priority over model-based column docs for the query that contains | ||
| * them. | ||
| * | ||
| * The `annotation` must follow the same syntax as Prisma schema doc-comments: | ||
| * - `[TypeName]` – references `<namespace>.TypeName` | ||
| * - `![InlineType]` – uses the inline type `(InlineType)` literally | ||
| * | ||
| * @example | ||
| * ```sql | ||
| * -- @pjt-type field_alias ![number] | ||
| * SELECT id, field AS field_alias FROM "Model" | ||
| * ``` | ||
| */ | ||
| export function parseSqlAnnotations(sqlContent: string): Map<string, string> { | ||
| const annotations = new Map<string, string>(); | ||
| for (const line of sqlContent.split('\n')) { | ||
| const match = line.trim().match(/^--\s*@pjt-type\s+(\S+)\s+(.+?)\s*$/); | ||
| if (match) { | ||
| annotations.set(match[1]!, match[2]!); | ||
| } | ||
| } | ||
| return annotations; | ||
| } | ||
|
|
||
| /** | ||
| * Handles a TypedSQL query file by replacing JSON column types with annotated types. | ||
| * | ||
| * TypedSQL files are TypeScript modules generated by Prisma that represent typed SQL | ||
| * queries. Each file exports a factory function and a namespace with `Parameters` and | ||
| * `Result` types. This handler replaces `$runtime.JsonValue` types in the `Result` type | ||
| * with user-annotated types from the Prisma schema. | ||
| */ | ||
| export function handleTypedSqlFile( | ||
| tsSource: ts.SourceFile, | ||
| writer: DeclarationWriter, | ||
| query: SqlQueryOutput, | ||
| columnDocs: Map<string, string | undefined>, | ||
| config: PrismaJsonTypesGeneratorConfig | ||
| ) { | ||
| // Only process json and json-array typed columns | ||
| const jsonColumns = query.resultColumns.filter( | ||
| (col) => col.typ === 'json' || col.typ === 'json-array' | ||
| ); | ||
|
|
||
| if (jsonColumns.length === 0) return; | ||
|
|
||
| // Build a map of column name → replacement info | ||
| const columnsToReplace = new Map< | ||
| string, | ||
| { newType: string; nullable: boolean; isArray: boolean } | ||
| >(); | ||
|
|
||
| for (const col of jsonColumns) { | ||
| const documentation = columnDocs.get(col.name); | ||
|
|
||
| // No annotation and allowAny is set — skip replacing | ||
| if (!documentation && config.allowAny) continue; | ||
|
|
||
| const newType = createType(documentation, config); | ||
| columnsToReplace.set(col.name, { | ||
| newType, | ||
| nullable: col.nullable, | ||
| isArray: col.typ === 'json-array' | ||
| }); | ||
| } | ||
|
|
||
| if (columnsToReplace.size === 0) return; | ||
|
|
||
| // Traverse the top-level namespace declaration matching the query name | ||
| tsSource.forEachChild((child) => { | ||
| if (child.kind !== ts.SyntaxKind.ModuleDeclaration) return; | ||
|
|
||
| const ns = child as ts.ModuleDeclaration; | ||
| if (ns.name.getText() !== query.name) return; | ||
|
|
||
| const body = ns.body; | ||
| if (!body || body.kind !== ts.SyntaxKind.ModuleBlock) return; | ||
|
|
||
| for (const stmt of (body as ts.ModuleBlock).statements) { | ||
| if (stmt.kind !== ts.SyntaxKind.TypeAliasDeclaration) continue; | ||
|
|
||
| const typeAlias = stmt as ts.TypeAliasDeclaration; | ||
| if (typeAlias.name.getText() !== 'Result') continue; | ||
| if (typeAlias.type.kind !== ts.SyntaxKind.TypeLiteral) continue; | ||
|
|
||
| const typeLiteral = typeAlias.type as ts.TypeLiteralNode; | ||
|
|
||
| for (const member of typeLiteral.members) { | ||
| if (member.kind !== ts.SyntaxKind.PropertySignature) continue; | ||
|
|
||
| const prop = member as ts.PropertySignature; | ||
| const propName = prop.name?.getText(); | ||
|
|
||
| if (!propName || !columnsToReplace.has(propName)) continue; | ||
|
|
||
| const { newType, nullable, isArray } = columnsToReplace.get(propName)!; | ||
| const typeNode = prop.type; | ||
|
|
||
| if (!typeNode) continue; | ||
|
|
||
| let replacement: string; | ||
| if (isArray) { | ||
| replacement = `${newType}[]`; | ||
| } else if (nullable) { | ||
| replacement = `${newType} | null`; | ||
| } else { | ||
| replacement = newType; | ||
| } | ||
|
|
||
| // Use getStart() (not pos) to exclude leading trivia so the | ||
| // space between the colon and the type is preserved. | ||
| writer.replace(typeNode.getStart(tsSource), typeNode.end, replacement); | ||
| } | ||
| } | ||
| }); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why can't you just use docker compose for all 3 environments?