turbine-orm 0.93.1 → 0.94.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -23
- package/dist/adapters/cockroachdb.d.ts +3 -3
- package/dist/adapters/cockroachdb.js +7 -11
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/yugabytedb.js +1 -1
- package/dist/better-sqlite3.d.ts +132 -0
- package/dist/better-sqlite3.js +303 -0
- package/dist/catalog-metadata.d.ts +250 -0
- package/dist/catalog-metadata.js +730 -0
- package/dist/cjs/adapters/cockroachdb.d.ts +3 -3
- package/dist/cjs/adapters/cockroachdb.js +7 -11
- package/dist/cjs/adapters/index.d.ts +1 -1
- package/dist/cjs/adapters/yugabytedb.js +1 -1
- package/dist/cjs/better-sqlite3.d.ts +132 -0
- package/dist/cjs/better-sqlite3.js +311 -0
- package/dist/cjs/catalog-metadata.d.ts +250 -0
- package/dist/cjs/catalog-metadata.js +747 -0
- package/dist/cjs/cli/compile-query.d.ts +6 -3
- package/dist/cjs/cli/compile-query.js +24 -3
- package/dist/cjs/cli/config.d.ts +35 -10
- package/dist/cjs/cli/config.js +173 -42
- package/dist/cjs/cli/d1-config.d.ts +14 -0
- package/dist/cjs/cli/d1-config.js +9 -0
- package/dist/cjs/cli/d1-local.d.ts +31 -0
- package/dist/cjs/cli/d1-local.js +298 -0
- package/dist/cjs/cli/d1-migrations.d.ts +16 -0
- package/dist/cjs/cli/d1-migrations.js +156 -0
- package/dist/cjs/cli/d1-project.d.ts +23 -0
- package/dist/cjs/cli/d1-project.js +314 -0
- package/dist/cjs/cli/d1-seed.d.ts +35 -0
- package/dist/cjs/cli/d1-seed.js +220 -0
- package/dist/cjs/cli/destructive.js +1 -2
- package/dist/cjs/cli/error-catalog.d.ts +3 -3
- package/dist/cjs/cli/error-catalog.js +21 -3
- package/dist/cjs/cli/index.d.ts +13 -8
- package/dist/cjs/cli/index.js +503 -71
- package/dist/cjs/cli/libsql-migrate-command.d.ts +5 -0
- package/dist/cjs/cli/libsql-migrate-command.js +82 -0
- package/dist/cjs/cli/libsql-migrate-status.d.ts +33 -0
- package/dist/cjs/cli/libsql-migrate-status.js +189 -0
- package/dist/cjs/cli/libsql-migrate.d.ts +14 -0
- package/dist/cjs/cli/libsql-migrate.js +522 -0
- package/dist/cjs/cli/libsql-project-config.d.ts +11 -0
- package/dist/cjs/cli/libsql-project-config.js +59 -0
- package/dist/cjs/cli/libsql-project.d.ts +52 -0
- package/dist/cjs/cli/libsql-project.js +409 -0
- package/dist/cjs/cli/libsql-seed-command.d.ts +29 -0
- package/dist/cjs/cli/libsql-seed-command.js +93 -0
- package/dist/cjs/cli/loader.d.ts +6 -5
- package/dist/cjs/cli/loader.js +53 -9
- package/dist/cjs/cli/mcp.d.ts +16 -1
- package/dist/cjs/cli/mcp.js +219 -125
- package/dist/cjs/cli/migrate.d.ts +2 -2
- package/dist/cjs/cli/migrate.js +29 -14
- package/dist/cjs/cli/mssql-doctor.d.ts +44 -0
- package/dist/cjs/cli/mssql-doctor.js +277 -0
- package/dist/cjs/cli/mssql-migrate-command.d.ts +9 -0
- package/dist/cjs/cli/mssql-migrate-command.js +230 -0
- package/dist/cjs/cli/mssql-migrate-connection.d.ts +51 -0
- package/dist/cjs/cli/mssql-migrate-connection.js +255 -0
- package/dist/cjs/cli/mssql-migrate-sql.d.ts +12 -0
- package/dist/cjs/cli/mssql-migrate-sql.js +282 -0
- package/dist/cjs/cli/mssql-migrate.d.ts +45 -0
- package/dist/cjs/cli/mssql-migrate.js +296 -0
- package/dist/cjs/cli/mssql-project.d.ts +34 -0
- package/dist/cjs/cli/mssql-project.js +171 -0
- package/dist/cjs/cli/mssql-seed.d.ts +7 -0
- package/dist/cjs/cli/mssql-seed.js +78 -0
- package/dist/cjs/cli/mssql-tools.d.ts +37 -0
- package/dist/cjs/cli/mssql-tools.js +354 -0
- package/dist/cjs/cli/mysql-doctor.d.ts +48 -0
- package/dist/cjs/cli/mysql-doctor.js +323 -0
- package/dist/cjs/cli/mysql-migrate-command.d.ts +7 -0
- package/dist/cjs/cli/mysql-migrate-command.js +290 -0
- package/dist/cjs/cli/mysql-migrate-sql.d.ts +18 -0
- package/dist/cjs/cli/mysql-migrate-sql.js +166 -0
- package/dist/cjs/cli/mysql-migrate.d.ts +77 -0
- package/dist/cjs/cli/mysql-migrate.js +619 -0
- package/dist/cjs/cli/mysql-project.d.ts +49 -0
- package/dist/cjs/cli/mysql-project.js +284 -0
- package/dist/cjs/cli/mysql-push-command.d.ts +7 -0
- package/dist/cjs/cli/mysql-push-command.js +94 -0
- package/dist/cjs/cli/mysql-push.d.ts +15 -0
- package/dist/cjs/cli/mysql-push.js +98 -0
- package/dist/cjs/cli/mysql-schema-command.d.ts +5 -0
- package/dist/cjs/cli/mysql-schema-command.js +58 -0
- package/dist/cjs/cli/mysql-schema-ddl.d.ts +37 -0
- package/dist/cjs/cli/mysql-schema-ddl.js +234 -0
- package/dist/cjs/cli/mysql-schema-snapshot.d.ts +21 -0
- package/dist/cjs/cli/mysql-schema-snapshot.js +127 -0
- package/dist/cjs/cli/mysql-schema.d.ts +27 -0
- package/dist/cjs/cli/mysql-schema.js +206 -0
- package/dist/cjs/cli/mysql-seed-loader.cjs +58 -0
- package/dist/cjs/cli/mysql-seed-loader.d.cts +3 -0
- package/dist/cjs/cli/mysql-seed.d.ts +6 -0
- package/dist/cjs/cli/mysql-seed.js +83 -0
- package/dist/cjs/cli/mysql-tools.d.ts +44 -0
- package/dist/cjs/cli/mysql-tools.js +336 -0
- package/dist/cjs/cli/no-follow.d.ts +29 -0
- package/dist/cjs/cli/no-follow.js +73 -0
- package/dist/cjs/cli/pii-predicate-guard.d.ts +1 -1
- package/dist/cjs/cli/pii-predicate-guard.js +2 -2
- package/dist/cjs/cli/pii-tags.d.ts +2 -2
- package/dist/cjs/cli/pii-tags.js +1 -1
- package/dist/cjs/cli/prisma-schema.js +2 -2
- package/dist/cjs/cli/sql-statements.d.ts +1 -1
- package/dist/cjs/cli/sql-statements.js +1 -1
- package/dist/cjs/cli/sqlite-doctor.d.ts +35 -0
- package/dist/cjs/cli/sqlite-doctor.js +400 -0
- package/dist/cjs/cli/sqlite-migrate-command.d.ts +4 -0
- package/dist/cjs/cli/sqlite-migrate-command.js +175 -0
- package/dist/cjs/cli/sqlite-migrate.d.ts +61 -0
- package/dist/cjs/cli/sqlite-migrate.js +692 -0
- package/dist/cjs/cli/sqlite-project.d.ts +42 -0
- package/dist/cjs/cli/sqlite-project.js +254 -0
- package/dist/cjs/cli/sqlite-schema-command.d.ts +4 -0
- package/dist/cjs/cli/sqlite-schema-command.js +82 -0
- package/dist/cjs/cli/sqlite-schema-ddl.d.ts +25 -0
- package/dist/cjs/cli/sqlite-schema-ddl.js +252 -0
- package/dist/cjs/cli/sqlite-schema.d.ts +25 -0
- package/dist/cjs/cli/sqlite-schema.js +334 -0
- package/dist/cjs/cli/sqlite-seed.d.ts +4 -0
- package/dist/cjs/cli/sqlite-seed.js +94 -0
- package/dist/cjs/cli/sqlite-tools.d.ts +24 -0
- package/dist/cjs/cli/sqlite-tools.js +169 -0
- package/dist/cjs/cli/studio.js +9 -9
- package/dist/cjs/cli/tool-capabilities.d.ts +72 -0
- package/dist/cjs/cli/tool-capabilities.js +120 -0
- package/dist/cjs/cli/tool-command.d.ts +11 -0
- package/dist/cjs/cli/tool-command.js +49 -0
- package/dist/cjs/cli/ui.d.ts +1 -1
- package/dist/cjs/cli/ui.js +1 -1
- package/dist/cjs/client.d.ts +20 -20
- package/dist/cjs/client.js +65 -344
- package/dist/cjs/connection-url.d.ts +1 -1
- package/dist/cjs/connection-url.js +1 -1
- package/dist/cjs/core.d.ts +58 -0
- package/dist/cjs/core.js +225 -0
- package/dist/cjs/d1/catalog-metadata.d.ts +5 -0
- package/dist/cjs/d1/catalog-metadata.js +230 -0
- package/dist/cjs/d1/catalog.d.ts +15 -0
- package/dist/cjs/d1/catalog.js +88 -0
- package/dist/cjs/d1/generate.d.ts +8 -0
- package/dist/cjs/d1/generate.js +163 -0
- package/dist/cjs/d1/introspect.d.ts +21 -0
- package/dist/cjs/d1/introspect.js +74 -0
- package/dist/cjs/d1/migrate.d.ts +29 -0
- package/dist/cjs/d1/migrate.js +222 -0
- package/dist/cjs/d1/migrations/sql.d.ts +2 -0
- package/dist/cjs/d1/migrations/sql.js +109 -0
- package/dist/cjs/d1/pool.d.ts +14 -0
- package/dist/cjs/d1/pool.js +90 -0
- package/dist/cjs/d1/sql.d.ts +5 -0
- package/dist/cjs/d1/sql.js +140 -0
- package/dist/cjs/d1/sqlite-dialect.d.ts +16 -0
- package/dist/cjs/d1/sqlite-dialect.js +579 -0
- package/dist/cjs/d1/types.d.ts +29 -0
- package/dist/cjs/d1/types.js +2 -0
- package/dist/cjs/d1.d.ts +53 -0
- package/dist/cjs/d1.js +220 -0
- package/dist/cjs/dialect.d.ts +33 -5
- package/dist/cjs/dialect.js +8 -6
- package/dist/cjs/errors.d.ts +38 -1
- package/dist/cjs/errors.js +72 -18
- package/dist/cjs/generate.d.ts +19 -3
- package/dist/cjs/generate.js +330 -97
- package/dist/cjs/global-filters-config.js +4 -4
- package/dist/cjs/index-advisor.js +6 -6
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +3 -2
- package/dist/cjs/introspect.d.ts +59 -356
- package/dist/cjs/introspect.js +158 -984
- package/dist/cjs/libsql/bindings.d.ts +2 -0
- package/dist/cjs/libsql/bindings.js +78 -0
- package/dist/cjs/libsql/dialect.d.ts +3 -0
- package/dist/cjs/libsql/dialect.js +48 -0
- package/dist/cjs/libsql/generate.d.ts +4 -0
- package/dist/cjs/libsql/generate.js +56 -0
- package/dist/cjs/libsql/introspect.d.ts +16 -0
- package/dist/cjs/libsql/introspect.js +295 -0
- package/dist/cjs/libsql/pool.d.ts +42 -0
- package/dist/cjs/libsql/pool.js +275 -0
- package/dist/cjs/libsql/seed-cleanup.d.ts +2 -0
- package/dist/cjs/libsql/seed-cleanup.js +19 -0
- package/dist/cjs/libsql/values.d.ts +20 -0
- package/dist/cjs/libsql/values.js +75 -0
- package/dist/cjs/libsql-seed.d.ts +19 -0
- package/dist/cjs/libsql-seed.js +50 -0
- package/dist/cjs/libsql.d.ts +28 -0
- package/dist/cjs/libsql.js +88 -0
- package/dist/cjs/live-query.d.ts +33 -0
- package/dist/cjs/live-query.js +172 -0
- package/dist/cjs/log-codes.d.ts +1 -1
- package/dist/cjs/log-codes.js +4 -0
- package/dist/cjs/mssql-seed.d.ts +27 -0
- package/dist/cjs/mssql-seed.js +118 -0
- package/dist/cjs/mssql.d.ts +7 -7
- package/dist/cjs/mssql.js +365 -53
- package/dist/cjs/mysql-seed.d.ts +25 -0
- package/dist/cjs/mysql-seed.js +169 -0
- package/dist/cjs/mysql.d.ts +18 -6
- package/dist/cjs/mysql.js +602 -94
- package/dist/cjs/neon-http/client.d.ts +95 -0
- package/dist/cjs/neon-http/client.js +291 -0
- package/dist/cjs/neon-http/sql.d.ts +3 -0
- package/dist/cjs/neon-http/sql.js +116 -0
- package/dist/cjs/neon-http.d.ts +5 -0
- package/dist/cjs/neon-http.js +8 -0
- package/dist/cjs/neon-ws/load-driver.cjs +44 -0
- package/dist/cjs/neon-ws/load-driver.d.cts +9 -0
- package/dist/cjs/neon-ws/recovery.d.ts +14 -0
- package/dist/cjs/neon-ws/recovery.js +69 -0
- package/dist/cjs/neon-ws/snapshot.d.ts +3 -0
- package/dist/cjs/neon-ws/snapshot.js +17 -0
- package/dist/cjs/neon-ws/transport.d.ts +112 -0
- package/dist/cjs/neon-ws/transport.js +290 -0
- package/dist/cjs/neon-ws.d.ts +26 -0
- package/dist/cjs/neon-ws.js +189 -0
- package/dist/cjs/nested-write.d.ts +34 -3
- package/dist/cjs/nested-write.js +117 -24
- package/dist/cjs/notification-hub/consumer.d.ts +22 -0
- package/dist/cjs/notification-hub/consumer.js +111 -0
- package/dist/cjs/notification-hub.d.ts +41 -0
- package/dist/cjs/notification-hub.js +373 -0
- package/dist/cjs/pg-catalog-text.d.ts +96 -0
- package/dist/cjs/pg-catalog-text.js +213 -0
- package/dist/cjs/pg-types.d.ts +46 -2
- package/dist/cjs/pipeline-submittable.d.ts +15 -5
- package/dist/cjs/pipeline-submittable.js +103 -48
- package/dist/cjs/pipeline.d.ts +5 -2
- package/dist/cjs/pipeline.js +111 -41
- package/dist/cjs/plan-divergence.d.ts +1 -1
- package/dist/cjs/plan-divergence.js +1 -1
- package/dist/cjs/powdb-introspect.d.ts +1 -1
- package/dist/cjs/powdb-introspect.js +5 -5
- package/dist/cjs/powdb-shared.d.ts +5 -5
- package/dist/cjs/powdb-shared.js +6 -5
- package/dist/cjs/powdb.d.ts +28 -10
- package/dist/cjs/powdb.js +80 -28
- package/dist/cjs/powql.d.ts +50 -28
- package/dist/cjs/powql.js +47 -33
- package/dist/cjs/prisma-compat.js +4 -5
- package/dist/cjs/prisma-schema-fingerprint.d.ts +1 -1
- package/dist/cjs/prisma-schema-fingerprint.js +1 -1
- package/dist/cjs/query/aggregates.d.ts +0 -13
- package/dist/cjs/query/aggregates.js +105 -238
- package/dist/cjs/query/batched-loader.d.ts +1 -1
- package/dist/cjs/query/batched-loader.js +18 -20
- package/dist/cjs/query/builder.d.ts +108 -144
- package/dist/cjs/query/builder.js +592 -893
- package/dist/cjs/query/compound-unique.d.ts +18 -3
- package/dist/cjs/query/compound-unique.js +110 -43
- package/dist/cjs/query/cursor-tuple.d.ts +17 -0
- package/dist/cjs/query/cursor-tuple.js +121 -0
- package/dist/cjs/query/expr.d.ts +2 -0
- package/dist/cjs/query/expr.js +40 -23
- package/dist/cjs/query/filters.d.ts +39 -7
- package/dist/cjs/query/filters.js +77 -19
- package/dist/cjs/query/normalize-args.d.ts +1 -1
- package/dist/cjs/query/normalize-args.js +7 -5
- package/dist/cjs/query/option-surface.d.ts +1 -1
- package/dist/cjs/query/option-surface.js +5 -3
- package/dist/cjs/query/pg-type-parsers.d.ts +126 -0
- package/dist/cjs/query/pg-type-parsers.js +306 -0
- package/dist/cjs/query/relation-names.d.ts +4 -2
- package/dist/cjs/query/relation-names.js +21 -12
- package/dist/cjs/query/relations.d.ts +19 -7
- package/dist/cjs/query/relations.js +329 -260
- package/dist/cjs/query/row-lock.js +3 -3
- package/dist/cjs/query/sql-comment.js +3 -3
- package/dist/cjs/query/stream-idle.d.ts +11 -1
- package/dist/cjs/query/stream-idle.js +53 -13
- package/dist/cjs/query/stream-signal.d.ts +21 -0
- package/dist/cjs/query/stream-signal.js +132 -0
- package/dist/cjs/query/temporal-parsers.d.ts +101 -0
- package/dist/cjs/query/temporal-parsers.js +362 -0
- package/dist/cjs/query/types.d.ts +67 -20
- package/dist/cjs/query/utils.d.ts +2 -878
- package/dist/cjs/query/utils.js +25 -2058
- package/dist/cjs/query/warn-registry.d.ts +1 -1
- package/dist/cjs/query/warn-registry.js +1 -1
- package/dist/cjs/query/where-compile.d.ts +4 -1
- package/dist/cjs/query/where-compile.js +18 -14
- package/dist/cjs/query/where.d.ts +14 -7
- package/dist/cjs/query/where.js +244 -436
- package/dist/cjs/query/writes.d.ts +33 -2
- package/dist/cjs/query/writes.js +104 -77
- package/dist/cjs/query-utils.d.ts +687 -0
- package/dist/cjs/query-utils.js +1444 -0
- package/dist/cjs/realtime.d.ts +1 -1
- package/dist/cjs/realtime.js +3 -3
- package/dist/cjs/schema-builder.js +2 -2
- package/dist/cjs/schema-metadata.d.ts +13 -3
- package/dist/cjs/schema-metadata.js +33 -5
- package/dist/cjs/schema-sql.d.ts +15 -24
- package/dist/cjs/schema-sql.js +53 -63
- package/dist/cjs/schema.d.ts +37 -2
- package/dist/cjs/schema.js +29 -2
- package/dist/cjs/seed.js +5 -5
- package/dist/cjs/serverless.d.ts +24 -71
- package/dist/cjs/serverless.js +24 -71
- package/dist/cjs/sql.d.ts +111 -0
- package/dist/cjs/sql.js +335 -0
- package/dist/cjs/sqlite-seed.d.ts +17 -0
- package/dist/cjs/sqlite-seed.js +31 -0
- package/dist/cjs/sqlite.d.ts +32 -19
- package/dist/cjs/sqlite.js +865 -652
- package/dist/cjs/supplied-pool-types.js +10 -9
- package/dist/cjs/transaction-control.js +6 -1
- package/dist/cjs/transaction-outcome.d.ts +61 -0
- package/dist/cjs/transaction-outcome.js +239 -0
- package/dist/cjs/transaction-state.d.ts +82 -13
- package/dist/cjs/transaction-state.js +222 -56
- package/dist/cjs/transaction-transport.d.ts +38 -0
- package/dist/cjs/transaction-transport.js +157 -0
- package/dist/cjs/typed-sql.d.ts +1 -1
- package/dist/cjs/typed-sql.js +1 -1
- package/dist/cli/compile-query.d.ts +6 -3
- package/dist/cli/compile-query.js +25 -4
- package/dist/cli/config.d.ts +35 -10
- package/dist/cli/config.js +170 -43
- package/dist/cli/d1-config.d.ts +14 -0
- package/dist/cli/d1-config.js +6 -0
- package/dist/cli/d1-local.d.ts +31 -0
- package/dist/cli/d1-local.js +285 -0
- package/dist/cli/d1-migrations.d.ts +16 -0
- package/dist/cli/d1-migrations.js +151 -0
- package/dist/cli/d1-project.d.ts +23 -0
- package/dist/cli/d1-project.js +304 -0
- package/dist/cli/d1-seed.d.ts +35 -0
- package/dist/cli/d1-seed.js +213 -0
- package/dist/cli/destructive.js +1 -2
- package/dist/cli/error-catalog.d.ts +3 -3
- package/dist/cli/error-catalog.js +21 -3
- package/dist/cli/index.d.ts +13 -8
- package/dist/cli/index.js +500 -71
- package/dist/cli/libsql-migrate-command.d.ts +5 -0
- package/dist/cli/libsql-migrate-command.js +77 -0
- package/dist/cli/libsql-migrate-status.d.ts +33 -0
- package/dist/cli/libsql-migrate-status.js +182 -0
- package/dist/cli/libsql-migrate.d.ts +14 -0
- package/dist/cli/libsql-migrate.js +516 -0
- package/dist/cli/libsql-project-config.d.ts +11 -0
- package/dist/cli/libsql-project-config.js +55 -0
- package/dist/cli/libsql-project.d.ts +52 -0
- package/dist/cli/libsql-project.js +391 -0
- package/dist/cli/libsql-seed-command.d.ts +29 -0
- package/dist/cli/libsql-seed-command.js +85 -0
- package/dist/cli/loader.d.ts +6 -5
- package/dist/cli/loader.js +50 -9
- package/dist/cli/mcp.d.ts +16 -1
- package/dist/cli/mcp.js +220 -127
- package/dist/cli/migrate.d.ts +2 -2
- package/dist/cli/migrate.js +29 -14
- package/dist/cli/mssql-doctor.d.ts +44 -0
- package/dist/cli/mssql-doctor.js +237 -0
- package/dist/cli/mssql-migrate-command.d.ts +9 -0
- package/dist/cli/mssql-migrate-command.js +192 -0
- package/dist/cli/mssql-migrate-connection.d.ts +51 -0
- package/dist/cli/mssql-migrate-connection.js +245 -0
- package/dist/cli/mssql-migrate-sql.d.ts +12 -0
- package/dist/cli/mssql-migrate-sql.js +275 -0
- package/dist/cli/mssql-migrate.d.ts +45 -0
- package/dist/cli/mssql-migrate.js +290 -0
- package/dist/cli/mssql-project.d.ts +34 -0
- package/dist/cli/mssql-project.js +160 -0
- package/dist/cli/mssql-seed.d.ts +7 -0
- package/dist/cli/mssql-seed.js +73 -0
- package/dist/cli/mssql-tools.d.ts +37 -0
- package/dist/cli/mssql-tools.js +341 -0
- package/dist/cli/mysql-doctor.d.ts +48 -0
- package/dist/cli/mysql-doctor.js +316 -0
- package/dist/cli/mysql-migrate-command.d.ts +7 -0
- package/dist/cli/mysql-migrate-command.js +285 -0
- package/dist/cli/mysql-migrate-sql.d.ts +18 -0
- package/dist/cli/mysql-migrate-sql.js +162 -0
- package/dist/cli/mysql-migrate.d.ts +77 -0
- package/dist/cli/mysql-migrate.js +606 -0
- package/dist/cli/mysql-project.d.ts +49 -0
- package/dist/cli/mysql-project.js +272 -0
- package/dist/cli/mysql-push-command.d.ts +7 -0
- package/dist/cli/mysql-push-command.js +89 -0
- package/dist/cli/mysql-push.d.ts +15 -0
- package/dist/cli/mysql-push.js +95 -0
- package/dist/cli/mysql-schema-command.d.ts +5 -0
- package/dist/cli/mysql-schema-command.js +54 -0
- package/dist/cli/mysql-schema-ddl.d.ts +37 -0
- package/dist/cli/mysql-schema-ddl.js +227 -0
- package/dist/cli/mysql-schema-snapshot.d.ts +21 -0
- package/dist/cli/mysql-schema-snapshot.js +119 -0
- package/dist/cli/mysql-schema.d.ts +27 -0
- package/dist/cli/mysql-schema.js +200 -0
- package/dist/cli/mysql-seed-loader.cjs +25 -0
- package/dist/cli/mysql-seed-loader.d.cts +3 -0
- package/dist/cli/mysql-seed.d.ts +6 -0
- package/dist/cli/mysql-seed.js +75 -0
- package/dist/cli/mysql-tools.d.ts +44 -0
- package/dist/cli/mysql-tools.js +290 -0
- package/dist/cli/no-follow.d.ts +29 -0
- package/dist/cli/no-follow.js +67 -0
- package/dist/cli/pii-predicate-guard.d.ts +1 -1
- package/dist/cli/pii-predicate-guard.js +2 -2
- package/dist/cli/pii-tags.d.ts +2 -2
- package/dist/cli/pii-tags.js +1 -1
- package/dist/cli/prisma-schema.js +2 -2
- package/dist/cli/sql-statements.d.ts +1 -1
- package/dist/cli/sql-statements.js +1 -1
- package/dist/cli/sqlite-doctor.d.ts +35 -0
- package/dist/cli/sqlite-doctor.js +392 -0
- package/dist/cli/sqlite-migrate-command.d.ts +4 -0
- package/dist/cli/sqlite-migrate-command.js +171 -0
- package/dist/cli/sqlite-migrate.d.ts +61 -0
- package/dist/cli/sqlite-migrate.js +681 -0
- package/dist/cli/sqlite-project.d.ts +42 -0
- package/dist/cli/sqlite-project.js +244 -0
- package/dist/cli/sqlite-schema-command.d.ts +4 -0
- package/dist/cli/sqlite-schema-command.js +79 -0
- package/dist/cli/sqlite-schema-ddl.d.ts +25 -0
- package/dist/cli/sqlite-schema-ddl.js +248 -0
- package/dist/cli/sqlite-schema.d.ts +25 -0
- package/dist/cli/sqlite-schema.js +330 -0
- package/dist/cli/sqlite-seed.d.ts +4 -0
- package/dist/cli/sqlite-seed.js +57 -0
- package/dist/cli/sqlite-tools.d.ts +24 -0
- package/dist/cli/sqlite-tools.js +163 -0
- package/dist/cli/studio.js +9 -9
- package/dist/cli/tool-capabilities.d.ts +72 -0
- package/dist/cli/tool-capabilities.js +114 -0
- package/dist/cli/tool-command.d.ts +11 -0
- package/dist/cli/tool-command.js +45 -0
- package/dist/cli/ui.d.ts +1 -1
- package/dist/cli/ui.js +1 -1
- package/dist/client.d.ts +20 -20
- package/dist/client.js +62 -341
- package/dist/connection-url.d.ts +1 -1
- package/dist/connection-url.js +1 -1
- package/dist/core.d.ts +58 -0
- package/dist/core.js +220 -0
- package/dist/d1/catalog-metadata.d.ts +5 -0
- package/dist/d1/catalog-metadata.js +227 -0
- package/dist/d1/catalog.d.ts +15 -0
- package/dist/d1/catalog.js +82 -0
- package/dist/d1/generate.d.ts +8 -0
- package/dist/d1/generate.js +160 -0
- package/dist/d1/introspect.d.ts +21 -0
- package/dist/d1/introspect.js +71 -0
- package/dist/d1/migrate.d.ts +29 -0
- package/dist/d1/migrate.js +217 -0
- package/dist/d1/migrations/sql.d.ts +2 -0
- package/dist/d1/migrations/sql.js +106 -0
- package/dist/d1/pool.d.ts +14 -0
- package/dist/d1/pool.js +86 -0
- package/dist/d1/sql.d.ts +5 -0
- package/dist/d1/sql.js +135 -0
- package/dist/d1/sqlite-dialect.d.ts +16 -0
- package/dist/d1/sqlite-dialect.js +572 -0
- package/dist/d1/types.d.ts +29 -0
- package/dist/d1/types.js +1 -0
- package/dist/d1.d.ts +53 -0
- package/dist/d1.js +215 -0
- package/dist/dialect.d.ts +33 -5
- package/dist/dialect.js +6 -4
- package/dist/errors.d.ts +38 -1
- package/dist/errors.js +68 -17
- package/dist/generate.d.ts +19 -3
- package/dist/generate.js +330 -97
- package/dist/global-filters-config.js +2 -2
- package/dist/index-advisor.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/introspect.d.ts +59 -356
- package/dist/introspect.js +116 -943
- package/dist/libsql/bindings.d.ts +2 -0
- package/dist/libsql/bindings.js +75 -0
- package/dist/libsql/dialect.d.ts +3 -0
- package/dist/libsql/dialect.js +45 -0
- package/dist/libsql/generate.d.ts +4 -0
- package/dist/libsql/generate.js +53 -0
- package/dist/libsql/introspect.d.ts +16 -0
- package/dist/libsql/introspect.js +289 -0
- package/dist/libsql/pool.d.ts +42 -0
- package/dist/libsql/pool.js +270 -0
- package/dist/libsql/seed-cleanup.d.ts +2 -0
- package/dist/libsql/seed-cleanup.js +15 -0
- package/dist/libsql/values.d.ts +20 -0
- package/dist/libsql/values.js +68 -0
- package/dist/libsql-seed.d.ts +19 -0
- package/dist/libsql-seed.js +46 -0
- package/dist/libsql.d.ts +28 -0
- package/dist/libsql.js +79 -0
- package/dist/live-query.d.ts +33 -0
- package/dist/live-query.js +169 -0
- package/dist/log-codes.d.ts +1 -1
- package/dist/log-codes.js +4 -0
- package/dist/mssql-seed.d.ts +27 -0
- package/dist/mssql-seed.js +114 -0
- package/dist/mssql.d.ts +7 -7
- package/dist/mssql.js +366 -54
- package/dist/mysql-seed.d.ts +25 -0
- package/dist/mysql-seed.js +165 -0
- package/dist/mysql.d.ts +18 -6
- package/dist/mysql.js +603 -95
- package/dist/neon-http/client.d.ts +95 -0
- package/dist/neon-http/client.js +286 -0
- package/dist/neon-http/sql.d.ts +3 -0
- package/dist/neon-http/sql.js +112 -0
- package/dist/neon-http.d.ts +5 -0
- package/dist/neon-http.js +2 -0
- package/dist/neon-ws/load-driver.cjs +11 -0
- package/dist/neon-ws/load-driver.d.cts +9 -0
- package/dist/neon-ws/recovery.d.ts +14 -0
- package/dist/neon-ws/recovery.js +66 -0
- package/dist/neon-ws/snapshot.d.ts +3 -0
- package/dist/neon-ws/snapshot.js +15 -0
- package/dist/neon-ws/transport.d.ts +112 -0
- package/dist/neon-ws/transport.js +286 -0
- package/dist/neon-ws.d.ts +26 -0
- package/dist/neon-ws.js +182 -0
- package/dist/nested-write.d.ts +34 -3
- package/dist/nested-write.js +114 -22
- package/dist/notification-hub/consumer.d.ts +22 -0
- package/dist/notification-hub/consumer.js +106 -0
- package/dist/notification-hub.d.ts +41 -0
- package/dist/notification-hub.js +370 -0
- package/dist/pg-catalog-text.d.ts +96 -0
- package/dist/pg-catalog-text.js +208 -0
- package/dist/pg-types.d.ts +46 -2
- package/dist/pipeline-submittable.d.ts +15 -5
- package/dist/pipeline-submittable.js +105 -50
- package/dist/pipeline.d.ts +5 -2
- package/dist/pipeline.js +113 -43
- package/dist/plan-divergence.d.ts +1 -1
- package/dist/plan-divergence.js +1 -1
- package/dist/powdb-introspect.d.ts +1 -1
- package/dist/powdb-introspect.js +5 -5
- package/dist/powdb-shared.d.ts +5 -5
- package/dist/powdb-shared.js +6 -5
- package/dist/powdb.d.ts +28 -10
- package/dist/powdb.js +80 -28
- package/dist/powql.d.ts +50 -28
- package/dist/powql.js +49 -35
- package/dist/prisma-compat.js +4 -5
- package/dist/prisma-schema-fingerprint.d.ts +1 -1
- package/dist/prisma-schema-fingerprint.js +1 -1
- package/dist/query/aggregates.d.ts +0 -13
- package/dist/query/aggregates.js +97 -230
- package/dist/query/batched-loader.d.ts +1 -1
- package/dist/query/batched-loader.js +5 -7
- package/dist/query/builder.d.ts +108 -144
- package/dist/query/builder.js +563 -864
- package/dist/query/compound-unique.d.ts +18 -3
- package/dist/query/compound-unique.js +99 -33
- package/dist/query/cursor-tuple.d.ts +17 -0
- package/dist/query/cursor-tuple.js +114 -0
- package/dist/query/expr.d.ts +2 -0
- package/dist/query/expr.js +32 -16
- package/dist/query/filters.d.ts +39 -7
- package/dist/query/filters.js +69 -14
- package/dist/query/normalize-args.d.ts +1 -1
- package/dist/query/normalize-args.js +4 -2
- package/dist/query/option-surface.d.ts +1 -1
- package/dist/query/option-surface.js +4 -2
- package/dist/query/pg-type-parsers.d.ts +126 -0
- package/dist/query/pg-type-parsers.js +296 -0
- package/dist/query/relation-names.d.ts +4 -2
- package/dist/query/relation-names.js +15 -7
- package/dist/query/relations.d.ts +19 -7
- package/dist/query/relations.js +293 -227
- package/dist/query/row-lock.js +1 -1
- package/dist/query/sql-comment.js +1 -1
- package/dist/query/stream-idle.d.ts +11 -1
- package/dist/query/stream-idle.js +51 -13
- package/dist/query/stream-signal.d.ts +21 -0
- package/dist/query/stream-signal.js +125 -0
- package/dist/query/temporal-parsers.d.ts +101 -0
- package/dist/query/temporal-parsers.js +354 -0
- package/dist/query/types.d.ts +67 -20
- package/dist/query/utils.d.ts +2 -878
- package/dist/query/utils.js +5 -2003
- package/dist/query/warn-registry.d.ts +1 -1
- package/dist/query/warn-registry.js +1 -1
- package/dist/query/where-compile.d.ts +4 -1
- package/dist/query/where-compile.js +14 -10
- package/dist/query/where.d.ts +14 -7
- package/dist/query/where.js +236 -430
- package/dist/query/writes.d.ts +33 -2
- package/dist/query/writes.js +90 -65
- package/dist/query-utils.d.ts +687 -0
- package/dist/query-utils.js +1390 -0
- package/dist/realtime.d.ts +1 -1
- package/dist/realtime.js +3 -3
- package/dist/schema-builder.js +2 -2
- package/dist/schema-metadata.d.ts +13 -3
- package/dist/schema-metadata.js +33 -5
- package/dist/schema-sql.d.ts +15 -24
- package/dist/schema-sql.js +50 -60
- package/dist/schema.d.ts +37 -2
- package/dist/schema.js +29 -2
- package/dist/seed.js +5 -5
- package/dist/serverless.d.ts +24 -71
- package/dist/serverless.js +24 -71
- package/dist/sql.d.ts +111 -0
- package/dist/sql.js +321 -0
- package/dist/sqlite-seed.d.ts +17 -0
- package/dist/sqlite-seed.js +27 -0
- package/dist/sqlite.d.ts +32 -19
- package/dist/sqlite.js +859 -648
- package/dist/supplied-pool-types.js +2 -1
- package/dist/transaction-control.js +6 -1
- package/dist/transaction-outcome.d.ts +61 -0
- package/dist/transaction-outcome.js +234 -0
- package/dist/transaction-state.d.ts +82 -13
- package/dist/transaction-state.js +220 -57
- package/dist/transaction-transport.d.ts +38 -0
- package/dist/transaction-transport.js +153 -0
- package/dist/typed-sql.d.ts +1 -1
- package/dist/typed-sql.js +1 -1
- package/package.json +239 -13
- package/skills/turbine-orm/SKILL.md +6 -5
|
@@ -0,0 +1,1390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* turbine-orm, Query builder utilities
|
|
3
|
+
*
|
|
4
|
+
* Standalone utility functions and classes used by the query builder.
|
|
5
|
+
*/
|
|
6
|
+
import { ValidationError } from './errors.js';
|
|
7
|
+
import { logTo } from './logger.js';
|
|
8
|
+
import { shouldWarnOnce, WARN_NS } from './query/warn-registry.js';
|
|
9
|
+
import { camelToSnake, localDateTimeKind, snakeToCamel, timeOfDayKind } from './schema.js';
|
|
10
|
+
export { createFastTimestamptzParser, createUtcDateParser, createUtcDateParserGeneral, createUtcTimestampParser, createUtcTimestampParserGeneral, parseUtcTimestampText, } from './query/temporal-parsers.js';
|
|
11
|
+
// No native lookup at evaluation. The PostgreSQL compatibility entry installs
|
|
12
|
+
// its own runtime. Optional transports provide their own dialect wire rules.
|
|
13
|
+
let pg = {};
|
|
14
|
+
export function registerQueryDriver(driver) {
|
|
15
|
+
pg = driver;
|
|
16
|
+
}
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// Identifier quoting, prevents SQL injection via table/column names
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
/**
|
|
21
|
+
* Quote a SQL identifier (table name, column name) using Postgres double-quote
|
|
22
|
+
* rules: wrap in double quotes, escape internal double quotes by doubling them.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* quoteIdent('users') → '"users"'
|
|
26
|
+
* quoteIdent('my"table') → '"my""table"'
|
|
27
|
+
* quoteIdent('user name') → '"user name"'
|
|
28
|
+
*/
|
|
29
|
+
export function quoteIdent(name) {
|
|
30
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Prototype-safe own-property read for the plain metadata maps (columnMap,
|
|
34
|
+
* relations, reverseColumnMap). These are constructed as plain objects, so a
|
|
35
|
+
* bare `map[key]` for a user-supplied field name like "constructor",
|
|
36
|
+
* "toString", or "__proto__" returns an inherited member from
|
|
37
|
+
* `Object.prototype`, a truthy value that slips past validation and produces a
|
|
38
|
+
* cryptic `TypeError` instead of a clean `ValidationError`. Returns `undefined`
|
|
39
|
+
* unless `key` is an OWN enumerable/non-enumerable property.
|
|
40
|
+
*/
|
|
41
|
+
export function ownLookup(map, key) {
|
|
42
|
+
return Object.hasOwn(map, key) ? map[key] : undefined;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Resolve a user-supplied key to its unquoted column name, or `undefined` when
|
|
46
|
+
* the key names no column on the table.
|
|
47
|
+
*
|
|
48
|
+
* THE key-resolution rule, in one place. `QueryInterface.toColumn` is this
|
|
49
|
+
* function plus the E003 throw, so every SQL builder resolves keys through it,
|
|
50
|
+
* and the value-side passes (write coercion, the `updatedAt` injector, the
|
|
51
|
+
* nested-write foreign-key merge) call it directly rather than re-deriving the
|
|
52
|
+
* rule. They used to read `columnMap` alone, which knows only the FIELD
|
|
53
|
+
* spelling, so a key spelled as the snake_case COLUMN, which the SQL builders
|
|
54
|
+
* accept and which is the natural spelling on an introspected schema, produced
|
|
55
|
+
* correct SQL with an unprocessed value: byte-identical statement, silently
|
|
56
|
+
* different bound param.
|
|
57
|
+
*
|
|
58
|
+
* The rule: the field map first, else `camelToSnake(key)` accepted ONLY when
|
|
59
|
+
* that name is a real column. `camelToSnake` is idempotent on an already-snake
|
|
60
|
+
* string, which is what makes the column spelling legal; arbitrary strings
|
|
61
|
+
* still fail to resolve, so identifier validation is unchanged.
|
|
62
|
+
*
|
|
63
|
+
* Prototype-safe: both maps are plain objects, so a key like "constructor" or
|
|
64
|
+
* "__proto__" would otherwise return an inherited member and pass for a column
|
|
65
|
+
* name (see {@link ownLookup}).
|
|
66
|
+
*/
|
|
67
|
+
export function resolveColumnName(meta, key) {
|
|
68
|
+
const mapped = ownLookup(meta.columnMap, key);
|
|
69
|
+
if (mapped)
|
|
70
|
+
return mapped;
|
|
71
|
+
const snake = camelToSnake(key);
|
|
72
|
+
if (meta.reverseColumnMap && ownLookup(meta.reverseColumnMap, snake))
|
|
73
|
+
return snake;
|
|
74
|
+
if (meta.allColumns?.includes(snake))
|
|
75
|
+
return snake;
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Resolve a user-supplied key to a relation's CANONICAL name and definition, or
|
|
80
|
+
* `undefined` when the key names no relation on the table.
|
|
81
|
+
*
|
|
82
|
+
* The relation-name half of the rule {@link resolveColumnName} states for
|
|
83
|
+
* columns, and deliberately the same shape: the declared name first, else
|
|
84
|
+
* `snakeToCamel(key)` accepted ONLY when that names a real relation.
|
|
85
|
+
* `snakeToCamel` is idempotent on an already-camel string, so a canonical key
|
|
86
|
+
* takes the first branch and this is a no-op for every existing caller.
|
|
87
|
+
*
|
|
88
|
+
* WHY IT EXISTS. A relation has one declared name, `ripeningChecks`, while the
|
|
89
|
+
* DDL anyone reads has only the TABLE name, `ripening_checks`. Writing back
|
|
90
|
+
* what the schema shows therefore failed with E005 in `with`, E003 in a
|
|
91
|
+
* relation filter, and E005 in `orderBy`, on names the error text was already
|
|
92
|
+
* computing correctly ("Did you mean ...?"). A system that can name the
|
|
93
|
+
* intended relation can accept it.
|
|
94
|
+
*
|
|
95
|
+
* NOT A GUESS, for the same reason the column rule is not: the transformed name
|
|
96
|
+
* is accepted only when it is a real declared relation, so an unknown key still
|
|
97
|
+
* fails and a typo is still a typo. Exact match wins first, so a schema that
|
|
98
|
+
* literally declares `ripening_checks` keeps it, even alongside a
|
|
99
|
+
* `ripeningChecks`.
|
|
100
|
+
*
|
|
101
|
+
* The RESULT KEY is the canonical name, not the caller's spelling, matching the
|
|
102
|
+
* column side (`select: { ledger_handle: true }` already returns
|
|
103
|
+
* `{ ledgerHandle }`). Resolving here rather than normalizing the args up front
|
|
104
|
+
* also means both spellings share one SQL-cache entry instead of minting two
|
|
105
|
+
* templates for one query.
|
|
106
|
+
*
|
|
107
|
+
* Prototype-safe via {@link ownLookup}, so `__proto__` cannot name a relation.
|
|
108
|
+
*/
|
|
109
|
+
export function resolveRelation(relations, key) {
|
|
110
|
+
const direct = ownLookup(relations, key);
|
|
111
|
+
if (direct !== undefined)
|
|
112
|
+
return { name: key, def: direct };
|
|
113
|
+
const camel = snakeToCamel(key);
|
|
114
|
+
if (camel === key)
|
|
115
|
+
return undefined;
|
|
116
|
+
const mapped = ownLookup(relations, camel);
|
|
117
|
+
return mapped === undefined ? undefined : { name: camel, def: mapped };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* {@link resolveRelation} when only the definition is wanted: a drop-in for the
|
|
121
|
+
* `ownLookup(meta.relations, key)` it replaces, with the same signature and the
|
|
122
|
+
* same `undefined` on a miss.
|
|
123
|
+
*/
|
|
124
|
+
export function resolveRelationDef(relations, key) {
|
|
125
|
+
return resolveRelation(relations, key)?.def;
|
|
126
|
+
}
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// Caller-controlled key ORDER, canonicalized
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
/**
|
|
131
|
+
* THE canonical order for a caller-supplied set of columns: the table's own
|
|
132
|
+
* `allColumns` order, which is the order `omit` and the default projection
|
|
133
|
+
* already produce.
|
|
134
|
+
*
|
|
135
|
+
* ## The failure mode this exists to close, and it is NOT arity
|
|
136
|
+
*
|
|
137
|
+
* Every distinct SQL text Turbine emits is parsed on the server as a NAMED
|
|
138
|
+
* prepared statement and is never DEALLOCATEd. The arity rule
|
|
139
|
+
* (`markVariableArity`) bounds the shapes whose LENGTH the caller picks. It
|
|
140
|
+
* does nothing about the shapes whose length is fixed and whose ORDER the
|
|
141
|
+
* caller picks, and those grow the SQL text just as freely: `select: { a, b }`
|
|
142
|
+
* and `select: { b, a }` are the same query and two different statements.
|
|
143
|
+
*
|
|
144
|
+
* Measured against PostgreSQL 16 on a SEVEN-column table, one connection, with
|
|
145
|
+
* the arity fix already landed:
|
|
146
|
+
*
|
|
147
|
+
* baseline prepared= 0 CachedPlanSource= 0.0 MB
|
|
148
|
+
* after 5040 `select` permutations prepared= 5040 CachedPlanSource=39.4 MB
|
|
149
|
+
* after 300 varying-arity ORs prepared= 5040 CachedPlanSource=39.4 MB
|
|
150
|
+
* after 5040 `distinct` permutations prepared=10080 CachedPlanSource=59.1 MB
|
|
151
|
+
* 720 reordered PATCH bodies (update) prepared= 720 CachedPlanSource= 2.8 MB
|
|
152
|
+
*
|
|
153
|
+
* The write row is the realistic one: `JSON.parse` preserves insertion order,
|
|
154
|
+
* so `update({ where, data: JSON.parse(reqBody) })` hands a request body the
|
|
155
|
+
* SET-clause column order for free. No arrays, no unusual input, no opt-in.
|
|
156
|
+
*
|
|
157
|
+
* The reachable space is ORDERED subsets, sum over k of k! * C(n,k): 9.9e6 for
|
|
158
|
+
* 10 columns, 6.6e18 for 20. Canonicalizing collapses each permutation class to
|
|
159
|
+
* one statement, leaving the UNORDERED subsets (2^n) that `omit` has always
|
|
160
|
+
* had.
|
|
161
|
+
*
|
|
162
|
+
* ## Why ordering is the right remedy here rather than withholding the name
|
|
163
|
+
*
|
|
164
|
+
* A projection's SELECT-list order is not semantically meaningful to Turbine:
|
|
165
|
+
* rows are assembled by NAME (`parseRow`, `jsonScalarPairs` and
|
|
166
|
+
* `buildRelationShape` all key off the same resolved list), so reordering it
|
|
167
|
+
* changes no value. Where an order IS meaningful (`orderBy`, and `DISTINCT ON`,
|
|
168
|
+
* whose list is re-emitted as an ORDER BY prefix), the statement is sent
|
|
169
|
+
* unnamed instead. See `MAX_NAMED_ORDER_KEYS` in filters.ts and the `distinct`
|
|
170
|
+
* mark in builder.ts.
|
|
171
|
+
*
|
|
172
|
+
* Duplicates collapse, which is the other half of "canonical": two spellings of
|
|
173
|
+
* one column (`userId` and `user_id`, both legal on an introspected schema)
|
|
174
|
+
* used to emit that column twice in the SELECT list.
|
|
175
|
+
*
|
|
176
|
+
* Cost is one Set of the projected columns plus one pass over `allColumns`, on
|
|
177
|
+
* a path that already walks the caller's keys.
|
|
178
|
+
*
|
|
179
|
+
* @param meta the table the columns belong to; without `allColumns` there is no
|
|
180
|
+
* canonical order to appeal to and the input is returned untouched.
|
|
181
|
+
* @param columns already-resolved snake_case column names.
|
|
182
|
+
*/
|
|
183
|
+
export function canonicalColumnOrder(meta, columns) {
|
|
184
|
+
const all = meta.allColumns;
|
|
185
|
+
if (all === undefined || columns.length < 2)
|
|
186
|
+
return columns;
|
|
187
|
+
const wanted = new Set(columns);
|
|
188
|
+
const ordered = [];
|
|
189
|
+
for (const col of all) {
|
|
190
|
+
if (wanted.delete(col))
|
|
191
|
+
ordered.push(col);
|
|
192
|
+
}
|
|
193
|
+
// A resolved column absent from `allColumns` is only reachable from
|
|
194
|
+
// hand-built metadata whose maps disagree with each other. Keep it (in the
|
|
195
|
+
// caller's relative order) rather than silently dropping it from the
|
|
196
|
+
// projection: this function reorders, it never decides what is projected.
|
|
197
|
+
if (wanted.size > 0) {
|
|
198
|
+
for (const col of columns) {
|
|
199
|
+
if (wanted.delete(col))
|
|
200
|
+
ordered.push(col);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return ordered;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* {@link canonicalColumnOrder} for a write's `data` entries: same order, same
|
|
207
|
+
* reason, two deliberate differences.
|
|
208
|
+
*
|
|
209
|
+
* DUPLICATES ARE KEPT. Two keys resolving to one column (`{ userId, user_id }`)
|
|
210
|
+
* is a caller error that PostgreSQL reports precisely ("multiple assignments to
|
|
211
|
+
* same column", 42701, and the INSERT equivalent). Collapsing them here would
|
|
212
|
+
* turn that error into a silent write of whichever value survived, so the entry
|
|
213
|
+
* list is REORDERED and never shortened. A stable sort keeps such a pair
|
|
214
|
+
* adjacent and in the caller's relative order, so the engine still sees, and
|
|
215
|
+
* still rejects, both assignments.
|
|
216
|
+
*
|
|
217
|
+
* THE KEY SPELLING IS PRESERVED. Everything downstream (`coerceWriteValue`,
|
|
218
|
+
* `buildSetClause`, `toSqlColumn`) re-resolves the caller's key itself, so only
|
|
219
|
+
* the ORDER of the entries changes here, never their content.
|
|
220
|
+
*
|
|
221
|
+
* A key that resolves to no column sorts LAST, in the caller's relative order.
|
|
222
|
+
* It is about to raise E003 from the SQL builder either way, and the builder is
|
|
223
|
+
* where that error belongs; ordering must not pre-empt it with a worse one.
|
|
224
|
+
*/
|
|
225
|
+
export function canonicalWriteEntries(meta, entries) {
|
|
226
|
+
const all = meta.allColumns;
|
|
227
|
+
if (all === undefined || entries.length < 2)
|
|
228
|
+
return entries;
|
|
229
|
+
const index = new Map();
|
|
230
|
+
for (let i = 0; i < all.length; i++)
|
|
231
|
+
index.set(all[i], i);
|
|
232
|
+
const rank = (key) => {
|
|
233
|
+
const column = resolveColumnName(meta, key);
|
|
234
|
+
const at = column === undefined ? undefined : index.get(column);
|
|
235
|
+
return at ?? Number.MAX_SAFE_INTEGER;
|
|
236
|
+
};
|
|
237
|
+
// Ranks are computed once per entry rather than inside the comparator, which
|
|
238
|
+
// would re-resolve every key O(k log k) times.
|
|
239
|
+
const ranked = entries.map((entry, at) => ({ entry, rank: rank(entry[0]), at }));
|
|
240
|
+
// `at` breaks ties explicitly rather than relying on sort stability, so two
|
|
241
|
+
// spellings of one column, and every unresolvable key, keep the order the
|
|
242
|
+
// caller wrote them in.
|
|
243
|
+
ranked.sort((a, b) => a.rank - b.rank || a.at - b.at);
|
|
244
|
+
return ranked.map((r) => r.entry);
|
|
245
|
+
}
|
|
246
|
+
// ---------------------------------------------------------------------------
|
|
247
|
+
// Internally-synthesized combinator brand
|
|
248
|
+
// ---------------------------------------------------------------------------
|
|
249
|
+
/**
|
|
250
|
+
* Brands a WHERE object whose `AND` / `OR` array Turbine ITSELF synthesized,
|
|
251
|
+
* rather than one the caller wrote.
|
|
252
|
+
*
|
|
253
|
+
* The distinction matters for exactly one rule: a caller-written combinator
|
|
254
|
+
* array is treated as a VARIABLE-ARITY shape and its statement is sent unnamed
|
|
255
|
+
* (see `markVariableArity` in where.ts, and `acquireSql` in builder.ts).
|
|
256
|
+
* Turbine's own wrappers, the `{ AND: [userWhere, globalFilter] }` the
|
|
257
|
+
* global-filter merge produces and the `{ AND: [where, correlation] }` the
|
|
258
|
+
* batched loader produces, have a FIXED arity of two, decided by Turbine, not
|
|
259
|
+
* reachable from a request body. Counting them would have taken every query on
|
|
260
|
+
* a table with a configured global filter off named prepared statements, i.e.
|
|
261
|
+
* penalised precisely the multi-tenant setups the rule exists to protect.
|
|
262
|
+
*
|
|
263
|
+
* A `Symbol.for` key for the same cross-copy-identity reason the warn registry
|
|
264
|
+
* uses one (an ESM and a CJS copy of this module in one process must agree),
|
|
265
|
+
* and a SYMBOL rather than a string key so `Object.keys` (which is what every
|
|
266
|
+
* where walker enumerates) never sees it and no emitted SQL can change.
|
|
267
|
+
*/
|
|
268
|
+
export const INTERNAL_COMBINATOR = Symbol.for('turbine.internalCombinator');
|
|
269
|
+
/** Shared by every brand: a frozen descriptor saves an allocation per branded where. */
|
|
270
|
+
const INTERNAL_COMBINATOR_DESCRIPTOR = Object.freeze({
|
|
271
|
+
value: true,
|
|
272
|
+
enumerable: false,
|
|
273
|
+
configurable: true,
|
|
274
|
+
});
|
|
275
|
+
/** Tag `where` as carrying a Turbine-synthesized combinator, and return it. */
|
|
276
|
+
export function markInternalCombinator(where) {
|
|
277
|
+
Object.defineProperty(where, INTERNAL_COMBINATOR, INTERNAL_COMBINATOR_DESCRIPTOR);
|
|
278
|
+
return where;
|
|
279
|
+
}
|
|
280
|
+
/** Was this WHERE object's combinator synthesized by Turbine? */
|
|
281
|
+
export function isInternalCombinator(where) {
|
|
282
|
+
return (typeof where === 'object' && where !== null && where[INTERNAL_COMBINATOR] === true);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Escape single quotes for use as string keys in json_build_object().
|
|
286
|
+
* Doubles single quotes per SQL quoting rules.
|
|
287
|
+
*/
|
|
288
|
+
export function escSingleQuote(s) {
|
|
289
|
+
return s.replace(/'/g, "''");
|
|
290
|
+
}
|
|
291
|
+
const LIKE_META = /[\\%_]/;
|
|
292
|
+
const LIKE_META_G = /[\\%_]/g;
|
|
293
|
+
/**
|
|
294
|
+
* Escape LIKE pattern metacharacters: %, _, and \.
|
|
295
|
+
* Must be used with `ESCAPE '\'` in the LIKE clause.
|
|
296
|
+
*/
|
|
297
|
+
export function escapeLike(value) {
|
|
298
|
+
// One pass, and none at all for the common operand with no metacharacter.
|
|
299
|
+
// Identical output to escaping `\` then `%` then `_` in turn: the backslashes
|
|
300
|
+
// the first step adds are never `%` or `_`, so the steps never interact.
|
|
301
|
+
return LIKE_META.test(value) ? value.replace(LIKE_META_G, '\\$&') : value;
|
|
302
|
+
}
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
// LRU cache, bounded SQL template cache to prevent memory leaks
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
/**
|
|
307
|
+
* Simple LRU (Least Recently Used) cache with a fixed maximum size.
|
|
308
|
+
* When the cache exceeds maxSize, the oldest (least recently used) entry is
|
|
309
|
+
* evicted. Uses Map insertion order, so EVICTION is O(1).
|
|
310
|
+
*
|
|
311
|
+
* The access-order reorder in {@link get} is not: `Map.delete` + `Map.set`
|
|
312
|
+
* leaves a tombstone, and V8 rehashes the whole table once live plus deleted
|
|
313
|
+
* entries reach capacity, so the reorder amortizes to O(capacity) per hit.
|
|
314
|
+
* At the 1,000-entry default that measured 1,356 ns against 2.6 ns for a plain
|
|
315
|
+
* `Map.get`, on the hottest lookup in the SQL build. See {@link get} for why
|
|
316
|
+
* skipping it below capacity is not merely an optimization but exact.
|
|
317
|
+
*/
|
|
318
|
+
export class LRUCache {
|
|
319
|
+
maxSize;
|
|
320
|
+
cache = new Map();
|
|
321
|
+
constructor(maxSize) {
|
|
322
|
+
this.maxSize = maxSize;
|
|
323
|
+
}
|
|
324
|
+
get(key) {
|
|
325
|
+
const value = this.cache.get(key);
|
|
326
|
+
// Access order is only ever CONSUMED by eviction (`set` drops the first
|
|
327
|
+
// key once the cache is full), so while it is still filling, maintaining
|
|
328
|
+
// that order cannot change WHICH entries are present: nothing is evicted,
|
|
329
|
+
// and the reorder is pure cost. So it starts the moment the cache is full,
|
|
330
|
+
// and from then on every hit reorders exactly as before.
|
|
331
|
+
//
|
|
332
|
+
// What is traded, stated plainly: reads that happened while the cache was
|
|
333
|
+
// filling are not reflected in the order, so the first evictions after it
|
|
334
|
+
// fills can drop an entry that was hot early rather than the true
|
|
335
|
+
// least-recently-used one. Reads after that point are ordered normally, so
|
|
336
|
+
// the effect does not accumulate, and the worst case is one extra SQL
|
|
337
|
+
// rebuild on the next miss. This cache decides speed, never results.
|
|
338
|
+
if (value !== undefined && this.cache.size >= this.maxSize) {
|
|
339
|
+
// Move to end (most recently used)
|
|
340
|
+
this.cache.delete(key);
|
|
341
|
+
this.cache.set(key, value);
|
|
342
|
+
}
|
|
343
|
+
return value;
|
|
344
|
+
}
|
|
345
|
+
set(key, value) {
|
|
346
|
+
if (this.cache.has(key)) {
|
|
347
|
+
this.cache.delete(key);
|
|
348
|
+
}
|
|
349
|
+
else if (this.cache.size >= this.maxSize) {
|
|
350
|
+
// Delete oldest (first) entry
|
|
351
|
+
const firstKey = this.cache.keys().next().value;
|
|
352
|
+
if (firstKey !== undefined)
|
|
353
|
+
this.cache.delete(firstKey);
|
|
354
|
+
}
|
|
355
|
+
this.cache.set(key, value);
|
|
356
|
+
}
|
|
357
|
+
get size() {
|
|
358
|
+
return this.cache.size;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* FNV-1a 64-bit hash returning 16 lowercase hex chars.
|
|
363
|
+
* Single-loop string iteration. Uses BigInt for 64-bit math.
|
|
364
|
+
*
|
|
365
|
+
* @internal Exported for testing only.
|
|
366
|
+
*/
|
|
367
|
+
export function fnv1a64Hex(s) {
|
|
368
|
+
// FNV-1a offset basis and prime for 64-bit
|
|
369
|
+
let hash = 0xcbf29ce484222325n;
|
|
370
|
+
const prime = 0x100000001b3n;
|
|
371
|
+
const mask = 0xffffffffffffffffn; // 64-bit mask
|
|
372
|
+
for (let i = 0; i < s.length; i++) {
|
|
373
|
+
hash ^= BigInt(s.charCodeAt(i));
|
|
374
|
+
hash = (hash * prime) & mask;
|
|
375
|
+
}
|
|
376
|
+
return hash.toString(16).padStart(16, '0');
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Derive a prepared-statement name from a SQL string.
|
|
380
|
+
* Format: `t_<16hex>`, always 18 chars, well under NAMEDATALEN (63).
|
|
381
|
+
*
|
|
382
|
+
* @internal Exported for testing only.
|
|
383
|
+
*/
|
|
384
|
+
export function sqlToPreparedName(sql) {
|
|
385
|
+
return `t_${fnv1a64Hex(sql)}`;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* How many distinct statement names one process hands out. Every connection
|
|
389
|
+
* keeps each named statement it has prepared, at 9 to 45 KB of server memory
|
|
390
|
+
* apiece, until the connection closes, so the number of names is what bounds
|
|
391
|
+
* that memory. A statement past the budget is sent unnamed: parsed on every
|
|
392
|
+
* execution and never kept, which costs a few microseconds on a cheap query.
|
|
393
|
+
*/
|
|
394
|
+
export const PREPARED_STATEMENT_BUDGET = 200;
|
|
395
|
+
/** `Symbol.for` so the ESM and CJS copies of this module share one budget. */
|
|
396
|
+
const PREPARED_NAMES = Symbol.for('turbine.preparedStatementNames');
|
|
397
|
+
function preparedNames() {
|
|
398
|
+
const holder = globalThis;
|
|
399
|
+
let names = holder[PREPARED_NAMES];
|
|
400
|
+
if (!names) {
|
|
401
|
+
names = new Set();
|
|
402
|
+
holder[PREPARED_NAMES] = names;
|
|
403
|
+
}
|
|
404
|
+
return names;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* The prepared-statement name for `sql`, or `''` (send it unnamed) once the
|
|
408
|
+
* process has named {@link PREPARED_STATEMENT_BUDGET} other statements.
|
|
409
|
+
*
|
|
410
|
+
* The first shapes a process runs keep their names for its lifetime, which in
|
|
411
|
+
* practice are its hot shapes. A server-side `DEALLOCATE` cannot replace this:
|
|
412
|
+
* a pooled query does not know which connection it will run on, and a
|
|
413
|
+
* connection keeps every name it ever prepared.
|
|
414
|
+
*/
|
|
415
|
+
export function boundedPreparedName(sql) {
|
|
416
|
+
return claimPreparedName(sqlToPreparedName(sql));
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Claim an already derived statement name from the same budget as
|
|
420
|
+
* {@link boundedPreparedName}: `name` itself, or `''` (send it unnamed) once
|
|
421
|
+
* the budget is spent. `sqlComment`'s `c_` names (query/sql-comment.ts) are
|
|
422
|
+
* claimed here, so a commented statement costs one slot like any other.
|
|
423
|
+
*/
|
|
424
|
+
export function claimPreparedName(name) {
|
|
425
|
+
const names = preparedNames();
|
|
426
|
+
if (names.has(name))
|
|
427
|
+
return name;
|
|
428
|
+
if (names.size >= PREPARED_STATEMENT_BUDGET)
|
|
429
|
+
return '';
|
|
430
|
+
names.add(name);
|
|
431
|
+
return name;
|
|
432
|
+
}
|
|
433
|
+
/** @internal Tests only: forget every name handed out. */
|
|
434
|
+
export function resetPreparedNameBudget() {
|
|
435
|
+
preparedNames().clear();
|
|
436
|
+
}
|
|
437
|
+
function argsRewriteError(model, action, path) {
|
|
438
|
+
return new TypeError(`[turbine] middleware cannot change \`params.${path}\` on ${model}.${action}: the query is compiled from the ` +
|
|
439
|
+
'arguments the caller passed, so a change made in middleware would not reliably reach it. Put the ' +
|
|
440
|
+
'condition in the query itself, or use `globalFilters` for a filter that applies to every query.');
|
|
441
|
+
}
|
|
442
|
+
/** Plain objects and arrays are copied; a Date, Buffer, class instance or other value is shared as it is. */
|
|
443
|
+
function isPlainContainer(value) {
|
|
444
|
+
if (value === null || typeof value !== 'object')
|
|
445
|
+
return false;
|
|
446
|
+
if (Array.isArray(value))
|
|
447
|
+
return true;
|
|
448
|
+
const proto = Object.getPrototypeOf(value);
|
|
449
|
+
return proto === Object.prototype || proto === null;
|
|
450
|
+
}
|
|
451
|
+
/** Nesting past this is shared, not copied, so a cyclic object cannot recurse without end. */
|
|
452
|
+
const MIDDLEWARE_ARGS_MAX_DEPTH = 100;
|
|
453
|
+
/**
|
|
454
|
+
* A copy of `value` that middleware may read, spread, serialize or
|
|
455
|
+
* `structuredClone`: plain objects and arrays are copied at every depth, and
|
|
456
|
+
* everything else (Date, Buffer, bigint, symbol, class instance) is shared.
|
|
457
|
+
* Symbol-keyed properties are copied by descriptor, so the markers the
|
|
458
|
+
* pipeline reads (the internal-combinator brand, the inclusive-cursor flag,
|
|
459
|
+
* column and expression brands) are on the copy exactly as on the original,
|
|
460
|
+
* non-enumerable ones included.
|
|
461
|
+
*/
|
|
462
|
+
function copyArgs(value, depth) {
|
|
463
|
+
if (depth > MIDDLEWARE_ARGS_MAX_DEPTH || !isPlainContainer(value))
|
|
464
|
+
return value;
|
|
465
|
+
let out;
|
|
466
|
+
if (Array.isArray(value)) {
|
|
467
|
+
const items = new Array(value.length);
|
|
468
|
+
// A long list of ids is the common big argument; keep its scalars off the call path.
|
|
469
|
+
for (let i = 0; i < value.length; i++) {
|
|
470
|
+
const item = value[i];
|
|
471
|
+
items[i] = item !== null && typeof item === 'object' ? copyArgs(item, depth + 1) : item;
|
|
472
|
+
}
|
|
473
|
+
out = items;
|
|
474
|
+
}
|
|
475
|
+
else {
|
|
476
|
+
out = Object.getPrototypeOf(value) === null ? Object.create(null) : {};
|
|
477
|
+
for (const key of Object.keys(value)) {
|
|
478
|
+
const item = value[key];
|
|
479
|
+
const copied = item !== null && typeof item === 'object' ? copyArgs(item, depth + 1) : item;
|
|
480
|
+
// `__proto__` from JSON.parse is an own key; assigning it would set the prototype.
|
|
481
|
+
if (key === '__proto__')
|
|
482
|
+
Object.defineProperty(out, key, { value: copied, enumerable: true, writable: true, configurable: true });
|
|
483
|
+
else
|
|
484
|
+
out[key] = copied;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
for (const sym of Object.getOwnPropertySymbols(value)) {
|
|
488
|
+
Object.defineProperty(out, sym, Object.getOwnPropertyDescriptor(value, sym));
|
|
489
|
+
}
|
|
490
|
+
return out;
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Where `b` first differs from `a`, as a path suffix (`.where.id`, or `''` for
|
|
494
|
+
* the values themselves), or undefined when they are structurally equal. The
|
|
495
|
+
* suffix is built on the way back out, so an equal pair costs no string work.
|
|
496
|
+
*/
|
|
497
|
+
function argsDifference(a, b, depth) {
|
|
498
|
+
if (Object.is(a, b))
|
|
499
|
+
return undefined;
|
|
500
|
+
if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object')
|
|
501
|
+
return '';
|
|
502
|
+
if (a instanceof Date || b instanceof Date) {
|
|
503
|
+
return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime()) ? undefined : '';
|
|
504
|
+
}
|
|
505
|
+
if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {
|
|
506
|
+
if (!(ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) || a.byteLength !== b.byteLength)
|
|
507
|
+
return '';
|
|
508
|
+
const x = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
|
|
509
|
+
const y = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
|
|
510
|
+
for (let i = 0; i < x.length; i++)
|
|
511
|
+
if (x[i] !== y[i])
|
|
512
|
+
return '';
|
|
513
|
+
return undefined;
|
|
514
|
+
}
|
|
515
|
+
if (a instanceof RegExp || b instanceof RegExp)
|
|
516
|
+
return String(a) === String(b) ? undefined : '';
|
|
517
|
+
if (a instanceof Map || a instanceof Set || b instanceof Map || b instanceof Set)
|
|
518
|
+
return '';
|
|
519
|
+
if (Array.isArray(a) !== Array.isArray(b) || depth > MIDDLEWARE_ARGS_MAX_DEPTH)
|
|
520
|
+
return '';
|
|
521
|
+
if (Array.isArray(a)) {
|
|
522
|
+
const other = b;
|
|
523
|
+
const shared = Math.min(a.length, other.length);
|
|
524
|
+
for (let i = 0; i < shared; i++) {
|
|
525
|
+
if (Object.is(a[i], other[i]))
|
|
526
|
+
continue;
|
|
527
|
+
const inner = argsDifference(a[i], other[i], depth + 1);
|
|
528
|
+
if (inner !== undefined)
|
|
529
|
+
return `.${i}${inner}`;
|
|
530
|
+
}
|
|
531
|
+
return a.length === other.length ? undefined : `.${shared}`;
|
|
532
|
+
}
|
|
533
|
+
const left = a;
|
|
534
|
+
const right = b;
|
|
535
|
+
for (const key of Object.keys(left)) {
|
|
536
|
+
if (!Object.hasOwn(right, key))
|
|
537
|
+
return `.${key}`;
|
|
538
|
+
const inner = argsDifference(left[key], right[key], depth + 1);
|
|
539
|
+
if (inner !== undefined)
|
|
540
|
+
return `.${key}${inner}`;
|
|
541
|
+
}
|
|
542
|
+
for (const key of Object.keys(right))
|
|
543
|
+
if (!Object.hasOwn(left, key))
|
|
544
|
+
return `.${key}`;
|
|
545
|
+
return undefined;
|
|
546
|
+
}
|
|
547
|
+
const MIDDLEWARE_ARGS = new WeakMap();
|
|
548
|
+
/** The key Node's `util.inspect` looks for, from the global registry so no `node:` import is needed. */
|
|
549
|
+
const NODE_INSPECT = Symbol.for('nodejs.util.inspect.custom');
|
|
550
|
+
/** Makes `console.log(params)` show the values rather than an accessor. Not own, so a spread of `params` never carries it. */
|
|
551
|
+
const MIDDLEWARE_PARAMS_PROTOTYPE = Object.defineProperty({}, NODE_INSPECT, {
|
|
552
|
+
value(_depth, options, inspect) {
|
|
553
|
+
return inspect({ model: this.model, action: this.action, args: this.args }, options);
|
|
554
|
+
},
|
|
555
|
+
});
|
|
556
|
+
/**
|
|
557
|
+
* The `params` a middleware receives. `params.args` is a plain copy of the
|
|
558
|
+
* caller's args, made when it is first read, so middleware can read it, spread
|
|
559
|
+
* it, serialize it and `structuredClone` it, and one that never reads it pays
|
|
560
|
+
* nothing.
|
|
561
|
+
*
|
|
562
|
+
* It is a copy because the query is compiled from the caller's args, not from
|
|
563
|
+
* what middleware sees. A change to the copy would never reach the query, so
|
|
564
|
+
* {@link assertMiddlewareArgsKept} refuses it, naming the path, when the
|
|
565
|
+
* middleware calls `next`. That check compares contents, which is why the copy
|
|
566
|
+
* is not frozen: a frozen object ignores a write silently in a script that is
|
|
567
|
+
* not in strict mode, and a filter added there would be dropped without a word.
|
|
568
|
+
* Assigning to `params.args` itself throws at once.
|
|
569
|
+
*/
|
|
570
|
+
export function readOnlyMiddlewareParams(model, action, args) {
|
|
571
|
+
const state = { model, action, original: args, copy: undefined };
|
|
572
|
+
const params = {
|
|
573
|
+
__proto__: MIDDLEWARE_PARAMS_PROTOTYPE,
|
|
574
|
+
model,
|
|
575
|
+
action,
|
|
576
|
+
get args() {
|
|
577
|
+
if (state.copy === undefined)
|
|
578
|
+
state.copy = copyArgs(args, 0);
|
|
579
|
+
return state.copy;
|
|
580
|
+
},
|
|
581
|
+
set args(_replacement) {
|
|
582
|
+
throw argsRewriteError(model, action, 'args');
|
|
583
|
+
},
|
|
584
|
+
};
|
|
585
|
+
MIDDLEWARE_ARGS.set(params, state);
|
|
586
|
+
return params;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Refuse a `next(p)` whose `p.args` is not the caller's args: one that
|
|
590
|
+
* middleware changed in place, or replaced with an object that differs from
|
|
591
|
+
* them. A copy that is structurally equal passes (`structuredClone(params.args)`,
|
|
592
|
+
* `{ ...params.args }`), because nothing it would change is lost. Throws a
|
|
593
|
+
* TypeError naming the first path that differs.
|
|
594
|
+
*/
|
|
595
|
+
export function assertMiddlewareArgsKept(handedOut, passed) {
|
|
596
|
+
const state = MIDDLEWARE_ARGS.get(handedOut);
|
|
597
|
+
if (passed === handedOut) {
|
|
598
|
+
if (handedOut.model !== state.model)
|
|
599
|
+
throw argsRewriteError(state.model, state.action, 'model');
|
|
600
|
+
if (handedOut.action !== state.action)
|
|
601
|
+
throw argsRewriteError(state.model, state.action, 'action');
|
|
602
|
+
// Nothing has read the args, so nothing could have changed them.
|
|
603
|
+
if (state.copy === undefined)
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
const given = passed?.args;
|
|
607
|
+
if (given === state.original)
|
|
608
|
+
return;
|
|
609
|
+
const changed = argsDifference(state.original, given, 0);
|
|
610
|
+
if (changed !== undefined)
|
|
611
|
+
throw argsRewriteError(state.model, state.action, `args${changed}`);
|
|
612
|
+
}
|
|
613
|
+
/** Whether `pool` is a node-postgres `Pool`, whose checkouts are real backend connections. */
|
|
614
|
+
export function isNodePostgresPool(pool) {
|
|
615
|
+
const Pool = pg.Pool;
|
|
616
|
+
return typeof Pool === 'function' && pool instanceof Pool;
|
|
617
|
+
}
|
|
618
|
+
/** Standard native pg text rows, including typed proxies over caller-owned pools. */
|
|
619
|
+
export function canReadArrayRows(pool) {
|
|
620
|
+
if (!isNodePostgresPool(pool) || Object.getOwnPropertyDescriptor(pool, 'Client')?.value !== pg.Client)
|
|
621
|
+
return false;
|
|
622
|
+
const { options, _clients: clients } = pool;
|
|
623
|
+
// A pool that keeps its options or its connections somewhere else keeps
|
|
624
|
+
// object rows, and so does one holding a slot that is not a connection.
|
|
625
|
+
if (!options || !Array.isArray(clients))
|
|
626
|
+
return false;
|
|
627
|
+
return (!pg.defaults?.binary &&
|
|
628
|
+
!options.binary &&
|
|
629
|
+
!clients.some((client) => !client || client.binary));
|
|
630
|
+
}
|
|
631
|
+
/** Whether `client` is a node-postgres connection a cancel request can reach. */
|
|
632
|
+
export function canCancelBackend(client) {
|
|
633
|
+
const c = client;
|
|
634
|
+
return (typeof pg.Connection === 'function' &&
|
|
635
|
+
!!c &&
|
|
636
|
+
typeof c.processID === 'number' &&
|
|
637
|
+
typeof c.secretKey === 'number' &&
|
|
638
|
+
(typeof c.port === 'number' || typeof c.port === 'string'));
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Ask the server to cancel whatever `client`'s backend is running, with the
|
|
642
|
+
* protocol's CancelRequest: a separate short connection carrying the backend's
|
|
643
|
+
* process id and secret key. No login, no session state, and a pooler forwards
|
|
644
|
+
* it to the right server backend, which `pg_cancel_backend(pid)` through a
|
|
645
|
+
* pooler would not.
|
|
646
|
+
*
|
|
647
|
+
* Resolves `true` once the server has closed the cancel connection, i.e. has
|
|
648
|
+
* signalled the backend; `false` when the request could not be delivered
|
|
649
|
+
* within `waitMs`. A cancel that arrives after the statement finished is
|
|
650
|
+
* ignored by the server.
|
|
651
|
+
*/
|
|
652
|
+
export function sendCancelRequest(client, waitMs) {
|
|
653
|
+
if (!canCancelBackend(client))
|
|
654
|
+
return Promise.resolve(false);
|
|
655
|
+
const target = client;
|
|
656
|
+
const Connection = pg.Connection;
|
|
657
|
+
return new Promise((resolve) => {
|
|
658
|
+
let con;
|
|
659
|
+
let sent = false;
|
|
660
|
+
let done = false;
|
|
661
|
+
const finish = (delivered) => {
|
|
662
|
+
if (done)
|
|
663
|
+
return;
|
|
664
|
+
done = true;
|
|
665
|
+
clearTimeout(timer);
|
|
666
|
+
try {
|
|
667
|
+
con?.stream?.destroy?.();
|
|
668
|
+
}
|
|
669
|
+
catch {
|
|
670
|
+
// already closed
|
|
671
|
+
}
|
|
672
|
+
resolve(delivered);
|
|
673
|
+
};
|
|
674
|
+
const timer = setTimeout(() => finish(false), waitMs);
|
|
675
|
+
try {
|
|
676
|
+
con = new Connection({ ssl: target.ssl, sslNegotiation: target.sslNegotiation });
|
|
677
|
+
const send = () => {
|
|
678
|
+
sent = true;
|
|
679
|
+
con?.cancel(target.processID, target.secretKey);
|
|
680
|
+
};
|
|
681
|
+
con.on('error', () => finish(false));
|
|
682
|
+
con.on('end', () => finish(sent));
|
|
683
|
+
con.on('connect', () => {
|
|
684
|
+
if (!target.ssl)
|
|
685
|
+
send();
|
|
686
|
+
else if (target.sslNegotiation !== 'direct')
|
|
687
|
+
con?.requestSsl();
|
|
688
|
+
});
|
|
689
|
+
con.on('sslconnect', send);
|
|
690
|
+
const host = typeof target.host === 'string' ? target.host : undefined;
|
|
691
|
+
if (host?.startsWith('/'))
|
|
692
|
+
con.connect(`${host}/.s.PGSQL.${String(target.port)}`);
|
|
693
|
+
else
|
|
694
|
+
con.connect(target.port, host);
|
|
695
|
+
}
|
|
696
|
+
catch {
|
|
697
|
+
finish(false);
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
/** Known operator keys, used to detect operator objects vs plain values */
|
|
702
|
+
export const OPERATOR_KEYS = new Set([
|
|
703
|
+
'equals',
|
|
704
|
+
'gt',
|
|
705
|
+
'gte',
|
|
706
|
+
'lt',
|
|
707
|
+
'lte',
|
|
708
|
+
'not',
|
|
709
|
+
'in',
|
|
710
|
+
'notIn',
|
|
711
|
+
'contains',
|
|
712
|
+
'startsWith',
|
|
713
|
+
'endsWith',
|
|
714
|
+
'mode',
|
|
715
|
+
]);
|
|
716
|
+
// ---------------------------------------------------------------------------
|
|
717
|
+
// Composite key correlation helper
|
|
718
|
+
// ---------------------------------------------------------------------------
|
|
719
|
+
/**
|
|
720
|
+
* Build a correlation clause joining columns between two table references.
|
|
721
|
+
* Handles both single-column (string) and multi-column (string[]) foreign keys.
|
|
722
|
+
*
|
|
723
|
+
* For single-column: `"alias"."col" = "parent"."col"`
|
|
724
|
+
* For multi-column: `"alias"."col_a" = "parent"."ref_a" AND "alias"."col_b" = "parent"."ref_b"`
|
|
725
|
+
*/
|
|
726
|
+
export function buildCorrelation(leftRef, leftColumns, rightRef, rightColumns) {
|
|
727
|
+
const leftCols = Array.isArray(leftColumns) ? leftColumns : [leftColumns];
|
|
728
|
+
const rightCols = Array.isArray(rightColumns) ? rightColumns : [rightColumns];
|
|
729
|
+
return leftCols
|
|
730
|
+
.map((col, i) => `${leftRef}.${quoteIdent(col)} = ${rightRef}.${quoteIdent(rightCols[i])}`)
|
|
731
|
+
.join(' AND ');
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Render a JS `Date` as a TIME-OF-DAY literal for a `time` / `timetz` column.
|
|
735
|
+
*
|
|
736
|
+
* Which time of day? The **UTC** components of the Date, never the process
|
|
737
|
+
* local zone. That is what Prisma does (`new Date('1970-01-01T09:00:00Z')`
|
|
738
|
+
* written to a `@db.Time(6)` column stores `09:00:00`), and the affected
|
|
739
|
+
* consumers are porting from Prisma, so Prisma is the contract. It is also the
|
|
740
|
+
* only choice that round-trips: the same Date produces the same literal no
|
|
741
|
+
* matter where the process runs.
|
|
742
|
+
*
|
|
743
|
+
* `timetz` gets an explicit `+00:00`, because the value's zone IS UTC and
|
|
744
|
+
* omitting it would let Postgres attach the session's `TimeZone` instead.
|
|
745
|
+
* Fractional seconds are emitted only when non-zero, so an even-second Date
|
|
746
|
+
* binds the plain `HH:MM:SS` form.
|
|
747
|
+
*/
|
|
748
|
+
export function toTimeOfDayLiteral(value, kind) {
|
|
749
|
+
const pad = (n, width = 2) => String(n).padStart(width, '0');
|
|
750
|
+
const ms = value.getUTCMilliseconds();
|
|
751
|
+
const literal = `${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}` +
|
|
752
|
+
(ms === 0 ? '' : `.${pad(ms, 3)}`);
|
|
753
|
+
return kind === 'timetz' ? `${literal}+00:00` : literal;
|
|
754
|
+
}
|
|
755
|
+
/** Render the UTC calendar date of a `Date` as `YYYY-MM-DD`. */
|
|
756
|
+
function utcDatePart(value) {
|
|
757
|
+
const year = value.getUTCFullYear();
|
|
758
|
+
const y = year < 0 ? `-${String(-year).padStart(4, '0')}` : String(year).padStart(4, '0');
|
|
759
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
760
|
+
return `${y}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}`;
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Render a JS `Date` as a literal for a zone-less `date` / `timestamp` column,
|
|
764
|
+
* using the value's **UTC** components.
|
|
765
|
+
*
|
|
766
|
+
* This is the write-side mirror of `parseDbDate`, which reads an offset-less
|
|
767
|
+
* database value back as UTC. Without it the driver serializes the Date with
|
|
768
|
+
* the PROCESS's offset (`prepareValue` → `dateToString`), so a `timestamp`
|
|
769
|
+
* column is not round-trip stable outside a UTC process: writing
|
|
770
|
+
* `2026-07-25T00:00Z` from `America/Los_Angeles` stores
|
|
771
|
+
* `2026-07-24 17:00:00` and reads back as `2026-07-24T17:00Z`. It also matches
|
|
772
|
+
* the choice {@link toTimeOfDayLiteral} already makes for `time` columns, and
|
|
773
|
+
* Prisma, which writes UTC components to zone-less columns.
|
|
774
|
+
*
|
|
775
|
+
* `timestamptz` is NOT handled here (and must not be): it stores a real
|
|
776
|
+
* instant, so the driver's local-offset string is already correct.
|
|
777
|
+
*/
|
|
778
|
+
export function toLocalDateTimeLiteral(value, kind) {
|
|
779
|
+
const datePart = utcDatePart(value);
|
|
780
|
+
if (kind === 'date')
|
|
781
|
+
return datePart;
|
|
782
|
+
return `${datePart} ${toTimeOfDayLiteral(value, 'time')}`;
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Classify a column's database type for temporal bind rewriting.
|
|
786
|
+
*
|
|
787
|
+
* `utcDateTimes: false` restricts the classification to the time-of-day types,
|
|
788
|
+
* whose rewrite is a hard-error fix (Postgres rejects an ISO timestamp for a
|
|
789
|
+
* `time` column outright) rather than a value correction.
|
|
790
|
+
*/
|
|
791
|
+
export function temporalBindKind(dbType, utcDateTimes = true) {
|
|
792
|
+
const timeKind = timeOfDayKind(dbType);
|
|
793
|
+
if (timeKind)
|
|
794
|
+
return timeKind;
|
|
795
|
+
return utcDateTimes ? localDateTimeKind(dbType) : null;
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Rewrite one bound value for a temporal column: a JS `Date` on a `time` /
|
|
799
|
+
* `timetz` / `date` / `timestamp` column becomes the corresponding UTC literal,
|
|
800
|
+
* and an array of Dates on such a column is rewritten element-wise (the
|
|
801
|
+
* per-element rewrite is what a `time[]` column needs, and matches the scalar
|
|
802
|
+
* case rather than silently binding an ISO timestamp).
|
|
803
|
+
*
|
|
804
|
+
* Everything else, every non-Date, every non-temporal column, and every
|
|
805
|
+
* `timestamptz` column, is returned by IDENTITY, so this is a byte-for-byte
|
|
806
|
+
* no-op outside the shapes above.
|
|
807
|
+
*/
|
|
808
|
+
export function coerceTemporalValue(dbType, value, utcDateTimes = true) {
|
|
809
|
+
const isDate = value instanceof Date;
|
|
810
|
+
if (!isDate && !Array.isArray(value))
|
|
811
|
+
return value;
|
|
812
|
+
if (isDate && Number.isNaN(value.getTime()))
|
|
813
|
+
return value;
|
|
814
|
+
// An array value is either an `in`/`notIn` list on a scalar temporal column
|
|
815
|
+
// (type already the element type) or the value of an array column, whose
|
|
816
|
+
// introspected type is the `_time` / `_timestamp` array spelling.
|
|
817
|
+
const kind = temporalBindKind(isDate ? dbType : arrayElementDbType(dbType), utcDateTimes);
|
|
818
|
+
if (!kind)
|
|
819
|
+
return value;
|
|
820
|
+
if (isDate)
|
|
821
|
+
return renderTemporal(value, kind);
|
|
822
|
+
// Rewrite only if the list actually holds a Date, so a string list stays
|
|
823
|
+
// byte-identical (and the same array instance is returned).
|
|
824
|
+
if (!value.some((v) => v instanceof Date))
|
|
825
|
+
return value;
|
|
826
|
+
return value.map((v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? renderTemporal(v, kind) : v));
|
|
827
|
+
}
|
|
828
|
+
/** `_time` → `time`, `time[]` → `time`, anything else unchanged. */
|
|
829
|
+
function arrayElementDbType(dbType) {
|
|
830
|
+
if (!dbType)
|
|
831
|
+
return dbType;
|
|
832
|
+
if (dbType.startsWith('_'))
|
|
833
|
+
return dbType.slice(1);
|
|
834
|
+
return dbType.endsWith('[]') ? dbType.slice(0, -2) : dbType;
|
|
835
|
+
}
|
|
836
|
+
function renderTemporal(value, kind) {
|
|
837
|
+
return kind === 'date' || kind === 'timestamp'
|
|
838
|
+
? toLocalDateTimeLiteral(value, kind)
|
|
839
|
+
: toTimeOfDayLiteral(value, kind);
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Matches an explicit timezone suffix on a date-time string: a trailing `Z`
|
|
843
|
+
* or a `±HH`, `±HHMM`, `±HH:MM` offset.
|
|
844
|
+
*/
|
|
845
|
+
const TZ_SUFFIX_RE = /(?:Z|[+-]\d{2}(?::?\d{2})?)$/;
|
|
846
|
+
const COLON_CHAR = 58;
|
|
847
|
+
const PLUS_CHAR = 43;
|
|
848
|
+
const MINUS_CHAR = 45;
|
|
849
|
+
/** `0`-`9` as a char code. */
|
|
850
|
+
function isDigitCode(code) {
|
|
851
|
+
return code >= 48 && code <= 57;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Parse a database date-time string deterministically.
|
|
855
|
+
*
|
|
856
|
+
* Postgres `timestamp` (without time zone) values arrive with no offset -
|
|
857
|
+
* both from the driver and from `json_agg`/`json_build_object` subquery JSON
|
|
858
|
+
* (`2026-07-07T17:15:41.896`). JavaScript's `new Date()` interprets such
|
|
859
|
+
* strings in the SERVER'S LOCAL TIME ZONE, so the same row parses to a
|
|
860
|
+
* different instant depending on where the code runs. The universal ORM
|
|
861
|
+
* convention (Prisma, Rails, Django) is to treat offset-less timestamps as
|
|
862
|
+
* UTC, that is also the only interpretation that round-trips: Postgres
|
|
863
|
+
* stores exactly the wall-clock fields you sent.
|
|
864
|
+
*
|
|
865
|
+
* Strings that carry an explicit offset (`timestamptz` output) are parsed
|
|
866
|
+
* as-is.
|
|
867
|
+
*/
|
|
868
|
+
export function parseDbDate(value) {
|
|
869
|
+
const date = parseDbDateCommon(value);
|
|
870
|
+
// The shapes JS cannot parse (a BC year, an offset with seconds, a year past
|
|
871
|
+
// 9999) come out invalid; only those pay for the general parse.
|
|
872
|
+
return Number.isNaN(date.getTime()) ? (parseDbDateGeneral(value) ?? date) : date;
|
|
873
|
+
}
|
|
874
|
+
function parseDbDateCommon(value) {
|
|
875
|
+
// Fast path for the shape `timestamptz` arrives in, a trailing `±HH:MM`
|
|
876
|
+
// offset (`2026-07-07T17:15:41.896+00:00`). It is exactly the general path's
|
|
877
|
+
// answer for that shape, not an approximation of it: the string contains a
|
|
878
|
+
// ':' (at length-3), TZ_SUFFIX_RE matches, and neither normalizing replace
|
|
879
|
+
// below can fire (the first needs four digits after the sign, the second two
|
|
880
|
+
// digits at the very end after it), so that path also ends in
|
|
881
|
+
// `new Date(value)`. All six offset characters are checked, so a near miss
|
|
882
|
+
// (`+0a:00`, `05:30` without a sign) still takes the general path. It skips
|
|
883
|
+
// one regex test and two regex replaces per value, which on a nested read is
|
|
884
|
+
// the single largest cost in the decode. The invalid-date fallback in
|
|
885
|
+
// parseDbDate still runs on the result, so a BC or five-digit year is
|
|
886
|
+
// unchanged.
|
|
887
|
+
const n = value.length;
|
|
888
|
+
if (n >= 6 && value.charCodeAt(n - 3) === COLON_CHAR) {
|
|
889
|
+
const sign = value.charCodeAt(n - 6);
|
|
890
|
+
if ((sign === PLUS_CHAR || sign === MINUS_CHAR) &&
|
|
891
|
+
isDigitCode(value.charCodeAt(n - 5)) &&
|
|
892
|
+
isDigitCode(value.charCodeAt(n - 4)) &&
|
|
893
|
+
isDigitCode(value.charCodeAt(n - 2)) &&
|
|
894
|
+
isDigitCode(value.charCodeAt(n - 1))) {
|
|
895
|
+
return new Date(value);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
// Date-only values (`2026-07-07`, from `date` columns in json_agg output)
|
|
899
|
+
// have no time to zone-pin, and their `-07` tail must not be read as an
|
|
900
|
+
// offset. JS parses bare ISO dates as UTC midnight already. A terminal Z
|
|
901
|
+
// also takes new Date unchanged: neither offset-normalizing replace below
|
|
902
|
+
// can match it. Keep parseDbDate's invalid-date fallback on both paths.
|
|
903
|
+
if (!value.includes(':') || value.endsWith('Z'))
|
|
904
|
+
return new Date(value);
|
|
905
|
+
if (TZ_SUFFIX_RE.test(value)) {
|
|
906
|
+
// JS Date can't parse colon-less (`-0430`) or bare-hour (`+02`) offsets -
|
|
907
|
+
// normalize both to `±HH:MM`. Postgres emits the bare-hour form for
|
|
908
|
+
// whole-hour zones in some text outputs.
|
|
909
|
+
return new Date(value.replace(/([+-]\d{2})(\d{2})$/, '$1:$2').replace(/([+-]\d{2})$/, '$1:00'));
|
|
910
|
+
}
|
|
911
|
+
// normalize `YYYY-MM-DD HH:MM:SS` (driver form) to ISO before pinning UTC
|
|
912
|
+
return new Date(`${value.replace(' ', 'T')}Z`);
|
|
913
|
+
}
|
|
914
|
+
const DB_DATE_GENERAL_RE = /^(\d{4,})-(\d\d)-(\d\d)(?:[T ](\d\d):(\d\d):(\d\d)(\.\d+)?)?(?:(Z)|([+-])(\d\d)(?::?(\d\d))?(?::?(\d\d))?)?( BC)?$/;
|
|
915
|
+
/**
|
|
916
|
+
* The Postgres renderings JS `Date` cannot parse: a ` BC` suffix, a
|
|
917
|
+
* local-mean-time offset with seconds (`-04:56:02`, any zone before about
|
|
918
|
+
* 1900), and years of five or more digits. Offset-less text is read as UTC,
|
|
919
|
+
* as in {@link parseDbDate}. `undefined` when the text is none of these.
|
|
920
|
+
*/
|
|
921
|
+
function parseDbDateGeneral(value) {
|
|
922
|
+
const m = DB_DATE_GENERAL_RE.exec(value);
|
|
923
|
+
if (!m)
|
|
924
|
+
return undefined;
|
|
925
|
+
let year = Number(m[1]);
|
|
926
|
+
if (m[13])
|
|
927
|
+
year = 1 - year;
|
|
928
|
+
const month = Number(m[2]) - 1;
|
|
929
|
+
const ms = m[7] ? Math.trunc(1000 * Number(`0${m[7]}`)) : 0;
|
|
930
|
+
const date = new Date(Date.UTC(2000, month, Number(m[3]), Number(m[4] ?? 0), Number(m[5] ?? 0), Number(m[6] ?? 0), ms));
|
|
931
|
+
// setUTCFullYear, not Date.UTC: Date.UTC reads years 0-99 as 1900-1999.
|
|
932
|
+
date.setUTCFullYear(year, month, Number(m[3]));
|
|
933
|
+
if (m[9]) {
|
|
934
|
+
const offset = Number(m[10]) * 3600 + Number(m[11] ?? 0) * 60 + Number(m[12] ?? 0);
|
|
935
|
+
return new Date(date.getTime() - (m[9] === '-' ? -offset : offset) * 1000);
|
|
936
|
+
}
|
|
937
|
+
return date;
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Per-cell decode work in a row decode plan (`RowDecodePlan` in builder.ts).
|
|
941
|
+
* Defined here rather than in builder.ts because the positional nested-row
|
|
942
|
+
* plan in relations.ts reads the same codes, and relations.ts cannot import
|
|
943
|
+
* builder.ts.
|
|
944
|
+
*/
|
|
945
|
+
export const CELL_PLAIN = 0;
|
|
946
|
+
export const CELL_TEMPORAL = 1;
|
|
947
|
+
export const CELL_FLOAT = 2;
|
|
948
|
+
export const CELL_FLOAT_ARRAY = 3;
|
|
949
|
+
export const CELL_TEXT_ARRAY = 4;
|
|
950
|
+
/** The dialect's own decode for a type whose storage differs (see `Dialect.decodeColumnValue`). */
|
|
951
|
+
export const CELL_DIALECT = 5;
|
|
952
|
+
/**
|
|
953
|
+
* A float column's value as the driver reads it. JSON has no NaN or infinity,
|
|
954
|
+
* so `json_build_object` renders them as the strings "NaN", "Infinity" and
|
|
955
|
+
* "-Infinity"; every other value passes through.
|
|
956
|
+
*/
|
|
957
|
+
export function readJsonFloat(value) {
|
|
958
|
+
if (typeof value !== 'string')
|
|
959
|
+
return value;
|
|
960
|
+
if (value === 'NaN')
|
|
961
|
+
return Number.NaN;
|
|
962
|
+
if (value === 'Infinity')
|
|
963
|
+
return Number.POSITIVE_INFINITY;
|
|
964
|
+
if (value === '-Infinity')
|
|
965
|
+
return Number.NEGATIVE_INFINITY;
|
|
966
|
+
return value;
|
|
967
|
+
}
|
|
968
|
+
/** {@link readJsonFloat} over a float array (at any depth); the input when nothing changes. */
|
|
969
|
+
export function readJsonFloatArray(value) {
|
|
970
|
+
if (!Array.isArray(value))
|
|
971
|
+
return value;
|
|
972
|
+
let out;
|
|
973
|
+
for (let i = 0; i < value.length; i++) {
|
|
974
|
+
const el = value[i];
|
|
975
|
+
const read = Array.isArray(el) ? readJsonFloatArray(el) : readJsonFloat(el);
|
|
976
|
+
if (read !== el) {
|
|
977
|
+
out ??= value.slice();
|
|
978
|
+
out[i] = read;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
return out ?? value;
|
|
982
|
+
}
|
|
983
|
+
let textArrayParser;
|
|
984
|
+
/**
|
|
985
|
+
* An array column the driver has no parser for (an enum array) arrives as
|
|
986
|
+
* Postgres array text, `{ok,sad}`; read it into an array of strings, as the
|
|
987
|
+
* same column reads through a relation. The input when it cannot be parsed.
|
|
988
|
+
*/
|
|
989
|
+
export function readTextArray(value) {
|
|
990
|
+
if (typeof value !== 'string' || value.charCodeAt(0) !== 123)
|
|
991
|
+
return value;
|
|
992
|
+
try {
|
|
993
|
+
textArrayParser ??= pg.types.arrayParser;
|
|
994
|
+
return textArrayParser.create(value).parse() ?? value;
|
|
995
|
+
}
|
|
996
|
+
catch {
|
|
997
|
+
return value;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Is `value` one of the two representations a Postgres temporal `infinity` /
|
|
1002
|
+
* `-infinity` reaches the ORM row parser in?
|
|
1003
|
+
*
|
|
1004
|
+
* TWO representations, because a temporal column is read two different ways
|
|
1005
|
+
* and they disagree on the wire:
|
|
1006
|
+
*
|
|
1007
|
+
* driver the pg text parser for `timestamp` / `date` does not
|
|
1008
|
+
* recognise the word, so it falls through to the driver's own
|
|
1009
|
+
* parser, which returns the JS NUMBERS `Infinity` /
|
|
1010
|
+
* `-Infinity`. This is what a top-level row, the batched and
|
|
1011
|
+
* flatten strategies, a write `RETURNING` projection and a
|
|
1012
|
+
* `groupBy` key all see.
|
|
1013
|
+
* JSON wire `json_build_object` renders the same value as the STRING
|
|
1014
|
+
* `"infinity"`, and scalar `timestamp` / `timestamptz` are
|
|
1015
|
+
* deliberately absent from {@link JSON_WIRE_COERCION_OIDS},
|
|
1016
|
+
* so no driver parser runs over it. This is what the `'join'`
|
|
1017
|
+
* strategy and the positional encoding see.
|
|
1018
|
+
*
|
|
1019
|
+
* Both are normalized in one place ({@link QueryInterface}'s row parser), to
|
|
1020
|
+
* whichever reading `temporalInfinity` selects (the JS number by default, or
|
|
1021
|
+
* `null`), so the same stored value cannot read differently depending on which
|
|
1022
|
+
* plan the query happened to take. The string form is only ever consulted for a column
|
|
1023
|
+
* the schema says is temporal, so a `text` column holding the word "infinity"
|
|
1024
|
+
* is untouched.
|
|
1025
|
+
*
|
|
1026
|
+
* Not dialect-gated. Postgres is the only engine with an infinite temporal
|
|
1027
|
+
* value, but the row parser is engine-shared and the alternative reading on the
|
|
1028
|
+
* other engines (a stray `'infinity'` string becoming an Invalid Date) is not
|
|
1029
|
+
* one worth preserving.
|
|
1030
|
+
*/
|
|
1031
|
+
export function isTemporalInfinity(value) {
|
|
1032
|
+
if (typeof value === 'number')
|
|
1033
|
+
return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY;
|
|
1034
|
+
return value === 'infinity' || value === '-infinity';
|
|
1035
|
+
}
|
|
1036
|
+
// ---------------------------------------------------------------------------
|
|
1037
|
+
// JSON-wire value coercion (relationLoadStrategy: 'join')
|
|
1038
|
+
// ---------------------------------------------------------------------------
|
|
1039
|
+
/**
|
|
1040
|
+
* Postgres type name → OID, for every type family whose `json_build_object`
|
|
1041
|
+
* rendering is NOT the value the pg driver produces for the same column.
|
|
1042
|
+
*
|
|
1043
|
+
* Why this table exists: the `'join'` strategy reads a relation through
|
|
1044
|
+
* `json_agg(json_build_object(...))`, so its values are whatever
|
|
1045
|
+
* `JSON.parse` makes of Postgres's JSON rendering. Every other read path in
|
|
1046
|
+
* the library, a top-level row, `'batched'`, `'flatten'`, reads the column
|
|
1047
|
+
* through the driver and gets the driver's representation. Measured against
|
|
1048
|
+
* PostgreSQL 17, those two disagree for exactly the families below, which
|
|
1049
|
+
* made the SAME query return a different JS type depending on which plan ran
|
|
1050
|
+
* (and `'auto'` picks the plan from a row-count heuristic, so it could differ
|
|
1051
|
+
* between two runs of one query). Three of these are lossy, not merely
|
|
1052
|
+
* different:
|
|
1053
|
+
*
|
|
1054
|
+
* type driver (target) json_build_object
|
|
1055
|
+
* ──────────── ──────────────────────────── ─────────────────────────────
|
|
1056
|
+
* numeric '1000.50' (string) 1000.5 (number, LOSSY)
|
|
1057
|
+
* int8 '9007199254740993' 9007199254740992 (LOSSY)
|
|
1058
|
+
* bytea Buffer '\xdeadbeef' (string)
|
|
1059
|
+
* date Date (UTC midnight) Date (UTC midnight, by coincidence)
|
|
1060
|
+
* interval { days, hours, … } '1 day 02:03:04' (string)
|
|
1061
|
+
* point { x, y } '(1,2)' (string)
|
|
1062
|
+
* circle { x, y, radius } '<(1,2),3>' (string)
|
|
1063
|
+
*
|
|
1064
|
+
* The array forms diverge the same way, plus `_timestamp`/`_timestamptz`
|
|
1065
|
+
* (driver: `Date[]`; JSON: `string[]`), the scalar `timestamp` /
|
|
1066
|
+
* `timestamptz` are deliberately ABSENT because the existing `dateColumns`
|
|
1067
|
+
* coercion in `parseRow` already lands them on the driver's value, and they
|
|
1068
|
+
* are the hottest column type in a typical schema (no reason to add a cast to
|
|
1069
|
+
* every `created_at`).
|
|
1070
|
+
*
|
|
1071
|
+
* The fix these OIDs drive: emit the column as `col::text` inside
|
|
1072
|
+
* `json_build_object` so the JSON carries the same wire text the driver would
|
|
1073
|
+
* receive, then run the DRIVER'S OWN parser for that OID over it. Parity is
|
|
1074
|
+
* then by construction rather than by coincidence, and it automatically
|
|
1075
|
+
* honours a caller's `pg.types.setTypeParser` (including the int8 parser
|
|
1076
|
+
* TurbineClient itself registers) instead of second-guessing it.
|
|
1077
|
+
*
|
|
1078
|
+
* Postgres-only: the JSON functions and the divergence set are both
|
|
1079
|
+
* engine-specific, so callers gate this on the postgres dialect.
|
|
1080
|
+
*/
|
|
1081
|
+
export const JSON_WIRE_COERCION_OIDS = {
|
|
1082
|
+
numeric: 1700,
|
|
1083
|
+
int8: 20,
|
|
1084
|
+
bytea: 17,
|
|
1085
|
+
date: 1082,
|
|
1086
|
+
interval: 1186,
|
|
1087
|
+
point: 600,
|
|
1088
|
+
circle: 718,
|
|
1089
|
+
_numeric: 1231,
|
|
1090
|
+
_int8: 1016,
|
|
1091
|
+
_bytea: 1001,
|
|
1092
|
+
_date: 1182,
|
|
1093
|
+
_interval: 1187,
|
|
1094
|
+
_point: 1017,
|
|
1095
|
+
_timestamp: 1115,
|
|
1096
|
+
_timestamptz: 1185,
|
|
1097
|
+
};
|
|
1098
|
+
/**
|
|
1099
|
+
* The OID whose driver parser reproduces `pgType`'s driver representation from
|
|
1100
|
+
* its text rendering, or `undefined` when the type's JSON rendering already
|
|
1101
|
+
* matches the driver (the common case: text, uuid, bool, int4, float8, json,
|
|
1102
|
+
* jsonb, arrays of those, …).
|
|
1103
|
+
*/
|
|
1104
|
+
export function jsonWireCoercionOid(pgType) {
|
|
1105
|
+
if (!pgType)
|
|
1106
|
+
return undefined;
|
|
1107
|
+
return JSON_WIRE_COERCION_OIDS[pgType];
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Apply the driver's text parser for `oid` to a JSON-sourced wire string.
|
|
1111
|
+
*
|
|
1112
|
+
* Resolved through `pg.types.getTypeParser` on every call rather than
|
|
1113
|
+
* memoized: parser registration is process-global and happens in the
|
|
1114
|
+
* TurbineClient constructor (int8, and `timestamp` under `utcTimestamps`), and
|
|
1115
|
+
* a caller may register their own at any point. A stale memo would silently
|
|
1116
|
+
* reintroduce the very divergence this exists to remove. The lookup is a plain
|
|
1117
|
+
* object index in pg-types, so it is not worth caching.
|
|
1118
|
+
*/
|
|
1119
|
+
export function coerceJsonWireValue(oid, value) {
|
|
1120
|
+
if (typeof value !== 'string')
|
|
1121
|
+
return value;
|
|
1122
|
+
return pg.types.getTypeParser(oid, 'text')(value);
|
|
1123
|
+
}
|
|
1124
|
+
// ---------------------------------------------------------------------------
|
|
1125
|
+
// Unknown-field diagnostics
|
|
1126
|
+
// ---------------------------------------------------------------------------
|
|
1127
|
+
/**
|
|
1128
|
+
* Case-insensitive closeness of `candidate` to `input`, higher is better,
|
|
1129
|
+
* 0 meaning "not worth suggesting". Deliberately tiny: this runs only on the
|
|
1130
|
+
* error path, and its whole job is to turn a guessed name into the real one.
|
|
1131
|
+
*
|
|
1132
|
+
* Substring containment is scored ABOVE edit distance because the real-world
|
|
1133
|
+
* miss is a longer, more descriptive guess than the actual name (`modelVersions`
|
|
1134
|
+
* for a relation turbine derived as `versions`), where the edit distance is
|
|
1135
|
+
* large but the containment is exact.
|
|
1136
|
+
*/
|
|
1137
|
+
function nameCloseness(input, candidate) {
|
|
1138
|
+
const a = input.toLowerCase();
|
|
1139
|
+
const b = candidate.toLowerCase();
|
|
1140
|
+
if (a === b)
|
|
1141
|
+
return 1000;
|
|
1142
|
+
// Containment only between names of 3+ characters: `id` sits inside almost
|
|
1143
|
+
// any name, so `tenentId` must reach `tenantId` by edit distance instead.
|
|
1144
|
+
if (Math.min(a.length, b.length) >= 3 && (a.includes(b) || b.includes(a))) {
|
|
1145
|
+
return 500 + Math.min(a.length, b.length);
|
|
1146
|
+
}
|
|
1147
|
+
// Levenshtein, bounded: only near-misses are worth suggesting.
|
|
1148
|
+
const rows = a.length + 1;
|
|
1149
|
+
const cols = b.length + 1;
|
|
1150
|
+
let prev = Array.from({ length: cols }, (_, j) => j);
|
|
1151
|
+
for (let i = 1; i < rows; i++) {
|
|
1152
|
+
const cur = [i];
|
|
1153
|
+
for (let j = 1; j < cols; j++) {
|
|
1154
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
1155
|
+
}
|
|
1156
|
+
prev = cur;
|
|
1157
|
+
}
|
|
1158
|
+
const distance = prev[cols - 1];
|
|
1159
|
+
const limit = Math.max(2, Math.floor(Math.max(a.length, b.length) / 3));
|
|
1160
|
+
return distance <= limit ? 100 - distance : 0;
|
|
1161
|
+
}
|
|
1162
|
+
/** The closest name in `candidates` to `input`, or null when none is close. */
|
|
1163
|
+
export function closestName(input, candidates) {
|
|
1164
|
+
let best = null;
|
|
1165
|
+
let bestScore = 0;
|
|
1166
|
+
for (const c of candidates) {
|
|
1167
|
+
const score = nameCloseness(input, c);
|
|
1168
|
+
if (score > bestScore) {
|
|
1169
|
+
bestScore = score;
|
|
1170
|
+
best = c;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
return best;
|
|
1174
|
+
}
|
|
1175
|
+
/** camelCase name → its lowercased words (`logQueryParams` → log, query, params). */
|
|
1176
|
+
function camelWords(name) {
|
|
1177
|
+
return name
|
|
1178
|
+
.split(/(?=[A-Z])/)
|
|
1179
|
+
.map((w) => w.toLowerCase())
|
|
1180
|
+
.filter(Boolean);
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* The real option key `key` most likely meant, or null when nothing is close.
|
|
1184
|
+
*
|
|
1185
|
+
* Shared by every "unknown option" diagnostic (the client-config warner in
|
|
1186
|
+
* client.ts and the prisma-compat query-option warner), so a reader who has
|
|
1187
|
+
* seen one recognizes the ranking in the other.
|
|
1188
|
+
*
|
|
1189
|
+
* {@link closestName} decides first, which is bounded by edit distance and
|
|
1190
|
+
* covers typos. It does not cover the miss these warnings exist for: a guessed
|
|
1191
|
+
* name that omits a whole WORD. `logParams` is five edits from `logQueryParams`,
|
|
1192
|
+
* past the bound, yet it names the same words in the same order; likewise
|
|
1193
|
+
* `customPlan` for `forceCustomPlan`. So a second pass accepts a candidate whose
|
|
1194
|
+
* camelCase words CONTAIN the guess's words in order, preferring the one that
|
|
1195
|
+
* adds fewest words.
|
|
1196
|
+
*/
|
|
1197
|
+
export function suggestKey(key, candidates) {
|
|
1198
|
+
const direct = closestName(key, candidates);
|
|
1199
|
+
if (direct)
|
|
1200
|
+
return direct;
|
|
1201
|
+
const wanted = camelWords(key);
|
|
1202
|
+
if (wanted.length < 2)
|
|
1203
|
+
return null;
|
|
1204
|
+
let best = null;
|
|
1205
|
+
let bestExtra = Number.POSITIVE_INFINITY;
|
|
1206
|
+
for (const candidate of candidates) {
|
|
1207
|
+
const words = camelWords(candidate);
|
|
1208
|
+
if (words.length <= wanted.length)
|
|
1209
|
+
continue;
|
|
1210
|
+
let i = 0;
|
|
1211
|
+
for (const w of words)
|
|
1212
|
+
if (w === wanted[i])
|
|
1213
|
+
i++;
|
|
1214
|
+
if (i !== wanted.length)
|
|
1215
|
+
continue;
|
|
1216
|
+
const extra = words.length - wanted.length;
|
|
1217
|
+
if (extra < bestExtra) {
|
|
1218
|
+
bestExtra = extra;
|
|
1219
|
+
best = candidate;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return best;
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* The "unknown field" error text, listing RELATIONS as well as columns.
|
|
1226
|
+
*
|
|
1227
|
+
* The message used to read `Known fields: id, name.` and nothing else. That is
|
|
1228
|
+
* actively misleading when the key was a relation name: relation filters ARE
|
|
1229
|
+
* valid in a `where`, so a user who guessed the wrong relation name concluded
|
|
1230
|
+
* from this message that turbine cannot filter by relations at all. Relation
|
|
1231
|
+
* names are frequently guessed wrong because introspection derives them, and
|
|
1232
|
+
* two foreign keys to one table produce names (`msgsBySender`) that no one
|
|
1233
|
+
* would predict.
|
|
1234
|
+
*/
|
|
1235
|
+
export function unknownFieldMessage(table, field, meta) {
|
|
1236
|
+
const columns = Object.keys(meta.columnMap);
|
|
1237
|
+
const relations = Object.keys(meta.relations ?? {});
|
|
1238
|
+
const suggestion = closestName(field, [...columns, ...relations]);
|
|
1239
|
+
const didYouMean = suggestion
|
|
1240
|
+
? ` Did you mean "${suggestion}"${relations.includes(suggestion) ? ' (a relation)' : ''}?`
|
|
1241
|
+
: '';
|
|
1242
|
+
return (`Unknown field "${field}" on table "${table}".${didYouMean}` +
|
|
1243
|
+
` Known columns: ${columns.join(', ') || '(none)'}.` +
|
|
1244
|
+
(relations.length ? ` Known relations (valid in \`where\` and \`with\`): ${relations.join(', ')}.` : ''));
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* The trailing "Available: a, b, c" clause of a name-not-found error, or
|
|
1248
|
+
* `emptySentence` when there is nothing to list.
|
|
1249
|
+
*
|
|
1250
|
+
* The empty branch is the whole reason this exists. Fifteen error sites
|
|
1251
|
+
* interpolated `Object.keys(...).join(', ')` directly, and on a table with no
|
|
1252
|
+
* relations (or a schema with no tables) that renders a dangling
|
|
1253
|
+
* `Available: ` with nothing after the colon, which reads as a broken error
|
|
1254
|
+
* message rather than as an answer. One site already got this right by hand;
|
|
1255
|
+
* the other fourteen use the same function, so the next one cannot get it
|
|
1256
|
+
* wrong by omission.
|
|
1257
|
+
*/
|
|
1258
|
+
export function availableClause(names, emptySentence) {
|
|
1259
|
+
return names.length > 0 ? `Available: ${names.join(', ')}` : emptySentence;
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* The error text for a RELATION named inside `select` / `omit`.
|
|
1263
|
+
*
|
|
1264
|
+
* Separate from {@link unknownFieldMessage} because the generic text degrades
|
|
1265
|
+
* into nonsense here: `closestName` matches an exactly-spelled relation name at
|
|
1266
|
+
* distance zero, so the message would read `Unknown field "comments". Did you
|
|
1267
|
+
* mean "comments" (a relation)?`, which answers a question nobody asked and
|
|
1268
|
+
* hides the actual fix.
|
|
1269
|
+
*
|
|
1270
|
+
* It is worth its own message for a second reason: this is not really a typo,
|
|
1271
|
+
* it is a habit. Prisma nests a relation inside `select`, so writing
|
|
1272
|
+
* `select: { comments: true }` is the natural first guess, and in Turbine a
|
|
1273
|
+
* relation is loaded by `with`, which sits BESIDE `select` rather than inside
|
|
1274
|
+
* it. Naming the fix costs one sentence and saves a search.
|
|
1275
|
+
*/
|
|
1276
|
+
export function relationInProjectionMessage(table, field, clause) {
|
|
1277
|
+
const head = `"${field}" is a relation on table "${table}", not a column, so it cannot be named in \`${clause}\`.`;
|
|
1278
|
+
return clause === 'select'
|
|
1279
|
+
? `${head} Load it with \`with: { ${field}: true }\`, which is a sibling of \`select\`, not a member of it.` +
|
|
1280
|
+
" To narrow the relation's own columns, put a `select` inside that relation's options:" +
|
|
1281
|
+
` \`with: { ${field}: { select: { … } } }\`.`
|
|
1282
|
+
: `${head} A relation is only present when you ask for it in \`with\`, so leave it out of \`with\` to leave it` +
|
|
1283
|
+
' out of the result.';
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Advice (`diagnostics.advice`) for a sort/grouping term Turbine dropped as redundant
|
|
1287
|
+
* (`filters.ts` `dedupeOrderEntries` / `dedupeColumnList`).
|
|
1288
|
+
*
|
|
1289
|
+
* Deliberately a WARNING and not an error, and deliberately not silent either.
|
|
1290
|
+
* The dropped term provably cannot change a result, so failing the query would
|
|
1291
|
+
* be a false alarm on a shape correct code produces (a caller-chosen sort key
|
|
1292
|
+
* plus an unconditional primary-key tiebreak, which collide exactly when the
|
|
1293
|
+
* caller sorts by the primary key). But a caller who wrote the duplicate by
|
|
1294
|
+
* hand, or who believes a second key is doing something, should hear about it
|
|
1295
|
+
* once. Advice for the usual reason: it describes the QUERY the application
|
|
1296
|
+
* sends, which does not vary with the environment, so a production process
|
|
1297
|
+
* learns nothing from repeating it. The caller passes its advice logger, or
|
|
1298
|
+
* `undefined` when advice is off.
|
|
1299
|
+
*
|
|
1300
|
+
* Keyed per dropped key, so a sort assembled per request from the same UI says
|
|
1301
|
+
* it once rather than once per request.
|
|
1302
|
+
*/
|
|
1303
|
+
export function warnRedundantSortTerm(advice, table, clause, dropped) {
|
|
1304
|
+
if (!advice)
|
|
1305
|
+
return;
|
|
1306
|
+
for (const d of dropped) {
|
|
1307
|
+
if (!shouldWarnOnce(WARN_NS.redundantSortTerm, `${table}|${clause}|${d.key}`))
|
|
1308
|
+
continue;
|
|
1309
|
+
const how = d.first === d.key
|
|
1310
|
+
? `"${d.key}" is named twice`
|
|
1311
|
+
: `"${d.key}" and the earlier "${d.first}" both target ${d.resolved}`;
|
|
1312
|
+
logTo(advice, 'warn', `${clause} on table "${table}": ${how}, so the later one was dropped. It could not have ` +
|
|
1313
|
+
'changed the result (the earlier term already orders those rows), and dropping it keeps the query on ' +
|
|
1314
|
+
'a shared prepared statement. Remove it to silence this.', { code: 'redundant-sort-term', table, clause, key: d.key });
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* The two projection SHAPE refusals (0.65), shared by the SQL engines' single
|
|
1319
|
+
* resolver, the batched loader's raw-arg check, and PowDB, so every path that
|
|
1320
|
+
* refuses these shapes does so with one message.
|
|
1321
|
+
*
|
|
1322
|
+
* Both checks look at TRUTHY keys, and the raw-arg check in the batched
|
|
1323
|
+
* loader exists because the loader force-adds correlation keys to a `select`
|
|
1324
|
+
* before the resolver sees it: evaluated after that adjustment, an all-falsy
|
|
1325
|
+
* user `select` looks populated and the verdict flips between strategies,
|
|
1326
|
+
* which is exactly the class 0.64/0.65 exist to kill.
|
|
1327
|
+
*/
|
|
1328
|
+
export function selectNamesNothingMessage(table) {
|
|
1329
|
+
return (`"select" names no fields (on table "${table}"): every value is false or it is empty. ` +
|
|
1330
|
+
`Pass at least one field as true, or drop "select" to get the default projection.`);
|
|
1331
|
+
}
|
|
1332
|
+
export function selectOmitExclusiveMessage(table) {
|
|
1333
|
+
return (`"select" and "omit" are mutually exclusive (on table "${table}"). ` +
|
|
1334
|
+
`A select already lists exactly the fields you want.`);
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* The Prisma pagination aliases, folded into Turbine's own spelling ONCE,
|
|
1338
|
+
* before anything reads them.
|
|
1339
|
+
*
|
|
1340
|
+
* Turbine's names are `limit` / `offset`; Prisma's are `take` / `skip`. `take`
|
|
1341
|
+
* was accepted and `skip` was not, which is the worst of the three possible
|
|
1342
|
+
* states: `{ take: 20, skip: 40 }` is what a Prisma habit writes, it looks
|
|
1343
|
+
* accepted because half of it is, and the query silently returns page one
|
|
1344
|
+
* forever. An unknown key is at least inert on its own; a HALF-recognized pair
|
|
1345
|
+
* changes the answer.
|
|
1346
|
+
*
|
|
1347
|
+
* Folded here rather than read at each site deliberately. `take` used to be
|
|
1348
|
+
* handled by six separate `args?.take ?? args?.limit` reads, one of which is
|
|
1349
|
+
* the SQL-cache FINGERPRINT, so adding `skip` the same way would have meant
|
|
1350
|
+
* teaching six places about it and a miss in the fingerprint is not a missing
|
|
1351
|
+
* feature, it is two different pages sharing one cached statement. Normalizing
|
|
1352
|
+
* up front leaves `limit` / `offset` as the single authority and the aliases
|
|
1353
|
+
* cease to exist below this line.
|
|
1354
|
+
*
|
|
1355
|
+
* Returns the SAME object when neither alias is present, so the common path
|
|
1356
|
+
* allocates nothing.
|
|
1357
|
+
*/
|
|
1358
|
+
export function normalizePagination(args) {
|
|
1359
|
+
if (!args)
|
|
1360
|
+
return args;
|
|
1361
|
+
const a = args;
|
|
1362
|
+
if (a.take === undefined && a.skip === undefined)
|
|
1363
|
+
return args;
|
|
1364
|
+
const out = { ...args };
|
|
1365
|
+
if (a.take !== undefined) {
|
|
1366
|
+
assertAliasAgrees('take', a.take, 'limit', a.limit);
|
|
1367
|
+
out.limit = a.take;
|
|
1368
|
+
delete out.take;
|
|
1369
|
+
}
|
|
1370
|
+
if (a.skip !== undefined) {
|
|
1371
|
+
assertAliasAgrees('skip', a.skip, 'offset', a.offset);
|
|
1372
|
+
out.offset = a.skip;
|
|
1373
|
+
delete out.skip;
|
|
1374
|
+
}
|
|
1375
|
+
return out;
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Both spellings of one bound, disagreeing. Refused rather than resolved: the
|
|
1379
|
+
* old `take ?? limit` silently preferred one of the two numbers the caller
|
|
1380
|
+
* wrote, and there is no reading of `{ limit: 10, take: 5 }` that makes one of
|
|
1381
|
+
* them the intended answer. Equal values are accepted, since there is nothing
|
|
1382
|
+
* to choose between.
|
|
1383
|
+
*/
|
|
1384
|
+
function assertAliasAgrees(alias, aliasValue, native, nativeValue) {
|
|
1385
|
+
if (nativeValue === undefined || nativeValue === aliasValue)
|
|
1386
|
+
return;
|
|
1387
|
+
throw new ValidationError(`"${alias}" and "${native}" are the same option and were given different values ` +
|
|
1388
|
+
`(${alias}: ${String(aliasValue)}, ${native}: ${String(nativeValue)}). ` +
|
|
1389
|
+
`"${alias}" is Prisma's spelling of "${native}"; pass one of them.`);
|
|
1390
|
+
}
|