@prisma/orm-mariadb 0.0.0-stage → 8.0.0-rc.24
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/LICENSE +201 -0
- package/README.md +48 -2
- package/dist/adapter.d.mts +1 -0
- package/dist/adapter.mjs +2 -0
- package/dist/adapter__codec-types.d.mts +1 -0
- package/dist/adapter__codec-types.mjs +2 -0
- package/dist/adapter__control.d.mts +3 -0
- package/dist/adapter__control.mjs +3 -0
- package/dist/components.d.mts +1 -0
- package/dist/components.mjs +2 -0
- package/dist/components__authoring.d.mts +1 -0
- package/dist/components__authoring.mjs +2 -0
- package/dist/components__codec.d.mts +1 -0
- package/dist/components__codec.mjs +2 -0
- package/dist/components__components.d.mts +1 -0
- package/dist/components__components.mjs +2 -0
- package/dist/components__control.d.mts +1 -0
- package/dist/components__control.mjs +2 -0
- package/dist/components__emission.d.mts +1 -0
- package/dist/components__emission.mjs +2 -0
- package/dist/components__execution.d.mts +1 -0
- package/dist/components__execution.mjs +2 -0
- package/dist/components__ir.d.mts +1 -0
- package/dist/components__ir.mjs +2 -0
- package/dist/components__psl-ast.d.mts +1 -0
- package/dist/components__psl-ast.mjs +2 -0
- package/dist/components__runtime.d.mts +1 -0
- package/dist/components__runtime.mjs +2 -0
- package/dist/components__utils.d.mts +1 -0
- package/dist/components__utils.mjs +2 -0
- package/dist/config.d.mts +10 -0
- package/dist/config.d.mts.map +1 -0
- package/dist/config.mjs +17 -0
- package/dist/config.mjs.map +1 -0
- package/dist/contract.d.mts +1 -0
- package/dist/contract.mjs +2 -0
- package/dist/contract__apply-specifier-default-control-policy.d.mts +1 -0
- package/dist/contract__apply-specifier-default-control-policy.mjs +2 -0
- package/dist/contract__contract-validation-error.d.mts +1 -0
- package/dist/contract__contract-validation-error.mjs +2 -0
- package/dist/contract__default-namespace.d.mts +1 -0
- package/dist/contract__default-namespace.mjs +2 -0
- package/dist/contract__enum-accessor.d.mts +1 -0
- package/dist/contract__enum-accessor.mjs +2 -0
- package/dist/contract__hashing-utils.d.mts +1 -0
- package/dist/contract__hashing-utils.mjs +2 -0
- package/dist/contract__hashing.d.mts +1 -0
- package/dist/contract__hashing.mjs +2 -0
- package/dist/contract__is-plain-record.d.mts +1 -0
- package/dist/contract__is-plain-record.mjs +2 -0
- package/dist/contract__resolve-domain-model.d.mts +1 -0
- package/dist/contract__resolve-domain-model.mjs +2 -0
- package/dist/contract__types.d.mts +1 -0
- package/dist/contract__types.mjs +2 -0
- package/dist/contract__validate-domain.d.mts +1 -0
- package/dist/contract__validate-domain.mjs +2 -0
- package/dist/contract__validate-once.d.mts +1 -0
- package/dist/contract__validate-once.mjs +2 -0
- package/dist/contract__validate-storage.d.mts +1 -0
- package/dist/contract__validate-storage.mjs +2 -0
- package/dist/control.d.mts +12 -0
- package/dist/control.d.mts.map +1 -0
- package/dist/control.mjs +22 -0
- package/dist/control.mjs.map +1 -0
- package/dist/driver.d.mts +1 -0
- package/dist/driver.mjs +2 -0
- package/dist/driver__control.d.mts +3 -0
- package/dist/driver__control.mjs +3 -0
- package/dist/driver__runtime.d.mts +3 -0
- package/dist/driver__runtime.mjs +3 -0
- package/dist/family-contract.d.mts +1 -0
- package/dist/family-contract.mjs +2 -0
- package/dist/family-contract__authored-check-naming.d.mts +1 -0
- package/dist/family-contract__authored-check-naming.mjs +2 -0
- package/dist/family-contract__canonicalization-hooks.d.mts +1 -0
- package/dist/family-contract__canonicalization-hooks.mjs +2 -0
- package/dist/family-contract__check-expressions.d.mts +1 -0
- package/dist/family-contract__check-expressions.mjs +2 -0
- package/dist/family-contract__codec-json-type.d.mts +1 -0
- package/dist/family-contract__codec-json-type.mjs +2 -0
- package/dist/family-contract__contract-view.d.mts +1 -0
- package/dist/family-contract__contract-view.mjs +2 -0
- package/dist/family-contract__data-type-support.d.mts +1 -0
- package/dist/family-contract__data-type-support.mjs +2 -0
- package/dist/family-contract__data-type.d.mts +1 -0
- package/dist/family-contract__data-type.mjs +2 -0
- package/dist/family-contract__entity-handle-lowering-hook.d.mts +1 -0
- package/dist/family-contract__entity-handle-lowering-hook.mjs +2 -0
- package/dist/family-contract__entity-kinds.d.mts +1 -0
- package/dist/family-contract__entity-kinds.mjs +2 -0
- package/dist/family-contract__factories.d.mts +1 -0
- package/dist/family-contract__factories.mjs +2 -0
- package/dist/family-contract__foreign-key-materialization.d.mts +1 -0
- package/dist/family-contract__foreign-key-materialization.mjs +2 -0
- package/dist/family-contract__generated-id-column-aliases.d.mts +1 -0
- package/dist/family-contract__generated-id-column-aliases.mjs +2 -0
- package/dist/family-contract__index-naming.d.mts +1 -0
- package/dist/family-contract__index-naming.mjs +2 -0
- package/dist/family-contract__index-type-validation.d.mts +1 -0
- package/dist/family-contract__index-type-validation.mjs +2 -0
- package/dist/family-contract__index-types.d.mts +1 -0
- package/dist/family-contract__index-types.mjs +2 -0
- package/dist/family-contract__referential-action-sql.d.mts +1 -0
- package/dist/family-contract__referential-action-sql.mjs +2 -0
- package/dist/family-contract__resolve-storage-table.d.mts +1 -0
- package/dist/family-contract__resolve-storage-table.mjs +2 -0
- package/dist/family-contract__sql-expression.d.mts +1 -0
- package/dist/family-contract__sql-expression.mjs +2 -0
- package/dist/family-contract__types.d.mts +1 -0
- package/dist/family-contract__types.mjs +2 -0
- package/dist/family-contract__validators.d.mts +1 -0
- package/dist/family-contract__validators.mjs +2 -0
- package/dist/family-contract__value-set-derivation-hook.d.mts +1 -0
- package/dist/family-contract__value-set-derivation-hook.mjs +2 -0
- package/dist/family__control-adapter.d.mts +1 -0
- package/dist/family__control-adapter.mjs +2 -0
- package/dist/family__control.d.mts +3 -0
- package/dist/family__control.mjs +3 -0
- package/dist/family__diff.d.mts +1 -0
- package/dist/family__diff.mjs +2 -0
- package/dist/family__ir.d.mts +1 -0
- package/dist/family__ir.mjs +2 -0
- package/dist/family__migration.d.mts +1 -0
- package/dist/family__migration.mjs +2 -0
- package/dist/family__pack.d.mts +3 -0
- package/dist/family__pack.mjs +3 -0
- package/dist/family__psl-build.d.mts +1 -0
- package/dist/family__psl-build.mjs +2 -0
- package/dist/family__psl-infer.d.mts +1 -0
- package/dist/family__psl-infer.mjs +2 -0
- package/dist/family__runtime.d.mts +3 -0
- package/dist/family__runtime.mjs +3 -0
- package/dist/family__verify.d.mts +1 -0
- package/dist/family__verify.mjs +2 -0
- package/dist/migration-tools__aggregate.d.mts +1 -0
- package/dist/migration-tools__aggregate.mjs +2 -0
- package/dist/migration-tools__contract-snapshot-store.d.mts +1 -0
- package/dist/migration-tools__contract-snapshot-store.mjs +2 -0
- package/dist/migration-tools__hash.d.mts +1 -0
- package/dist/migration-tools__hash.mjs +2 -0
- package/dist/migration-tools__io.d.mts +1 -0
- package/dist/migration-tools__io.mjs +2 -0
- package/dist/migration-tools__spaces.d.mts +1 -0
- package/dist/migration-tools__spaces.mjs +2 -0
- package/dist/migration.d.mts +3 -0
- package/dist/migration.mjs +3 -0
- package/dist/target__control.d.mts +3 -0
- package/dist/target__control.mjs +3 -0
- package/dist/target__migration.d.mts +1 -0
- package/dist/target__migration.mjs +2 -0
- package/dist/target__pack.d.mts +3 -0
- package/dist/target__pack.mjs +3 -0
- package/dist/utils.d.mts +1 -0
- package/dist/utils.mjs +2 -0
- package/dist/utils__abortable.d.mts +1 -0
- package/dist/utils__abortable.mjs +2 -0
- package/dist/utils__array-equal.d.mts +1 -0
- package/dist/utils__array-equal.mjs +2 -0
- package/dist/utils__assertions.d.mts +1 -0
- package/dist/utils__assertions.mjs +2 -0
- package/dist/utils__canonical-stringify.d.mts +1 -0
- package/dist/utils__canonical-stringify.mjs +2 -0
- package/dist/utils__casts.d.mts +1 -0
- package/dist/utils__casts.mjs +2 -0
- package/dist/utils__defined.d.mts +1 -0
- package/dist/utils__defined.mjs +2 -0
- package/dist/utils__hash-content.d.mts +1 -0
- package/dist/utils__hash-content.mjs +2 -0
- package/dist/utils__internal-error.d.mts +1 -0
- package/dist/utils__internal-error.mjs +2 -0
- package/dist/utils__json.d.mts +1 -0
- package/dist/utils__json.mjs +2 -0
- package/dist/utils__promise.d.mts +1 -0
- package/dist/utils__promise.mjs +2 -0
- package/dist/utils__redact-db-url.d.mts +1 -0
- package/dist/utils__redact-db-url.mjs +2 -0
- package/dist/utils__result.d.mts +1 -0
- package/dist/utils__result.mjs +2 -0
- package/dist/utils__simplify-deep.d.mts +1 -0
- package/dist/utils__simplify-deep.mjs +2 -0
- package/dist/utils__structured-error.d.mts +1 -0
- package/dist/utils__structured-error.mjs +2 -0
- package/dist/utils__suppress-idle-connection-errors.d.mts +1 -0
- package/dist/utils__suppress-idle-connection-errors.mjs +2 -0
- package/dist/utils__text.d.mts +1 -0
- package/dist/utils__text.mjs +2 -0
- package/dist/utils__types.d.mts +1 -0
- package/dist/utils__types.mjs +2 -0
- package/dist/vite-plugin-contract-emit.d.mts +1 -0
- package/dist/vite-plugin-contract-emit.mjs +2 -0
- package/package.json +139 -3
- package/skills/prisma-8/SKILL.md +100 -0
- package/skills/prisma-8/references/build.md +142 -0
- package/skills/prisma-8/references/contract.md +552 -0
- package/skills/prisma-8/references/debug.md +150 -0
- package/skills/prisma-8/references/feedback.md +251 -0
- package/skills/prisma-8/references/migration-model.md +179 -0
- package/skills/prisma-8/references/migration-review.md +211 -0
- package/skills/prisma-8/references/migrations.md +635 -0
- package/skills/prisma-8/references/queries-mongo.md +261 -0
- package/skills/prisma-8/references/queries-postgres.md +710 -0
- package/skills/prisma-8/references/queries.md +255 -0
- package/skills/prisma-8/references/quickstart.md +317 -0
- package/skills/prisma-8/references/runtime.md +463 -0
- package/skills/prisma-8/references/supabase.md +234 -0
- package/skills/prisma-8/references/upgrade-app.md +102 -0
- package/skills/prisma-8/references/upgrade-extension.md +108 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.10-to-0.11/instructions.md +56 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/instructions.md +381 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-closed-mongo-contracts.ts +202 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-domain-namespaced-contracts.ts +201 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-postgres-public-default.ts +198 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/strip-migration-labels-hints.ts +340 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.12-to-0.13/instructions.md +339 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.12-to-0.13/re-emit-mti-variant-link-columns.ts +229 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/instructions.md +543 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts +290 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/uuid-preset-rename.ts +43 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.14-to-0.15/instructions.md +359 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.15-to-0.16/instructions.md +173 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.16-to-0.17/instructions.md +805 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.16-to-0.17/strip-sha256-hash-prefixes.ts +382 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.17-to-8.0.0-rc.1/instructions.md +72 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.7-to-0.8/instructions.md +8 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.8-to-0.9/instructions.md +36 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.8-to-0.9/strip-inline-contracts.ts +226 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.9-to-0.10/instructions.md +86 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.9-to-0.10/stamp-storage-types-kind.ts +360 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.1-to-8.0.0-rc.2/instructions.md +588 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +639 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/multifile-psl/add-use-prisma-8-directive.mjs +60 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/psl-verbatim-table-names/add-model-map.mjs +256 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +332 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts +193 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +489 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +1368 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts +1492 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +108 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +755 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +973 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/scripts/sql-expression-literals-psl/rewrite-sql-strings.mjs +271 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +1862 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/client-takes-contract-value/contract-from-json.ts +597 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/data-type-values/data-type-values.ts +1120 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/default-generators-to-on-create/rewrite-default-generators.mjs +86 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/mongo-field-storage-names/mongo-field-storage-names.ts +304 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +2462 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +513 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts +1206 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.2-to-8.0.0-rc.3/instructions.md +5 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.20-to-8.0.0-rc.21/instructions.md +802 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/instructions.md +586 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/scripts/value-objects-in-storage/value-objects-in-storage.ts +1184 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/instructions.md +480 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/scripts/mongo-index-names/mongo-index-names.ts +317 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/instructions.md +319 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-convenience-date-time-types/rewrite-mongo-date-types.ts +220 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-type-helpers/rewrite-mongo-field-types.ts +621 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.3-to-8.0.0-rc.4/instructions.md +158 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.4-to-8.0.0-rc.5/instructions.md +42 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.5-to-8.0.0-rc.6/instructions.md +157 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.6-to-8.0.0-rc.7/instructions.md +33 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.7-to-8.0.0-rc.8/instructions.md +36 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.8-to-8.0.0-rc.9/instructions.md +63 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.9-to-8.0.0-rc.10/instructions.md +84 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.10-to-0.11/instructions.md +276 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +738 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/migrate-contract-testing-imports.ts +97 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/regenerate-extension-public-baseline.ts +223 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/strip-migration-labels-hints.ts +340 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.12-to-0.13/instructions.md +266 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/instructions.md +522 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts +290 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/uuid-preset-rename.ts +43 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.14-to-0.15/instructions.md +803 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.15-to-0.16/instructions.md +219 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.16-to-0.17/instructions.md +731 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.16-to-0.17/strip-sha256-hash-prefixes.ts +382 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.17-to-8.0.0-rc.1/instructions.md +194 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.7-to-0.8/instructions.md +8 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/instructions.md +57 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/strip-inline-contracts.ts +226 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/instructions.md +150 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/stamp-storage-types-kind.ts +360 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.1-to-8.0.0-rc.2/instructions.md +746 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +857 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/psl-verbatim-table-names/add-model-map.mjs +256 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +504 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts +193 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +143 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +2168 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts +1492 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +223 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +583 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +1008 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +2186 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/client-takes-contract-value/contract-from-json.ts +597 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/data-type-values/data-type-values.ts +1120 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/default-generators-to-on-create/rewrite-default-generators.mjs +86 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/mongo-field-storage-names/mongo-field-storage-names.ts +304 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +2462 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +381 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts +1206 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.2-to-8.0.0-rc.3/instructions.md +5 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.20-to-8.0.0-rc.21/instructions.md +570 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/instructions.md +464 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/instructions.md +410 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/instructions.md +304 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-convenience-date-time-types/rewrite-mongo-date-types.ts +220 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-type-helpers/rewrite-mongo-field-types.ts +621 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.3-to-8.0.0-rc.4/instructions.md +137 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.4-to-8.0.0-rc.5/instructions.md +129 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.5-to-8.0.0-rc.6/instructions.md +102 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.6-to-8.0.0-rc.7/instructions.md +33 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.7-to-8.0.0-rc.8/instructions.md +35 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.8-to-8.0.0-rc.9/instructions.md +86 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.9-to-8.0.0-rc.10/instructions.md +63 -0
|
@@ -0,0 +1,2462 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Removes the `noCheck` key from every column of every SQL contract in a project. Where the key waived the element check of a list, the column and the field that maps it become lists whose elements may be null, in `contract.json` and `contract.d.ts`, because that is what the database enforces. The checks each contract declares are left as they are. In a PostgreSQL contract it also writes each literal default in the contract form this release stores, as its column's data type and parameters give it. The script then renames the snapshot directories and rewrites every migration, ref, `migration.ts` and `contract.d.ts` that names an old storage hash.
|
|
4
|
+
*
|
|
5
|
+
* Usage: node remove-nocheck.ts [project-root] [--default <namespace>.<table>.<column>=<JSON value>]...
|
|
6
|
+
*
|
|
7
|
+
* The project root defaults to the working directory. The script reads and writes files only. It needs no database, network or configured stack, and a project already in this release's form is left unchanged. When it stops (a file it must read is not valid JSON, a contract whose stored hash does not match its content, a default that this release refuses, or a snapshot directory that already exists with different content) it changes no file, prints one line per case and exits 1. When it finishes it prints how many files and snapshot directories it changed and each storage hash it replaced.
|
|
8
|
+
*
|
|
9
|
+
* `--default` gives the value to store in place of a default this release refuses, in every stored contract where that column's default is refused. The script checks the value by the same rules, and stops when a `--default` names a column whose default it does not refuse.
|
|
10
|
+
*
|
|
11
|
+
* The storage hash and migration hash rules are copied from `@internal/contract` and `@internal/migration-tools`, and the default rules from the data types of 8.0.0-rc.19, PostgreSQL's built-in types, `postgis/geometry` and `pgvector/vector`, so the script gives the same result whatever is installed.
|
|
12
|
+
*/
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import {
|
|
15
|
+
chmodSync,
|
|
16
|
+
type Dirent,
|
|
17
|
+
existsSync,
|
|
18
|
+
mkdirSync,
|
|
19
|
+
readdirSync,
|
|
20
|
+
readFileSync,
|
|
21
|
+
realpathSync,
|
|
22
|
+
renameSync,
|
|
23
|
+
rmSync,
|
|
24
|
+
statSync,
|
|
25
|
+
writeFileSync,
|
|
26
|
+
} from 'node:fs';
|
|
27
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
28
|
+
|
|
29
|
+
type Json = null | boolean | number | string | Json[] | JsonRecord;
|
|
30
|
+
interface JsonRecord {
|
|
31
|
+
[key: string]: Json;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
|
|
35
|
+
const HASH = /^[0-9a-f]{64}$/;
|
|
36
|
+
const TEMPORARY_SUFFIX = '.remove-nocheck-tmp';
|
|
37
|
+
|
|
38
|
+
function isRecord(value: unknown): value is JsonRecord {
|
|
39
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
40
|
+
const prototype: unknown = Object.getPrototypeOf(value);
|
|
41
|
+
return prototype === Object.prototype || prototype === null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function parseJson(text: string): Json | undefined {
|
|
45
|
+
try {
|
|
46
|
+
const value: Json = JSON.parse(text);
|
|
47
|
+
return value;
|
|
48
|
+
} catch {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sha256(text: string): string {
|
|
54
|
+
return createHash('sha256').update(text).digest('hex');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function compareCodeUnits(a: string, b: string): number {
|
|
58
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sortKeys(value: Json): Json {
|
|
62
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
63
|
+
if (!isRecord(value)) return value;
|
|
64
|
+
const sorted: JsonRecord = {};
|
|
65
|
+
for (const key of Object.keys(value).sort(compareCodeUnits)) {
|
|
66
|
+
const child = value[key];
|
|
67
|
+
if (child !== undefined) sorted[key] = sortKeys(child);
|
|
68
|
+
}
|
|
69
|
+
return sorted;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function canonicalizeJson(value: Json): string {
|
|
73
|
+
return JSON.stringify(sortKeys(value));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type PathSegment = string | readonly string[];
|
|
77
|
+
|
|
78
|
+
function matchesPath(path: readonly string[], pattern: readonly PathSegment[]): boolean {
|
|
79
|
+
if (path.length !== pattern.length) return false;
|
|
80
|
+
return pattern.every((segment, index) => {
|
|
81
|
+
const value = path[index];
|
|
82
|
+
if (value === undefined) return false;
|
|
83
|
+
if (segment === '*') return true;
|
|
84
|
+
return typeof segment === 'string' ? value === segment : segment.includes(value);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const SQL_PRESERVED_EMPTY: readonly (readonly PathSegment[])[] = [
|
|
89
|
+
['storage', 'namespaces', '*', 'entries', 'table'],
|
|
90
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*'],
|
|
91
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*', ['uniques', 'indexes', 'foreignKeys']],
|
|
92
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*', 'indexes', 'unique'],
|
|
93
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*', 'columns', '*', 'default', 'value'],
|
|
94
|
+
];
|
|
95
|
+
const COLUMN_DEFAULT_VALUE: readonly PathSegment[] = [
|
|
96
|
+
'storage',
|
|
97
|
+
'namespaces',
|
|
98
|
+
'*',
|
|
99
|
+
'entries',
|
|
100
|
+
'table',
|
|
101
|
+
'*',
|
|
102
|
+
'columns',
|
|
103
|
+
'*',
|
|
104
|
+
'default',
|
|
105
|
+
'value',
|
|
106
|
+
];
|
|
107
|
+
const FRAMEWORK_PRESERVED_EMPTY: readonly (readonly PathSegment[])[] = [
|
|
108
|
+
['domain', 'namespaces'],
|
|
109
|
+
['domain', 'namespaces', '*'],
|
|
110
|
+
['domain', 'namespaces', '*', 'models'],
|
|
111
|
+
['domain', 'namespaces', '*', 'models', '*', 'relations'],
|
|
112
|
+
['domain', 'namespaces', '*', 'models', '*', 'storage'],
|
|
113
|
+
['storage', 'namespaces'],
|
|
114
|
+
['storage', 'namespaces', '*', 'entries'],
|
|
115
|
+
['roots'],
|
|
116
|
+
['extensions'],
|
|
117
|
+
['extensions', '*'],
|
|
118
|
+
['capabilities'],
|
|
119
|
+
['meta'],
|
|
120
|
+
['execution', 'mutations', 'defaults'],
|
|
121
|
+
];
|
|
122
|
+
const TOP_LEVEL_ORDER = [
|
|
123
|
+
'schemaVersion',
|
|
124
|
+
'canonicalVersion',
|
|
125
|
+
'targetFamily',
|
|
126
|
+
'target',
|
|
127
|
+
'profileHash',
|
|
128
|
+
'roots',
|
|
129
|
+
'domain',
|
|
130
|
+
'storage',
|
|
131
|
+
'execution',
|
|
132
|
+
'capabilities',
|
|
133
|
+
'extensions',
|
|
134
|
+
'defaultControlPolicy',
|
|
135
|
+
'meta',
|
|
136
|
+
];
|
|
137
|
+
|
|
138
|
+
function isDefaultValue(value: Json): boolean {
|
|
139
|
+
if (value === false) return true;
|
|
140
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
141
|
+
return isRecord(value) && Object.keys(value).length === 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function isPreservedEmpty(path: readonly string[], key: string): boolean {
|
|
145
|
+
if (key === 'nullable') return true;
|
|
146
|
+
if (key === 'elementNullable' && path.at(-2) === 'many') return true;
|
|
147
|
+
if (FRAMEWORK_PRESERVED_EMPTY.some((pattern) => matchesPath(path, pattern))) return true;
|
|
148
|
+
if (
|
|
149
|
+
path.length >= COLUMN_DEFAULT_VALUE.length &&
|
|
150
|
+
matchesPath(path.slice(0, COLUMN_DEFAULT_VALUE.length), COLUMN_DEFAULT_VALUE)
|
|
151
|
+
)
|
|
152
|
+
return true;
|
|
153
|
+
return SQL_PRESERVED_EMPTY.some((pattern) => matchesPath(path, pattern));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function omitDefaults(value: Json, path: readonly string[]): Json {
|
|
157
|
+
if (Array.isArray(value)) return value.map((item) => omitDefaults(item, path));
|
|
158
|
+
if (!isRecord(value)) return value;
|
|
159
|
+
const result: JsonRecord = {};
|
|
160
|
+
for (const [key, child] of Object.entries(value)) {
|
|
161
|
+
const childPath = [...path, key];
|
|
162
|
+
if (key === '_generated') continue;
|
|
163
|
+
if (key === 'generated' && child === false) continue;
|
|
164
|
+
if ((key === 'onDelete' || key === 'onUpdate') && child === 'noAction') continue;
|
|
165
|
+
if (isDefaultValue(child) && !isPreservedEmpty(childPath, key)) continue;
|
|
166
|
+
result[key] = omitDefaults(child, childPath);
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function compareByName(a: Json, b: Json): number {
|
|
172
|
+
const nameA = isRecord(a) && typeof a['name'] === 'string' ? a['name'] : '';
|
|
173
|
+
const nameB = isRecord(b) && typeof b['name'] === 'string' ? b['name'] : '';
|
|
174
|
+
return compareCodeUnits(nameA, nameB);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function sortTableArrays(storage: Json): Json {
|
|
178
|
+
if (!isRecord(storage)) return storage;
|
|
179
|
+
const namespaces = storage['namespaces'];
|
|
180
|
+
if (!isRecord(namespaces)) return storage;
|
|
181
|
+
const sortedNamespaces: JsonRecord = {};
|
|
182
|
+
for (const [namespaceId, namespace] of Object.entries(namespaces)) {
|
|
183
|
+
const entries = isRecord(namespace) ? namespace['entries'] : undefined;
|
|
184
|
+
const tables = isRecord(entries) ? entries['table'] : undefined;
|
|
185
|
+
if (!isRecord(namespace) || !isRecord(entries) || !isRecord(tables)) {
|
|
186
|
+
sortedNamespaces[namespaceId] = namespace;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const sortedTables: JsonRecord = {};
|
|
190
|
+
for (const [tableName, table] of Object.entries(tables)) {
|
|
191
|
+
if (!isRecord(table)) {
|
|
192
|
+
sortedTables[tableName] = table;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const sortedTable: JsonRecord = { ...table };
|
|
196
|
+
for (const key of ['checks', 'indexes', 'uniques']) {
|
|
197
|
+
const list = table[key];
|
|
198
|
+
if (Array.isArray(list)) sortedTable[key] = [...list].sort(compareByName);
|
|
199
|
+
}
|
|
200
|
+
sortedTables[tableName] = sortedTable;
|
|
201
|
+
}
|
|
202
|
+
sortedNamespaces[namespaceId] = { ...namespace, entries: { ...entries, table: sortedTables } };
|
|
203
|
+
}
|
|
204
|
+
return { ...storage, namespaces: sortedNamespaces };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function orderTopLevel(value: JsonRecord): JsonRecord {
|
|
208
|
+
const ordered: JsonRecord = {};
|
|
209
|
+
const remaining = new Set(Object.keys(value));
|
|
210
|
+
for (const key of TOP_LEVEL_ORDER) {
|
|
211
|
+
const child = value[key];
|
|
212
|
+
if (child !== undefined) {
|
|
213
|
+
ordered[key] = child;
|
|
214
|
+
remaining.delete(key);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const key of [...remaining].sort(compareCodeUnits)) {
|
|
218
|
+
const child = value[key];
|
|
219
|
+
if (child !== undefined) ordered[key] = child;
|
|
220
|
+
}
|
|
221
|
+
return ordered;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function omitNamespaceKinds(storage: JsonRecord): JsonRecord {
|
|
225
|
+
const namespaces = storage['namespaces'];
|
|
226
|
+
if (!isRecord(namespaces)) return storage;
|
|
227
|
+
const stripped: JsonRecord = {};
|
|
228
|
+
for (const [namespaceId, namespace] of Object.entries(namespaces)) {
|
|
229
|
+
if (isRecord(namespace)) {
|
|
230
|
+
const { kind: _kind, ...rest } = namespace;
|
|
231
|
+
stripped[namespaceId] = rest;
|
|
232
|
+
} else {
|
|
233
|
+
stripped[namespaceId] = namespace;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return { ...storage, namespaces: stripped };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function computeStorageHash(contract: JsonRecord): string {
|
|
240
|
+
const storage = isRecord(contract['storage']) ? contract['storage'] : {};
|
|
241
|
+
const { storageHash: _published, ...withoutHash } = storage;
|
|
242
|
+
const hashed: JsonRecord = {
|
|
243
|
+
schemaVersion: '1',
|
|
244
|
+
targetFamily: typeof contract['targetFamily'] === 'string' ? contract['targetFamily'] : '',
|
|
245
|
+
target: typeof contract['target'] === 'string' ? contract['target'] : '',
|
|
246
|
+
profileHash: '',
|
|
247
|
+
roots: {},
|
|
248
|
+
domain: { namespaces: {} },
|
|
249
|
+
storage: omitNamespaceKinds(withoutHash),
|
|
250
|
+
extensions: {},
|
|
251
|
+
capabilities: {},
|
|
252
|
+
meta: {},
|
|
253
|
+
};
|
|
254
|
+
const withoutDefaults = omitDefaults(hashed, []);
|
|
255
|
+
if (!isRecord(withoutDefaults)) return '';
|
|
256
|
+
const withSortedStorage = {
|
|
257
|
+
...withoutDefaults,
|
|
258
|
+
storage: sortTableArrays(withoutDefaults['storage'] ?? {}),
|
|
259
|
+
};
|
|
260
|
+
const sorted = sortKeys(withSortedStorage);
|
|
261
|
+
return isRecord(sorted) ? sha256(JSON.stringify(orderTopLevel(sorted), null, 2)) : '';
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function computeMigrationHash(metadata: JsonRecord, ops: Json): string {
|
|
265
|
+
const { migrationHash: _migrationHash, ...withoutHash } = metadata;
|
|
266
|
+
const parts = [canonicalizeJson(withoutHash), canonicalizeJson(ops)].map(sha256);
|
|
267
|
+
return sha256(canonicalizeJson(parts));
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
interface ProjectFiles {
|
|
271
|
+
readonly json: readonly string[];
|
|
272
|
+
readonly migrationJson: readonly string[];
|
|
273
|
+
readonly refs: readonly string[];
|
|
274
|
+
readonly migrationTs: readonly string[];
|
|
275
|
+
readonly leftovers: readonly string[];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function isDirectory(path: string): boolean {
|
|
279
|
+
try {
|
|
280
|
+
return statSync(path).isDirectory();
|
|
281
|
+
} catch {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function isFile(path: string): boolean {
|
|
287
|
+
try {
|
|
288
|
+
return statSync(path).isFile();
|
|
289
|
+
} catch {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** A file, or a link to one: the script reads and writes through links to files. */
|
|
295
|
+
function isFileEntry(dir: string, entry: Dirent): boolean {
|
|
296
|
+
return entry.isFile() || (entry.isSymbolicLink() && isFile(join(dir, entry.name)));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** A file the script reads, by the path it was reached through: its own path rather than a link's. */
|
|
300
|
+
interface FoundFile {
|
|
301
|
+
readonly path: string;
|
|
302
|
+
readonly linked: boolean;
|
|
303
|
+
readonly inMigrationPackage: boolean;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function listFiles(root: string): ProjectFiles {
|
|
307
|
+
const leftovers: string[] = [];
|
|
308
|
+
const visited = new Set<string>();
|
|
309
|
+
const found = new Map<string, FoundFile>();
|
|
310
|
+
const visit = (dir: string): void => {
|
|
311
|
+
const realDir = realpathSync(dir);
|
|
312
|
+
if (visited.has(realDir)) return;
|
|
313
|
+
visited.add(realDir);
|
|
314
|
+
const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
|
315
|
+
compareCodeUnits(a.name, b.name),
|
|
316
|
+
);
|
|
317
|
+
const inMigrationPackage = entries.some(
|
|
318
|
+
(entry) => entry.name === 'migration.json' && isFileEntry(dir, entry),
|
|
319
|
+
);
|
|
320
|
+
for (const entry of entries) {
|
|
321
|
+
const path = join(dir, entry.name);
|
|
322
|
+
if (entry.name.endsWith(TEMPORARY_SUFFIX)) {
|
|
323
|
+
leftovers.push(path);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
if (entry.isDirectory() || (entry.isSymbolicLink() && isDirectory(path))) {
|
|
327
|
+
if (!SKIPPED_DIRECTORIES.has(entry.name) && !entry.name.startsWith('.')) visit(path);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (!isFileEntry(dir, entry)) continue;
|
|
331
|
+
const realFile = realpathSync(path);
|
|
332
|
+
const linked = entry.isSymbolicLink();
|
|
333
|
+
const known = found.get(realFile);
|
|
334
|
+
if (known === undefined || (known.linked && !linked))
|
|
335
|
+
found.set(realFile, { path, linked, inMigrationPackage });
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
visit(root);
|
|
339
|
+
const files = [...found.values()];
|
|
340
|
+
const named = (test: (file: FoundFile, name: string) => boolean): string[] =>
|
|
341
|
+
files.filter((file) => test(file, basename(file.path))).map((file) => file.path);
|
|
342
|
+
return {
|
|
343
|
+
json: named((_file, name) => name.endsWith('.json')),
|
|
344
|
+
migrationJson: named((_file, name) => name === 'migration.json'),
|
|
345
|
+
refs: named((file, name) => name.endsWith('.json') && basename(dirname(file.path)) === 'refs'),
|
|
346
|
+
migrationTs: named((file, name) => name === 'migration.ts' && file.inMigrationPackage),
|
|
347
|
+
leftovers,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function isSnapshotContract(path: string): boolean {
|
|
352
|
+
const snapshotDir = dirname(path);
|
|
353
|
+
return (
|
|
354
|
+
basename(path) === 'contract.json' &&
|
|
355
|
+
HASH.test(basename(snapshotDir)) &&
|
|
356
|
+
basename(dirname(snapshotDir)) === 'snapshots'
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function replaceQuotedHashes(text: string, hashes: ReadonlyMap<string, string>): string {
|
|
361
|
+
return text.replace(/"([0-9a-f]{64})"/g, (match: string, hash: string) => {
|
|
362
|
+
const next = hashes.get(hash);
|
|
363
|
+
return next === undefined ? match : `"${next}"`;
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function readDirectory(dir: string): Map<string, string> {
|
|
368
|
+
const files = new Map<string, string>();
|
|
369
|
+
if (!existsSync(dir)) return files;
|
|
370
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }))
|
|
371
|
+
if (isFileEntry(dir, entry) && !entry.name.endsWith(TEMPORARY_SUFFIX))
|
|
372
|
+
files.set(entry.name, readFileSync(join(dir, entry.name), 'utf8'));
|
|
373
|
+
return files;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function sameFiles(a: ReadonlyMap<string, string>, b: ReadonlyMap<string, string>): boolean {
|
|
377
|
+
return a.size === b.size && [...a].every(([name, content]) => b.get(name) === content);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function temporaryPath(path: string): string {
|
|
381
|
+
return join(dirname(path), `.${basename(path)}${TEMPORARY_SUFFIX}`);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function writeWithModeOf(path: string, text: string, modeSource: string): void {
|
|
385
|
+
writeFileSync(path, text);
|
|
386
|
+
if (existsSync(modeSource)) chmodSync(path, statSync(modeSource).mode & 0o7777);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function writeFile(path: string, text: string): void {
|
|
390
|
+
const target = realpathSync(path);
|
|
391
|
+
const temporary = temporaryPath(target);
|
|
392
|
+
writeWithModeOf(temporary, text, target);
|
|
393
|
+
renameSync(temporary, target);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function writeDirectory(dir: string, files: ReadonlyMap<string, string>, sourceDir: string): void {
|
|
397
|
+
const temporary = temporaryPath(dir);
|
|
398
|
+
mkdirSync(temporary);
|
|
399
|
+
for (const [name, text] of files)
|
|
400
|
+
writeWithModeOf(join(temporary, name), text, join(sourceDir, name));
|
|
401
|
+
renameSync(temporary, dir);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function removeDirectory(dir: string): void {
|
|
405
|
+
const temporary = temporaryPath(dir);
|
|
406
|
+
renameSync(dir, temporary);
|
|
407
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function count(amount: number, singular: string, plural: string): string {
|
|
411
|
+
return `${amount} ${amount === 1 ? singular : plural}`;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const REMOVED_KEY = 'noCheck';
|
|
415
|
+
const ELEMENT_KIND = 'elementNotNull';
|
|
416
|
+
|
|
417
|
+
function listKey(namespace: string, owner: string, member: string): string {
|
|
418
|
+
return `${namespace}\u0000${owner}\u0000${member}`;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
interface Rewrite {
|
|
422
|
+
readonly contract: JsonRecord;
|
|
423
|
+
readonly changed: boolean;
|
|
424
|
+
readonly columns: ReadonlySet<string>;
|
|
425
|
+
readonly fields: ReadonlySet<string>;
|
|
426
|
+
readonly defaults: ReadonlyMap<string, readonly DefaultRewrite[]>;
|
|
427
|
+
readonly notValues: readonly string[];
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
interface DefaultRewrite {
|
|
431
|
+
readonly from: string | number;
|
|
432
|
+
readonly to: string | number;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
type DefaultForm =
|
|
436
|
+
| { readonly kind: 'unchanged' }
|
|
437
|
+
| { readonly kind: 'rewritten'; readonly value: Json }
|
|
438
|
+
| { readonly kind: 'notAValue'; readonly reason: string };
|
|
439
|
+
|
|
440
|
+
type Params = Readonly<Record<string, Json>>;
|
|
441
|
+
|
|
442
|
+
class NotAValue extends Error {}
|
|
443
|
+
|
|
444
|
+
class CastRefused extends Error {}
|
|
445
|
+
|
|
446
|
+
function refuseJsonValue(typeId: string, expected: string): never {
|
|
447
|
+
throw new NotAValue(`${typeId} JSON value must be ${expected}`);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function withoutTrailing(text: string, character: string): string {
|
|
451
|
+
let end = text.length;
|
|
452
|
+
while (end > 0 && text[end - 1] === character) end -= 1;
|
|
453
|
+
return end === text.length ? text : text.slice(0, end);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function counted(amount: number, noun: string): string {
|
|
457
|
+
return `${amount} ${amount === 1 ? noun : `${noun}s`}`;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function integerParam(params: Params, name: string): number | undefined {
|
|
461
|
+
const value = params[name];
|
|
462
|
+
return typeof value === 'number' ? value : undefined;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function readJsonString(typeId: string, json: Json): string {
|
|
466
|
+
return typeof json === 'string' ? json : refuseJsonValue(typeId, 'a string');
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function readJsonMatching(typeId: string, json: Json, pattern: RegExp, form: string): string {
|
|
470
|
+
return typeof json === 'string' && pattern.test(json) ? json : refuseJsonValue(typeId, form);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function readJsonInteger(typeId: string, json: Json, min: number, max: number): Json {
|
|
474
|
+
return typeof json === 'number' && Number.isInteger(json) && json >= min && json <= max
|
|
475
|
+
? json
|
|
476
|
+
: refuseJsonValue(typeId, `an integer from ${min} to ${max}`);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const INT64_MIN = -(2n ** 63n);
|
|
480
|
+
const INT64_MAX = 2n ** 63n - 1n;
|
|
481
|
+
|
|
482
|
+
function readInt8(json: Json): Json {
|
|
483
|
+
const expected = `a decimal integer string from ${INT64_MIN} to ${INT64_MAX}`;
|
|
484
|
+
const value = BigInt(readJsonMatching('pg/int8', json, /^-?\d+$/, expected));
|
|
485
|
+
if (value < INT64_MIN || value > INT64_MAX) return refuseJsonValue('pg/int8', expected);
|
|
486
|
+
const written = value.toString();
|
|
487
|
+
if (json !== written)
|
|
488
|
+
return refuseJsonValue(
|
|
489
|
+
'pg/int8',
|
|
490
|
+
`"${written}", the integer's decimal text without leading zeros or a minus sign on zero`,
|
|
491
|
+
);
|
|
492
|
+
return json;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const NON_FINITE_TEXT: ReadonlySet<string> = new Set(['NaN', 'Infinity', '-Infinity']);
|
|
496
|
+
|
|
497
|
+
function readJsonFloat(typeId: string, json: Json): number {
|
|
498
|
+
if (typeof json === 'number' && Number.isFinite(json)) return json;
|
|
499
|
+
if (typeof json === 'string' && NON_FINITE_TEXT.has(json)) return Number(json);
|
|
500
|
+
return refuseJsonValue(typeId, 'a finite number or the text NaN, Infinity or -Infinity');
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const FLOAT4_MAX = 3.4028234663852886e38;
|
|
504
|
+
|
|
505
|
+
function fitsFloat4(value: number): boolean {
|
|
506
|
+
const single = Math.fround(value);
|
|
507
|
+
return Number.isFinite(single) && (value === 0 || single !== 0);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function readFloat4(json: Json): Json {
|
|
511
|
+
const value = readJsonFloat('pg/float4', json);
|
|
512
|
+
if (Number.isFinite(value) && !fitsFloat4(value))
|
|
513
|
+
return refuseJsonValue(
|
|
514
|
+
'pg/float4',
|
|
515
|
+
`a number float4 holds, at most ${FLOAT4_MAX} in magnitude and not so small that it becomes 0, or the text NaN, Infinity or -Infinity`,
|
|
516
|
+
);
|
|
517
|
+
return json;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const DECIMAL_NUMERAL_TEXT = /^-?\d+(?:\.\d+)?$/;
|
|
521
|
+
const STORED_NUMERIC_TEXT = /^(?:(?!-0(?:\.0+)?$)-?(?:0|[1-9]\d*)(?:\.\d+)?|NaN|-?Infinity)$/;
|
|
522
|
+
|
|
523
|
+
function storedNumeralText(text: string): string {
|
|
524
|
+
const numeral = /^([+-]?)0*(\d+)(\.\d+)?$/.exec(text);
|
|
525
|
+
if (numeral === null) return text;
|
|
526
|
+
const [, sign = '', whole = '', fraction = ''] = numeral;
|
|
527
|
+
const digits = `${whole}${fraction}`;
|
|
528
|
+
return sign !== '-' || /^[0.]+$/.test(digits) ? digits : `-${digits}`;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function fitsNumeric(text: string, precision: number, scale: number): boolean {
|
|
532
|
+
if (text === 'NaN') return true;
|
|
533
|
+
if (text.endsWith('Infinity')) return false;
|
|
534
|
+
const [whole = '', fraction = ''] = text.replace(/^-/, '').split('.');
|
|
535
|
+
const significantFraction = withoutTrailing(fraction, '0');
|
|
536
|
+
const digits = `${whole}${significantFraction}`.replace(/^0+/, '');
|
|
537
|
+
if (digits === '') return true;
|
|
538
|
+
const shift = scale - significantFraction.length;
|
|
539
|
+
if (shift >= 0) return digits.length + shift <= precision;
|
|
540
|
+
const units = withoutTrailing(digits, '0');
|
|
541
|
+
const droppedZeros = digits.length - units.length;
|
|
542
|
+
if (droppedZeros < -shift) return false;
|
|
543
|
+
return digits.length + shift <= precision;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function readNumeric(json: Json, params: Params): Json {
|
|
547
|
+
if (typeof json !== 'string' || !STORED_NUMERIC_TEXT.test(json)) {
|
|
548
|
+
const printed =
|
|
549
|
+
typeof json === 'string' && DECIMAL_NUMERAL_TEXT.test(json)
|
|
550
|
+
? storedNumeralText(json)
|
|
551
|
+
: undefined;
|
|
552
|
+
return refuseJsonValue(
|
|
553
|
+
'pg/numeric',
|
|
554
|
+
printed === undefined ? 'a decimal string' : `"${printed}", as PostgreSQL writes this value`,
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
const precision = integerParam(params, 'precision');
|
|
558
|
+
if (precision === undefined) return json;
|
|
559
|
+
const scale = integerParam(params, 'scale') ?? 0;
|
|
560
|
+
if (!fitsNumeric(json, precision, scale))
|
|
561
|
+
return refuseJsonValue(
|
|
562
|
+
'pg/numeric',
|
|
563
|
+
`a decimal string that numeric(${precision}, ${scale}) stores without rounding`,
|
|
564
|
+
);
|
|
565
|
+
return json;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function spellNumeric(json: Json, params: Params): Json {
|
|
569
|
+
const precision = integerParam(params, 'precision');
|
|
570
|
+
if (precision === undefined || typeof json !== 'string' || json === 'NaN') return json;
|
|
571
|
+
const scale = integerParam(params, 'scale') ?? 0;
|
|
572
|
+
const [whole = '', fraction = ''] = json.split('.');
|
|
573
|
+
return scale <= 0 ? whole : `${whole}.${fraction.slice(0, scale).padEnd(scale, '0')}`;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function fitsCharacterLength(text: string, length: number, blankPadded: boolean): boolean {
|
|
577
|
+
const significant = blankPadded ? withoutTrailing(text, ' ') : text;
|
|
578
|
+
return significant.length <= length || [...significant].length <= length;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function readCharacter(json: Json, params: Params): Json {
|
|
582
|
+
const length = integerParam(params, 'length') ?? 1;
|
|
583
|
+
if (!fitsCharacterLength(readJsonString('pg/char', json), length, true))
|
|
584
|
+
return refuseJsonValue(
|
|
585
|
+
'pg/char',
|
|
586
|
+
`a string of at most ${counted(length, 'character')} before any trailing spaces`,
|
|
587
|
+
);
|
|
588
|
+
return json;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function spellCharacter(json: Json): Json {
|
|
592
|
+
return typeof json === 'string' ? withoutTrailing(json, ' ') : json;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function readCharacterVarying(json: Json, params: Params): Json {
|
|
596
|
+
const length = integerParam(params, 'length');
|
|
597
|
+
const text = readJsonString('pg/varchar', json);
|
|
598
|
+
if (length !== undefined && !fitsCharacterLength(text, length, false))
|
|
599
|
+
return refuseJsonValue('pg/varchar', `a string of at most ${counted(length, 'character')}`);
|
|
600
|
+
return json;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const BIT_STRING = /^[01]*$/;
|
|
604
|
+
|
|
605
|
+
function readBit(json: Json, params: Params): Json {
|
|
606
|
+
const length = integerParam(params, 'length') ?? 1;
|
|
607
|
+
const bits = readJsonMatching('pg/bit', json, BIT_STRING, 'a string of 0 and 1 digits');
|
|
608
|
+
if (bits.length !== length)
|
|
609
|
+
return refuseJsonValue('pg/bit', `a string of exactly ${counted(length, 'bit')}`);
|
|
610
|
+
return json;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function readBitVarying(json: Json, params: Params): Json {
|
|
614
|
+
const length = integerParam(params, 'length');
|
|
615
|
+
const bits = readJsonMatching('pg/varbit', json, BIT_STRING, 'a string of 0 and 1 digits');
|
|
616
|
+
if (length !== undefined && bits.length > length)
|
|
617
|
+
return refuseJsonValue('pg/varbit', `a string of at most ${counted(length, 'bit')}`);
|
|
618
|
+
return json;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function readTextArray(json: Json): Json {
|
|
622
|
+
const expected = 'an array of strings and nulls';
|
|
623
|
+
if (!Array.isArray(json)) return refuseJsonValue('pg/text-array', expected);
|
|
624
|
+
for (const entry of json)
|
|
625
|
+
if (entry !== null && typeof entry !== 'string')
|
|
626
|
+
return refuseJsonValue('pg/text-array', expected);
|
|
627
|
+
return json;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const UUID_INPUT = /^(?:\{[0-9a-f]{4}(?:-?[0-9a-f]{4}){7}\}|[0-9a-f]{4}(?:-?[0-9a-f]{4}){7})$/i;
|
|
631
|
+
|
|
632
|
+
function storedUuid(text: string): string | undefined {
|
|
633
|
+
if (!UUID_INPUT.test(text)) return undefined;
|
|
634
|
+
const hex = text.replace(/[{}-]/g, '').toLowerCase();
|
|
635
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
interface InetValue {
|
|
639
|
+
readonly bytes: readonly number[];
|
|
640
|
+
readonly bits: number;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const isDigit = (ch: string | undefined): ch is string => ch !== undefined && /^[0-9]$/.test(ch);
|
|
644
|
+
|
|
645
|
+
function storedInet(text: string): string | undefined {
|
|
646
|
+
if (text.includes(':')) {
|
|
647
|
+
const value = readIpv6(text);
|
|
648
|
+
return value === undefined ? undefined : printIpv6(value);
|
|
649
|
+
}
|
|
650
|
+
const value = readIpv4(text);
|
|
651
|
+
return value === undefined ? undefined : printIpv4(value);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function readIpv4(text: string): InetValue | undefined {
|
|
655
|
+
const octets: number[] = [];
|
|
656
|
+
let index = 0;
|
|
657
|
+
let ch = text[index++];
|
|
658
|
+
while (isDigit(ch)) {
|
|
659
|
+
let octet = 0;
|
|
660
|
+
do {
|
|
661
|
+
octet = octet * 10 + Number(ch);
|
|
662
|
+
if (octet > 255) return undefined;
|
|
663
|
+
ch = text[index++];
|
|
664
|
+
} while (isDigit(ch));
|
|
665
|
+
if (octets.length === 4) return undefined;
|
|
666
|
+
octets.push(octet);
|
|
667
|
+
if (ch === undefined || ch === '/') break;
|
|
668
|
+
if (ch !== '.') return undefined;
|
|
669
|
+
ch = text[index++];
|
|
670
|
+
}
|
|
671
|
+
let bits = -1;
|
|
672
|
+
if (ch === '/' && isDigit(text[index]) && octets.length > 0) {
|
|
673
|
+
ch = text[index++];
|
|
674
|
+
bits = 0;
|
|
675
|
+
do {
|
|
676
|
+
bits = bits * 10 + Number(ch);
|
|
677
|
+
ch = text[index++];
|
|
678
|
+
} while (isDigit(ch));
|
|
679
|
+
if (ch !== undefined || bits > 32) return undefined;
|
|
680
|
+
}
|
|
681
|
+
if (ch !== undefined) return undefined;
|
|
682
|
+
if (bits === -1) {
|
|
683
|
+
if (octets.length !== 4) return undefined;
|
|
684
|
+
bits = 32;
|
|
685
|
+
}
|
|
686
|
+
if (octets.length === 0 || Math.floor(bits / 8) > octets.length) return undefined;
|
|
687
|
+
return { bytes: [...octets, 0, 0, 0, 0].slice(0, 4), bits };
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function readBits(text: string): number | undefined {
|
|
691
|
+
let bits = 0;
|
|
692
|
+
let digits = 0;
|
|
693
|
+
for (const ch of text) {
|
|
694
|
+
if (!isDigit(ch)) return undefined;
|
|
695
|
+
if (digits++ !== 0 && bits === 0) return undefined;
|
|
696
|
+
bits = bits * 10 + Number(ch);
|
|
697
|
+
if (bits > 128) return undefined;
|
|
698
|
+
}
|
|
699
|
+
return digits === 0 ? undefined : bits;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function readIpv4Tail(
|
|
703
|
+
text: string,
|
|
704
|
+
): { readonly octets: readonly number[]; readonly bits: number | undefined } | undefined {
|
|
705
|
+
const octets: number[] = [];
|
|
706
|
+
let octet = 0;
|
|
707
|
+
let digits = 0;
|
|
708
|
+
for (const [index, ch] of [...text].entries()) {
|
|
709
|
+
if (isDigit(ch)) {
|
|
710
|
+
if (digits++ !== 0 && octet === 0) return undefined;
|
|
711
|
+
octet = octet * 10 + Number(ch);
|
|
712
|
+
if (octet > 255) return undefined;
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
if (ch !== '.' && ch !== '/') return undefined;
|
|
716
|
+
if (octets.length > 3) return undefined;
|
|
717
|
+
octets.push(octet);
|
|
718
|
+
if (ch === '/') {
|
|
719
|
+
const bits = readBits(text.slice(index + 1));
|
|
720
|
+
return bits === undefined ? undefined : { octets, bits };
|
|
721
|
+
}
|
|
722
|
+
octet = 0;
|
|
723
|
+
digits = 0;
|
|
724
|
+
}
|
|
725
|
+
if (digits === 0 || octets.length > 3) return undefined;
|
|
726
|
+
return { octets: [...octets, octet], bits: undefined };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function readIpv6(text: string): InetValue | undefined {
|
|
730
|
+
const bytes = new Array<number>(16).fill(0);
|
|
731
|
+
let filled = 0;
|
|
732
|
+
let compressedAt: number | undefined;
|
|
733
|
+
let index = 0;
|
|
734
|
+
if (text[0] === ':') {
|
|
735
|
+
if (text[1] !== ':') return undefined;
|
|
736
|
+
index = 1;
|
|
737
|
+
}
|
|
738
|
+
let tokenStart = index;
|
|
739
|
+
let sawHexDigit = false;
|
|
740
|
+
let group = 0;
|
|
741
|
+
let groupDigits = 0;
|
|
742
|
+
let bits = 128;
|
|
743
|
+
while (index < text.length) {
|
|
744
|
+
const ch = text[index++] ?? '';
|
|
745
|
+
if (/^[0-9a-fA-F]$/.test(ch)) {
|
|
746
|
+
group = (group << 4) | Number.parseInt(ch, 16);
|
|
747
|
+
if (++groupDigits > 4) return undefined;
|
|
748
|
+
sawHexDigit = true;
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
if (ch === ':') {
|
|
752
|
+
tokenStart = index;
|
|
753
|
+
if (!sawHexDigit) {
|
|
754
|
+
if (compressedAt !== undefined) return undefined;
|
|
755
|
+
compressedAt = filled;
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
if (index >= text.length || filled + 2 > 16) return undefined;
|
|
759
|
+
bytes[filled++] = group >> 8;
|
|
760
|
+
bytes[filled++] = group & 0xff;
|
|
761
|
+
sawHexDigit = false;
|
|
762
|
+
group = 0;
|
|
763
|
+
groupDigits = 0;
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
if (ch === '.' && filled + 4 <= 16) {
|
|
767
|
+
const tail = readIpv4Tail(text.slice(tokenStart));
|
|
768
|
+
if (tail !== undefined) {
|
|
769
|
+
tail.octets.forEach((octet, offset) => {
|
|
770
|
+
bytes[filled + offset] = octet;
|
|
771
|
+
});
|
|
772
|
+
filled += 4;
|
|
773
|
+
sawHexDigit = false;
|
|
774
|
+
bits = tail.bits ?? bits;
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
if (ch === '/') {
|
|
779
|
+
const prefix = readBits(text.slice(index));
|
|
780
|
+
if (prefix !== undefined) {
|
|
781
|
+
bits = prefix;
|
|
782
|
+
break;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return undefined;
|
|
786
|
+
}
|
|
787
|
+
if (sawHexDigit) {
|
|
788
|
+
if (filled + 2 > 16) return undefined;
|
|
789
|
+
bytes[filled++] = group >> 8;
|
|
790
|
+
bytes[filled++] = group & 0xff;
|
|
791
|
+
}
|
|
792
|
+
if (compressedAt !== undefined) {
|
|
793
|
+
if (filled === 16) return undefined;
|
|
794
|
+
const shifted = bytes.slice(compressedAt, filled);
|
|
795
|
+
bytes.fill(0, compressedAt, filled);
|
|
796
|
+
bytes.splice(16 - shifted.length, shifted.length, ...shifted);
|
|
797
|
+
filled = 16;
|
|
798
|
+
}
|
|
799
|
+
return filled === 16 ? { bytes, bits } : undefined;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function printIpv4({ bytes, bits }: InetValue): string {
|
|
803
|
+
const address = bytes.join('.');
|
|
804
|
+
return bits === 32 ? address : `${address}/${bits}`;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function printIpv6({ bytes, bits }: InetValue): string {
|
|
808
|
+
const groups = Array.from(
|
|
809
|
+
{ length: 8 },
|
|
810
|
+
(_, i) => ((bytes[2 * i] ?? 0) << 8) | (bytes[2 * i + 1] ?? 0),
|
|
811
|
+
);
|
|
812
|
+
const zeroRun = longestZeroRun(groups);
|
|
813
|
+
let text = '';
|
|
814
|
+
for (let i = 0; i < 8; i++) {
|
|
815
|
+
if (zeroRun !== undefined && i >= zeroRun.start && i < zeroRun.start + zeroRun.length) {
|
|
816
|
+
if (i === zeroRun.start) text += ':';
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (i !== 0) text += ':';
|
|
820
|
+
const ipv4Tail =
|
|
821
|
+
i === 6 &&
|
|
822
|
+
zeroRun?.start === 0 &&
|
|
823
|
+
(zeroRun.length === 6 || (zeroRun.length === 5 && groups[5] === 0xffff));
|
|
824
|
+
if (ipv4Tail) {
|
|
825
|
+
text += bytes.slice(12).join('.');
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
828
|
+
text += (groups[i] ?? 0).toString(16);
|
|
829
|
+
}
|
|
830
|
+
if (zeroRun !== undefined && zeroRun.start + zeroRun.length === 8) text += ':';
|
|
831
|
+
return bits === 128 ? text : `${text}/${bits}`;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function longestZeroRun(
|
|
835
|
+
groups: readonly number[],
|
|
836
|
+
): { readonly start: number; readonly length: number } | undefined {
|
|
837
|
+
let best: { start: number; length: number } | undefined;
|
|
838
|
+
let current: { start: number; length: number } | undefined;
|
|
839
|
+
for (const [i, group] of groups.entries()) {
|
|
840
|
+
if (group === 0) {
|
|
841
|
+
current =
|
|
842
|
+
current === undefined
|
|
843
|
+
? { start: i, length: 1 }
|
|
844
|
+
: { ...current, length: current.length + 1 };
|
|
845
|
+
continue;
|
|
846
|
+
}
|
|
847
|
+
if (current !== undefined && (best === undefined || current.length > best.length))
|
|
848
|
+
best = current;
|
|
849
|
+
current = undefined;
|
|
850
|
+
}
|
|
851
|
+
if (current !== undefined && (best === undefined || current.length > best.length)) best = current;
|
|
852
|
+
return best !== undefined && best.length >= 2 ? best : undefined;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
const BASE64_TEXT = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
856
|
+
|
|
857
|
+
function spellBytea(json: Json): Json {
|
|
858
|
+
return typeof json === 'string' ? Buffer.from(json, 'base64').toString('base64') : json;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
const ISO_DURATION =
|
|
862
|
+
/^P(?!$)(-?\d+Y)?(-?\d+M)?(-?\d+D)?(?:T(?!$)(-?\d+H)?(-?\d+M)?(-?\d+(?:\.\d+)?S)?)?$/;
|
|
863
|
+
const MICROS_PER_SECOND = 1_000_000n;
|
|
864
|
+
|
|
865
|
+
interface IntervalFields {
|
|
866
|
+
readonly months: number;
|
|
867
|
+
readonly days: number;
|
|
868
|
+
readonly micros: bigint;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function microsFromFraction(fraction: string, negative: boolean): bigint {
|
|
872
|
+
if (fraction === '') return 0n;
|
|
873
|
+
const kept = BigInt(fraction.slice(0, 6).padEnd(6, '0'));
|
|
874
|
+
const rest = fraction.slice(6).replace(/0+$/, '');
|
|
875
|
+
if (rest === '') return kept;
|
|
876
|
+
const half = rest[0] === '5' && rest.length === 1;
|
|
877
|
+
const roundsUp = rest > '5' || (half && !negative);
|
|
878
|
+
return roundsUp ? kept + 1n : kept;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function intervalFieldsOf(match: RegExpExecArray): IntervalFields {
|
|
882
|
+
const [, years, months, days, hours, minutes, seconds] = match;
|
|
883
|
+
const wholeNumber = (part: string | undefined): number =>
|
|
884
|
+
part === undefined ? 0 : Number(part.slice(0, -1));
|
|
885
|
+
const secondsLiteral = seconds === undefined ? '0' : seconds.slice(0, -1);
|
|
886
|
+
const negative = secondsLiteral.startsWith('-');
|
|
887
|
+
const [whole = '0', fraction = ''] = secondsLiteral.replace('-', '').split('.');
|
|
888
|
+
const magnitude = BigInt(whole) * MICROS_PER_SECOND + microsFromFraction(fraction, negative);
|
|
889
|
+
return {
|
|
890
|
+
months: wholeNumber(years) * 12 + wholeNumber(months),
|
|
891
|
+
days: wholeNumber(days),
|
|
892
|
+
micros:
|
|
893
|
+
BigInt(wholeNumber(hours)) * 3_600n * MICROS_PER_SECOND +
|
|
894
|
+
BigInt(wholeNumber(minutes)) * 60n * MICROS_PER_SECOND +
|
|
895
|
+
(negative ? -magnitude : magnitude),
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
function secondsText(micros: bigint): string {
|
|
900
|
+
const sign = micros < 0n ? '-' : '';
|
|
901
|
+
const magnitude = micros < 0n ? -micros : micros;
|
|
902
|
+
const whole = (magnitude / MICROS_PER_SECOND) % 60n;
|
|
903
|
+
const fraction = magnitude % MICROS_PER_SECOND;
|
|
904
|
+
const fractionText =
|
|
905
|
+
fraction === 0n ? '' : `.${fraction.toString().padStart(6, '0').replace(/0+$/, '')}`;
|
|
906
|
+
return `${sign}${whole}${fractionText}`;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function formatIsoDuration({ months, days, micros }: IntervalFields): string {
|
|
910
|
+
const years = Math.trunc(months / 12);
|
|
911
|
+
const restMonths = months % 12;
|
|
912
|
+
const sign = micros < 0n ? '-' : '';
|
|
913
|
+
const magnitude = micros < 0n ? -micros : micros;
|
|
914
|
+
const hours = magnitude / (3_600n * MICROS_PER_SECOND);
|
|
915
|
+
const minutes = (magnitude / (60n * MICROS_PER_SECOND)) % 60n;
|
|
916
|
+
const hasSeconds = magnitude % (60n * MICROS_PER_SECOND) !== 0n;
|
|
917
|
+
const parts = [
|
|
918
|
+
years === 0 ? '' : `${years}Y`,
|
|
919
|
+
restMonths === 0 ? '' : `${restMonths}M`,
|
|
920
|
+
days === 0 ? '' : `${days}D`,
|
|
921
|
+
];
|
|
922
|
+
const time = [
|
|
923
|
+
hours === 0n ? '' : `${sign}${hours}H`,
|
|
924
|
+
minutes === 0n ? '' : `${sign}${minutes}M`,
|
|
925
|
+
hasSeconds ? `${secondsText(micros)}S` : '',
|
|
926
|
+
].join('');
|
|
927
|
+
const rendered = `P${parts.join('')}${time === '' ? '' : `T${time}`}`;
|
|
928
|
+
return rendered === 'P' ? 'PT0S' : rendered;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const POSTGRES_INTERVAL =
|
|
932
|
+
/^(?:([+-]?\d+) years? ?)?(?:([+-]?\d+) mons? ?)?(?:([+-]?\d+) days? ?)?(?:([+-])?(\d+):(\d{2}):(\d{2})(?:\.(\d+))?)?$/;
|
|
933
|
+
|
|
934
|
+
function postgresIntervalFields(text: string): IntervalFields | undefined {
|
|
935
|
+
const match = POSTGRES_INTERVAL.exec(text);
|
|
936
|
+
if (match === null || text === '' || text.endsWith(' ')) return undefined;
|
|
937
|
+
const [, years = '0', months = '0', days = '0', sign, hours = '0', minutes = '0', seconds = '0'] =
|
|
938
|
+
match;
|
|
939
|
+
const fraction = match[8] ?? '';
|
|
940
|
+
const magnitude =
|
|
941
|
+
(BigInt(hours) * 3_600n + BigInt(minutes) * 60n + BigInt(seconds)) * MICROS_PER_SECOND +
|
|
942
|
+
microsFromFraction(fraction, sign === '-');
|
|
943
|
+
return {
|
|
944
|
+
months: Number(years) * 12 + Number(months),
|
|
945
|
+
days: Number(days),
|
|
946
|
+
micros: sign === '-' ? -magnitude : magnitude,
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
function intervalStoredText(text: string): string {
|
|
951
|
+
const fractionDigits = /\.(\d+)/.exec(text)?.[1]?.length ?? 0;
|
|
952
|
+
if (fractionDigits > 6)
|
|
953
|
+
throw new CastRefused(
|
|
954
|
+
`"${text}" has ${fractionDigits} digits after the decimal point, but pg/interval holds microseconds, so at most 6. Round it, as in "PT1.123456S".`,
|
|
955
|
+
);
|
|
956
|
+
const iso = ISO_DURATION.exec(text);
|
|
957
|
+
if (iso !== null) return formatIsoDuration(intervalFieldsOf(iso));
|
|
958
|
+
const fields = postgresIntervalFields(text);
|
|
959
|
+
if (fields === undefined)
|
|
960
|
+
throw new CastRefused(
|
|
961
|
+
`pg/interval cannot read "${text}". Write an ISO 8601 duration, as in "P1Y2M3DT4H5M6S".`,
|
|
962
|
+
);
|
|
963
|
+
return formatIsoDuration(fields);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function isoYearText(text: string): string {
|
|
967
|
+
const match = /^(\d{4,6})(-.*?)( BC)?$/.exec(text);
|
|
968
|
+
if (match === null) return text;
|
|
969
|
+
const [, digits = '', rest = '', bc] = match;
|
|
970
|
+
const year = Number(digits);
|
|
971
|
+
if (bc !== undefined) {
|
|
972
|
+
if (year === 0) return text;
|
|
973
|
+
return `${yearText(1 - year)}${rest}`;
|
|
974
|
+
}
|
|
975
|
+
return digits.length > 4 ? `${yearText(year)}${rest}` : text;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
type DateTimeShape = 'date' | 'time' | 'timeWithOffset' | 'dateTime' | 'instant';
|
|
979
|
+
|
|
980
|
+
interface DateTimeOptions {
|
|
981
|
+
readonly shape: DateTimeShape;
|
|
982
|
+
readonly typeId: string;
|
|
983
|
+
readonly maxOffsetHours?: number;
|
|
984
|
+
readonly range?: { readonly earliest: string; readonly latest: string };
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
interface DateFields {
|
|
988
|
+
readonly year: number;
|
|
989
|
+
readonly month: number;
|
|
990
|
+
readonly day: number;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
interface TimeFields {
|
|
994
|
+
readonly hour: number;
|
|
995
|
+
readonly minute: number;
|
|
996
|
+
readonly second: number;
|
|
997
|
+
readonly fraction: string;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
interface WrittenDateTime {
|
|
1001
|
+
readonly date: DateFields | undefined;
|
|
1002
|
+
readonly time: TimeFields | undefined;
|
|
1003
|
+
readonly offsetSeconds: number | undefined;
|
|
1004
|
+
readonly fractionDigits: number;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
const SHAPES: Readonly<
|
|
1008
|
+
Record<
|
|
1009
|
+
DateTimeShape,
|
|
1010
|
+
{
|
|
1011
|
+
readonly description: string;
|
|
1012
|
+
readonly plural: string;
|
|
1013
|
+
readonly example: string;
|
|
1014
|
+
readonly date: boolean;
|
|
1015
|
+
readonly time: boolean;
|
|
1016
|
+
readonly offset: boolean;
|
|
1017
|
+
}
|
|
1018
|
+
>
|
|
1019
|
+
> = {
|
|
1020
|
+
date: {
|
|
1021
|
+
description: 'a date',
|
|
1022
|
+
plural: 'dates',
|
|
1023
|
+
example: '2024-01-01',
|
|
1024
|
+
date: true,
|
|
1025
|
+
time: false,
|
|
1026
|
+
offset: false,
|
|
1027
|
+
},
|
|
1028
|
+
time: {
|
|
1029
|
+
description: 'a time of day',
|
|
1030
|
+
plural: 'times of day',
|
|
1031
|
+
example: '12:34:56',
|
|
1032
|
+
date: false,
|
|
1033
|
+
time: true,
|
|
1034
|
+
offset: false,
|
|
1035
|
+
},
|
|
1036
|
+
timeWithOffset: {
|
|
1037
|
+
description: 'a time of day with a UTC offset',
|
|
1038
|
+
plural: 'times of day with a UTC offset',
|
|
1039
|
+
example: '12:34:56+02:00',
|
|
1040
|
+
date: false,
|
|
1041
|
+
time: true,
|
|
1042
|
+
offset: true,
|
|
1043
|
+
},
|
|
1044
|
+
dateTime: {
|
|
1045
|
+
description: 'a date and time',
|
|
1046
|
+
plural: 'dates and times',
|
|
1047
|
+
example: '2024-01-01T12:34:56',
|
|
1048
|
+
date: true,
|
|
1049
|
+
time: true,
|
|
1050
|
+
offset: false,
|
|
1051
|
+
},
|
|
1052
|
+
instant: {
|
|
1053
|
+
description: 'a date and time with a UTC offset',
|
|
1054
|
+
plural: 'instants',
|
|
1055
|
+
example: '2024-01-01T12:34:56Z',
|
|
1056
|
+
date: true,
|
|
1057
|
+
time: true,
|
|
1058
|
+
offset: true,
|
|
1059
|
+
},
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
const DATE_PREFIX = /^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})/;
|
|
1063
|
+
const TIME_PREFIX = /^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?/;
|
|
1064
|
+
const OFFSET = /^([+-])(\d{2})(?::(\d{2})(?::(\d{2}))?)?$/;
|
|
1065
|
+
const MAX_FRACTION_DIGITS = 6;
|
|
1066
|
+
const SECONDS_PER_DAY = 86_400;
|
|
1067
|
+
const MIDNIGHT: TimeFields = { hour: 0, minute: 0, second: 0, fraction: '' };
|
|
1068
|
+
|
|
1069
|
+
function isLeapYear(year: number): boolean {
|
|
1070
|
+
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
function daysInMonth(year: number, month: number): number {
|
|
1074
|
+
if (month === 2) return isLeapYear(year) ? 29 : 28;
|
|
1075
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function daysFromCivil({ year, month, day }: DateFields): number {
|
|
1079
|
+
const shifted = month <= 2 ? year - 1 : year;
|
|
1080
|
+
const era = Math.floor(shifted / 400);
|
|
1081
|
+
const yearOfEra = shifted - era * 400;
|
|
1082
|
+
const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
|
|
1083
|
+
const dayOfEra =
|
|
1084
|
+
yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
|
|
1085
|
+
return era * 146_097 + dayOfEra - 719_468;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function civilFromDays(days: number): DateFields {
|
|
1089
|
+
const shifted = days + 719_468;
|
|
1090
|
+
const era = Math.floor(shifted / 146_097);
|
|
1091
|
+
const dayOfEra = shifted - era * 146_097;
|
|
1092
|
+
const yearOfEra = Math.floor(
|
|
1093
|
+
(dayOfEra -
|
|
1094
|
+
Math.floor(dayOfEra / 1460) +
|
|
1095
|
+
Math.floor(dayOfEra / 36_524) -
|
|
1096
|
+
Math.floor(dayOfEra / 146_096)) /
|
|
1097
|
+
365,
|
|
1098
|
+
);
|
|
1099
|
+
const dayOfYear =
|
|
1100
|
+
dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
|
|
1101
|
+
const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
|
|
1102
|
+
const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
|
|
1103
|
+
const month = monthIndex < 10 ? monthIndex + 3 : monthIndex - 9;
|
|
1104
|
+
return { year: yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day };
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
function pad(value: number, width = 2): string {
|
|
1108
|
+
return String(value).padStart(width, '0');
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
function yearText(year: number): string {
|
|
1112
|
+
if (year >= 0 && year <= 9999) return pad(year, 4);
|
|
1113
|
+
return `${year < 0 ? '-' : '+'}${pad(Math.abs(year), 6)}`;
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
function dateText(date: DateFields): string {
|
|
1117
|
+
return `${yearText(date.year)}-${pad(date.month)}-${pad(date.day)}`;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
function timeText(time: TimeFields): string {
|
|
1121
|
+
const fraction = time.fraction.replace(/0+$/, '');
|
|
1122
|
+
return `${pad(time.hour)}:${pad(time.minute)}:${pad(time.second)}${fraction === '' ? '' : `.${fraction}`}`;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
function offsetText(seconds: number): string {
|
|
1126
|
+
if (seconds === 0) return 'Z';
|
|
1127
|
+
const magnitude = Math.abs(seconds);
|
|
1128
|
+
const rest = magnitude % 60;
|
|
1129
|
+
return `${seconds < 0 ? '-' : '+'}${pad(Math.floor(magnitude / 3600))}:${pad(Math.floor(magnitude / 60) % 60)}${rest === 0 ? '' : `:${pad(rest)}`}`;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function readWritten(text: string): WrittenDateTime | undefined {
|
|
1133
|
+
let rest = text;
|
|
1134
|
+
let date: DateFields | undefined;
|
|
1135
|
+
let timeFollows = true;
|
|
1136
|
+
const dateMatch = DATE_PREFIX.exec(rest);
|
|
1137
|
+
if (dateMatch !== null) {
|
|
1138
|
+
const [whole, yearDigits = '', month = '', day = ''] = dateMatch;
|
|
1139
|
+
if (yearDigits === '-000000') return undefined;
|
|
1140
|
+
date = { year: Number(yearDigits), month: Number(month), day: Number(day) };
|
|
1141
|
+
rest = rest.slice(whole.length);
|
|
1142
|
+
timeFollows = /^[Tt ]/.test(rest);
|
|
1143
|
+
if (timeFollows) rest = rest.slice(1);
|
|
1144
|
+
}
|
|
1145
|
+
let time: TimeFields | undefined;
|
|
1146
|
+
let fractionDigits = 0;
|
|
1147
|
+
if (timeFollows) {
|
|
1148
|
+
const timeMatch = TIME_PREFIX.exec(rest);
|
|
1149
|
+
if (timeMatch === null) return undefined;
|
|
1150
|
+
const [whole, hour = '', minute = '', second = '00', fraction = ''] = timeMatch;
|
|
1151
|
+
time = { hour: Number(hour), minute: Number(minute), second: Number(second), fraction };
|
|
1152
|
+
fractionDigits = fraction.length;
|
|
1153
|
+
rest = rest.slice(whole.length);
|
|
1154
|
+
}
|
|
1155
|
+
let offsetSeconds: number | undefined;
|
|
1156
|
+
if (rest === 'Z' || rest === 'z') {
|
|
1157
|
+
offsetSeconds = 0;
|
|
1158
|
+
} else if (rest !== '') {
|
|
1159
|
+
const offset = OFFSET.exec(rest);
|
|
1160
|
+
if (offset === null) return undefined;
|
|
1161
|
+
const [, sign, hours = '', minutes = '00', seconds = '00'] = offset;
|
|
1162
|
+
if (Number(minutes) > 59 || Number(seconds) > 59) return undefined;
|
|
1163
|
+
const magnitude = Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);
|
|
1164
|
+
offsetSeconds = sign === '-' ? -magnitude : magnitude;
|
|
1165
|
+
}
|
|
1166
|
+
return { date, time, offsetSeconds, fractionDigits };
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
type Position = readonly [days: number, seconds: number, fraction: string];
|
|
1170
|
+
|
|
1171
|
+
interface NormalizedDateTime {
|
|
1172
|
+
readonly date: DateFields | undefined;
|
|
1173
|
+
readonly time: TimeFields;
|
|
1174
|
+
readonly offsetSeconds: number;
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
function normalized(written: WrittenDateTime, shape: DateTimeShape): NormalizedDateTime {
|
|
1178
|
+
const clock = written.time ?? MIDNIGHT;
|
|
1179
|
+
const offsetSeconds = written.offsetSeconds ?? 0;
|
|
1180
|
+
if (written.date === undefined || shape !== 'instant')
|
|
1181
|
+
return { date: written.date, time: clock, offsetSeconds };
|
|
1182
|
+
const utc =
|
|
1183
|
+
daysFromCivil(written.date) * SECONDS_PER_DAY +
|
|
1184
|
+
clock.hour * 3600 +
|
|
1185
|
+
clock.minute * 60 +
|
|
1186
|
+
clock.second -
|
|
1187
|
+
offsetSeconds;
|
|
1188
|
+
const days = Math.floor(utc / SECONDS_PER_DAY);
|
|
1189
|
+
const secondOfDay = utc - days * SECONDS_PER_DAY;
|
|
1190
|
+
return {
|
|
1191
|
+
date: civilFromDays(days),
|
|
1192
|
+
time: {
|
|
1193
|
+
hour: Math.floor(secondOfDay / 3600),
|
|
1194
|
+
minute: Math.floor(secondOfDay / 60) % 60,
|
|
1195
|
+
second: secondOfDay % 60,
|
|
1196
|
+
fraction: clock.fraction,
|
|
1197
|
+
},
|
|
1198
|
+
offsetSeconds: 0,
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
function position(value: NormalizedDateTime): Position {
|
|
1203
|
+
const { time } = value;
|
|
1204
|
+
return [
|
|
1205
|
+
value.date === undefined ? 0 : daysFromCivil(value.date),
|
|
1206
|
+
time.hour * 3600 + time.minute * 60 + time.second,
|
|
1207
|
+
time.fraction.padEnd(MAX_FRACTION_DIGITS, '0'),
|
|
1208
|
+
];
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
function isBefore(left: Position, right: Position): boolean {
|
|
1212
|
+
if (left[0] !== right[0]) return left[0] < right[0];
|
|
1213
|
+
if (left[1] !== right[1]) return left[1] < right[1];
|
|
1214
|
+
return left[2] < right[2];
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function printed(value: NormalizedDateTime, shape: DateTimeShape): string {
|
|
1218
|
+
const { date, time, offsetSeconds } = value;
|
|
1219
|
+
if (date === undefined)
|
|
1220
|
+
return shape === 'timeWithOffset'
|
|
1221
|
+
? `${timeText(time)}${offsetText(offsetSeconds)}`
|
|
1222
|
+
: timeText(time);
|
|
1223
|
+
if (shape === 'date') return dateText(date);
|
|
1224
|
+
if (shape === 'dateTime') return `${dateText(date)}T${timeText(time)}`;
|
|
1225
|
+
return `${dateText(date)}T${timeText(time)}Z`;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
function boundPosition(text: string, shape: DateTimeShape): Position {
|
|
1229
|
+
const written = readWritten(text);
|
|
1230
|
+
if (written === undefined)
|
|
1231
|
+
throw new Error(`The range bound "${text}" is not in its stored form.`);
|
|
1232
|
+
return position(normalized(written, shape));
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
function dateTimeStoredText(text: string, options: DateTimeOptions, written: string): string {
|
|
1236
|
+
const shape = SHAPES[options.shape];
|
|
1237
|
+
const id = options.typeId;
|
|
1238
|
+
const parts = readWritten(text);
|
|
1239
|
+
if (parts === undefined)
|
|
1240
|
+
throw new CastRefused(
|
|
1241
|
+
`${id} cannot read "${written}". Write ${shape.description}, as in "${shape.example}".`,
|
|
1242
|
+
);
|
|
1243
|
+
if (parts.date !== undefined && !shape.date)
|
|
1244
|
+
throw new CastRefused(
|
|
1245
|
+
`${id} holds a time of day without a date, but "${written}" has a date. Write the time alone, as in "${shape.example}".`,
|
|
1246
|
+
);
|
|
1247
|
+
if (parts.date === undefined && shape.date)
|
|
1248
|
+
throw new CastRefused(
|
|
1249
|
+
shape.time
|
|
1250
|
+
? `${id} holds ${shape.description}, but "${written}" has no date. Write the date too, as in "${shape.example}".`
|
|
1251
|
+
: `${id} holds a date, and "${written}" is a time of day. Write a date, as in "${shape.example}".`,
|
|
1252
|
+
);
|
|
1253
|
+
if (parts.time !== undefined && !shape.time)
|
|
1254
|
+
throw new CastRefused(
|
|
1255
|
+
`${id} holds a date without a time of day, but "${written}" has a time. Write the date alone, as in "${shape.example}".`,
|
|
1256
|
+
);
|
|
1257
|
+
if (parts.time === undefined && shape.offset)
|
|
1258
|
+
throw new CastRefused(
|
|
1259
|
+
`${id} holds ${shape.description}, but "${written}" has no time of day. Write the time too, as in "${shape.example}".`,
|
|
1260
|
+
);
|
|
1261
|
+
if (parts.offsetSeconds !== undefined && !shape.offset)
|
|
1262
|
+
throw new CastRefused(
|
|
1263
|
+
`${id} holds no UTC offset, but "${written}" has one. Leave it out, as in "${shape.example}".`,
|
|
1264
|
+
);
|
|
1265
|
+
if (parts.offsetSeconds === undefined && shape.offset)
|
|
1266
|
+
throw new CastRefused(
|
|
1267
|
+
`${id} needs a UTC offset, but "${written}" has none. Add Z for UTC or an offset such as +02:00, as in "${shape.example}".`,
|
|
1268
|
+
);
|
|
1269
|
+
if (parts.fractionDigits > MAX_FRACTION_DIGITS)
|
|
1270
|
+
throw new CastRefused(
|
|
1271
|
+
`"${written}" has ${parts.fractionDigits} digits after the decimal point, but ${id} holds microseconds, so at most ${MAX_FRACTION_DIGITS}. Round it, as in "${shape.example.replace(/(\d{2}:\d{2}:\d{2})/, '$1.123456')}".`,
|
|
1272
|
+
);
|
|
1273
|
+
const { date, time } = parts;
|
|
1274
|
+
if (
|
|
1275
|
+
date !== undefined &&
|
|
1276
|
+
(date.month < 1 ||
|
|
1277
|
+
date.month > 12 ||
|
|
1278
|
+
date.day < 1 ||
|
|
1279
|
+
date.day > daysInMonth(date.year, date.month))
|
|
1280
|
+
)
|
|
1281
|
+
throw new CastRefused(
|
|
1282
|
+
`"${written}" is not a date that exists. Write a real date, as in "${shape.example}".`,
|
|
1283
|
+
);
|
|
1284
|
+
if (time !== undefined && (time.hour > 23 || time.minute > 59 || time.second > 59))
|
|
1285
|
+
throw new CastRefused(
|
|
1286
|
+
`"${written}" is not a time of day that exists: hours run from 00 to 23, and minutes and seconds from 00 to 59. Write one, as in "${shape.example}".`,
|
|
1287
|
+
);
|
|
1288
|
+
const offsetLimit = options.maxOffsetHours ?? 23;
|
|
1289
|
+
if (
|
|
1290
|
+
parts.offsetSeconds !== undefined &&
|
|
1291
|
+
Math.abs(parts.offsetSeconds) >= (offsetLimit + 1) * 3600
|
|
1292
|
+
)
|
|
1293
|
+
throw new CastRefused(
|
|
1294
|
+
`"${written}" has a UTC offset outside -${pad(offsetLimit)}:59 to +${pad(offsetLimit)}:59, which ${id} does not hold. Write a smaller offset, as in "${shape.example}".`,
|
|
1295
|
+
);
|
|
1296
|
+
const value = normalized(parts, options.shape);
|
|
1297
|
+
const { range } = options;
|
|
1298
|
+
if (range !== undefined) {
|
|
1299
|
+
const at = position(value);
|
|
1300
|
+
if (
|
|
1301
|
+
isBefore(at, boundPosition(range.earliest, options.shape)) ||
|
|
1302
|
+
isBefore(boundPosition(range.latest, options.shape), at)
|
|
1303
|
+
)
|
|
1304
|
+
throw new CastRefused(
|
|
1305
|
+
`${id} holds ${shape.plural} from ${range.earliest} to ${range.latest}, and "${written}" is outside them.`,
|
|
1306
|
+
);
|
|
1307
|
+
}
|
|
1308
|
+
return printed(value, options.shape);
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
const INFINITIES: ReadonlySet<string> = new Set(['infinity', '-infinity']);
|
|
1312
|
+
|
|
1313
|
+
function postgresDateTime(
|
|
1314
|
+
options: DateTimeOptions,
|
|
1315
|
+
holdsInfinity: boolean,
|
|
1316
|
+
): (text: string) => string {
|
|
1317
|
+
return (text) =>
|
|
1318
|
+
holdsInfinity && INFINITIES.has(text)
|
|
1319
|
+
? text
|
|
1320
|
+
: dateTimeStoredText(isoYearText(text), options, text);
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
function storedForm(
|
|
1324
|
+
storedText: (text: string) => string,
|
|
1325
|
+
text: string,
|
|
1326
|
+
): { readonly stored: string } | { readonly reason: string } {
|
|
1327
|
+
try {
|
|
1328
|
+
return { stored: storedText(text) };
|
|
1329
|
+
} catch (error) {
|
|
1330
|
+
if (error instanceof CastRefused) return { reason: error.message };
|
|
1331
|
+
throw error;
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
const SECONDS_FRACTION = /:\d{2}\.(\d+)/;
|
|
1336
|
+
const INTERVAL_SECONDS_FRACTION = /\d\.(\d+)S$/;
|
|
1337
|
+
|
|
1338
|
+
function storedTextType(
|
|
1339
|
+
typeId: string,
|
|
1340
|
+
storedText: (text: string) => string,
|
|
1341
|
+
description: string,
|
|
1342
|
+
fraction: RegExp,
|
|
1343
|
+
): Pick<PostgresDataType, 'read' | 'spell'> {
|
|
1344
|
+
return {
|
|
1345
|
+
read: (json, params) => {
|
|
1346
|
+
if (typeof json !== 'string') return refuseJsonValue(typeId, description);
|
|
1347
|
+
const form = storedForm(storedText, json);
|
|
1348
|
+
if ('reason' in form) return refuseJsonValue(typeId, `${description}: ${form.reason}`);
|
|
1349
|
+
const precision = integerParam(params, 'precision') ?? MAX_FRACTION_DIGITS;
|
|
1350
|
+
if (withoutTrailing(fraction.exec(form.stored)?.[1] ?? '', '0').length > precision)
|
|
1351
|
+
return refuseJsonValue(
|
|
1352
|
+
typeId,
|
|
1353
|
+
`a value with at most ${counted(precision, 'fraction digit')} of a second, which precision ${precision} holds without rounding`,
|
|
1354
|
+
);
|
|
1355
|
+
return json;
|
|
1356
|
+
},
|
|
1357
|
+
spell: (json) => {
|
|
1358
|
+
if (typeof json !== 'string') return json;
|
|
1359
|
+
const form = storedForm(storedText, json);
|
|
1360
|
+
return 'stored' in form ? form.stored : json;
|
|
1361
|
+
},
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
type ParamRule = (value: Json | undefined) => boolean;
|
|
1366
|
+
|
|
1367
|
+
const optionalInteger =
|
|
1368
|
+
(min: number, max: number): ParamRule =>
|
|
1369
|
+
(value) =>
|
|
1370
|
+
value === undefined ||
|
|
1371
|
+
(typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max);
|
|
1372
|
+
|
|
1373
|
+
interface PostgresDataType {
|
|
1374
|
+
readonly params?: Readonly<Record<string, ParamRule>>;
|
|
1375
|
+
readonly read: (json: Json, params: Params) => Json;
|
|
1376
|
+
readonly spell?: (json: Json, params: Params) => Json;
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
const NUMERIC_PARAMS = {
|
|
1380
|
+
precision: optionalInteger(1, 1000),
|
|
1381
|
+
scale: optionalInteger(-1000, 1000),
|
|
1382
|
+
};
|
|
1383
|
+
const CHARACTER_LENGTH_PARAMS = { length: optionalInteger(1, 10485760) };
|
|
1384
|
+
const BIT_LENGTH_PARAMS = { length: optionalInteger(1, 83886080) };
|
|
1385
|
+
const PRECISION_PARAMS = { precision: optionalInteger(0, 6) };
|
|
1386
|
+
const readString =
|
|
1387
|
+
(typeId: string): PostgresDataType['read'] =>
|
|
1388
|
+
(json) =>
|
|
1389
|
+
readJsonString(typeId, json);
|
|
1390
|
+
const anyJson: PostgresDataType['read'] = (json) => json;
|
|
1391
|
+
|
|
1392
|
+
const requiredInteger =
|
|
1393
|
+
(min: number, max: number): ParamRule =>
|
|
1394
|
+
(value) =>
|
|
1395
|
+
typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;
|
|
1396
|
+
|
|
1397
|
+
const HEX_TEXT = /^(?:[0-9A-Fa-f]{2})*$/;
|
|
1398
|
+
const EWKB_FLAG_Z = 0x80000000;
|
|
1399
|
+
const EWKB_FLAG_M = 0x40000000;
|
|
1400
|
+
const EWKB_FLAG_SRID = 0x20000000;
|
|
1401
|
+
const EWKB_TYPE_MASK = 0x1fffffff;
|
|
1402
|
+
const EWKB_POINT = 1;
|
|
1403
|
+
const EWKB_LINESTRING = 2;
|
|
1404
|
+
const EWKB_POLYGON = 3;
|
|
1405
|
+
const EWKB_MULTI_PARTS: ReadonlyMap<number, number> = new Map([
|
|
1406
|
+
[4, EWKB_POINT],
|
|
1407
|
+
[5, EWKB_LINESTRING],
|
|
1408
|
+
[6, EWKB_POLYGON],
|
|
1409
|
+
]);
|
|
1410
|
+
|
|
1411
|
+
class NotEwkb extends Error {}
|
|
1412
|
+
|
|
1413
|
+
interface EwkbGeometry {
|
|
1414
|
+
readonly srid: number | undefined;
|
|
1415
|
+
/** The geometry as the upper-case little-endian HEXEWKB PostGIS prints, or undefined when a coordinate is not finite. */
|
|
1416
|
+
readonly printed: string | undefined;
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
/** Reads HEXEWKB in either case and byte order, as `postgis/geometry` of 8.0.0-rc.19 does: points, line strings, polygons and their multi forms, without Z or M coordinates. */
|
|
1420
|
+
function readEwkb(hex: string): EwkbGeometry {
|
|
1421
|
+
const bytes = Buffer.from(hex, 'hex');
|
|
1422
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1423
|
+
const out: number[] = [];
|
|
1424
|
+
let offset = 0;
|
|
1425
|
+
let finite = true;
|
|
1426
|
+
const take = (size: number): number => {
|
|
1427
|
+
if (offset + size > view.byteLength) throw new NotEwkb();
|
|
1428
|
+
const at = offset;
|
|
1429
|
+
offset += size;
|
|
1430
|
+
return at;
|
|
1431
|
+
};
|
|
1432
|
+
const writeUint32 = (value: number): void => {
|
|
1433
|
+
const buffer = Buffer.alloc(4);
|
|
1434
|
+
buffer.writeUInt32LE(value >>> 0);
|
|
1435
|
+
out.push(...buffer);
|
|
1436
|
+
};
|
|
1437
|
+
const header = (top: boolean): { type: number; little: boolean; srid: number | undefined } => {
|
|
1438
|
+
const order = view.getUint8(take(1));
|
|
1439
|
+
if (order !== 0 && order !== 1) throw new NotEwkb();
|
|
1440
|
+
const little = order === 1;
|
|
1441
|
+
const code = view.getUint32(take(4), little) >>> 0;
|
|
1442
|
+
if ((code & EWKB_FLAG_Z) !== 0 || (code & EWKB_FLAG_M) !== 0) throw new NotEwkb();
|
|
1443
|
+
const type = code & EWKB_TYPE_MASK;
|
|
1444
|
+
const srid = (code & EWKB_FLAG_SRID) !== 0 ? view.getUint32(take(4), little) >>> 0 : undefined;
|
|
1445
|
+
out.push(1);
|
|
1446
|
+
writeUint32(top && srid !== undefined ? type | EWKB_FLAG_SRID : type);
|
|
1447
|
+
if (top && srid !== undefined) writeUint32(srid);
|
|
1448
|
+
return { type, little, srid };
|
|
1449
|
+
};
|
|
1450
|
+
const count = (little: boolean): number => {
|
|
1451
|
+
const value = view.getUint32(take(4), little) >>> 0;
|
|
1452
|
+
writeUint32(value);
|
|
1453
|
+
return value;
|
|
1454
|
+
};
|
|
1455
|
+
const positions = (amount: number, little: boolean): void => {
|
|
1456
|
+
for (let index = 0; index < amount * 2; index++) {
|
|
1457
|
+
const value = view.getFloat64(take(8), little);
|
|
1458
|
+
if (!Number.isFinite(value)) finite = false;
|
|
1459
|
+
const buffer = Buffer.alloc(8);
|
|
1460
|
+
buffer.writeDoubleLE(value);
|
|
1461
|
+
out.push(...buffer);
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
1464
|
+
const body = (type: number, little: boolean): void => {
|
|
1465
|
+
if (type === EWKB_POINT) positions(1, little);
|
|
1466
|
+
else if (type === EWKB_LINESTRING) positions(count(little), little);
|
|
1467
|
+
else if (type === EWKB_POLYGON)
|
|
1468
|
+
for (let ring = count(little); ring > 0; ring--) positions(count(little), little);
|
|
1469
|
+
else throw new NotEwkb();
|
|
1470
|
+
};
|
|
1471
|
+
const top = header(true);
|
|
1472
|
+
const part = EWKB_MULTI_PARTS.get(top.type);
|
|
1473
|
+
if (part === undefined) body(top.type, top.little);
|
|
1474
|
+
else
|
|
1475
|
+
for (let index = count(top.little); index > 0; index--) {
|
|
1476
|
+
const sub = header(false);
|
|
1477
|
+
if (sub.type !== part) throw new NotEwkb();
|
|
1478
|
+
body(sub.type, sub.little);
|
|
1479
|
+
}
|
|
1480
|
+
if (offset !== view.byteLength) throw new NotEwkb();
|
|
1481
|
+
return {
|
|
1482
|
+
srid: top.srid,
|
|
1483
|
+
printed: finite ? Buffer.from(out).toString('hex').toUpperCase() : undefined,
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
function ewkbOf(json: Json): EwkbGeometry | undefined {
|
|
1488
|
+
if (typeof json !== 'string') return undefined;
|
|
1489
|
+
try {
|
|
1490
|
+
return readEwkb(json);
|
|
1491
|
+
} catch (error) {
|
|
1492
|
+
if (error instanceof NotEwkb) return undefined;
|
|
1493
|
+
throw error;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
function readGeometry(json: Json, params: Params): Json {
|
|
1498
|
+
readJsonMatching('postgis/geometry', json, HEX_TEXT, 'a HEXEWKB string');
|
|
1499
|
+
const srid = integerParam(params, 'srid');
|
|
1500
|
+
const geometry = ewkbOf(json);
|
|
1501
|
+
if (geometry === undefined || (srid !== undefined && geometry.srid !== srid))
|
|
1502
|
+
return refuseJsonValue(
|
|
1503
|
+
'postgis/geometry',
|
|
1504
|
+
srid !== undefined ? `a HEXEWKB string of a geometry with SRID ${srid}` : 'a HEXEWKB string',
|
|
1505
|
+
);
|
|
1506
|
+
return json;
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
function spellGeometry(json: Json): Json {
|
|
1510
|
+
const geometry = ewkbOf(json);
|
|
1511
|
+
if (geometry === undefined) return json;
|
|
1512
|
+
if (geometry.printed === undefined)
|
|
1513
|
+
throw new NotAValue('Geometry encode: coordinates must be finite numbers');
|
|
1514
|
+
return geometry.printed;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
/** The text PostgreSQL prints for `value` stored as a `real`: the shortest decimal that reads back as the same single-precision number. */
|
|
1518
|
+
function realText(value: number): string {
|
|
1519
|
+
const single = Math.fround(value);
|
|
1520
|
+
for (let digits = 1; digits <= 9; digits++) {
|
|
1521
|
+
const text = String(Number(single.toPrecision(digits)));
|
|
1522
|
+
if (Math.fround(Number(text)) === single) return text;
|
|
1523
|
+
}
|
|
1524
|
+
return String(single);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
function readVector(json: Json, params: Params): Json {
|
|
1528
|
+
const length = integerParam(params, 'length');
|
|
1529
|
+
const expected =
|
|
1530
|
+
length === undefined
|
|
1531
|
+
? 'an array of finite numbers'
|
|
1532
|
+
: `an array of ${counted(length, 'finite number')}`;
|
|
1533
|
+
if (!Array.isArray(json) || (length !== undefined && json.length !== length))
|
|
1534
|
+
return refuseJsonValue('pgvector/vector', expected);
|
|
1535
|
+
for (const element of json)
|
|
1536
|
+
if (typeof element !== 'number' || !Number.isFinite(element))
|
|
1537
|
+
return refuseJsonValue('pgvector/vector', expected);
|
|
1538
|
+
for (const [index, element] of json.entries()) {
|
|
1539
|
+
if (typeof element !== 'number') continue;
|
|
1540
|
+
const refuse = (why: string) =>
|
|
1541
|
+
refuseJsonValue(
|
|
1542
|
+
'pgvector/vector',
|
|
1543
|
+
`an array of numbers real holds exactly; element ${index + 1}, ${element}, ${why}`,
|
|
1544
|
+
);
|
|
1545
|
+
if (!Number.isFinite(Math.fround(element)))
|
|
1546
|
+
return refuse('is outside the range real holds, which PostgreSQL refuses');
|
|
1547
|
+
const stored = realText(element);
|
|
1548
|
+
if (Number(stored) !== element) return refuse(`would be stored as ${stored}`);
|
|
1549
|
+
}
|
|
1550
|
+
return json;
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
const POSTGRES_DATA_TYPES: ReadonlyMap<string, PostgresDataType> = new Map<
|
|
1554
|
+
string,
|
|
1555
|
+
PostgresDataType
|
|
1556
|
+
>([
|
|
1557
|
+
['pg/text', { read: readString('pg/text') }],
|
|
1558
|
+
['pg/text-array', { read: readTextArray }],
|
|
1559
|
+
[
|
|
1560
|
+
'pg/enum',
|
|
1561
|
+
{
|
|
1562
|
+
params: { typeName: (value) => typeof value === 'string' && value.length > 0 },
|
|
1563
|
+
read: readString('pg/enum'),
|
|
1564
|
+
},
|
|
1565
|
+
],
|
|
1566
|
+
['pg/int2', { read: (json) => readJsonInteger('pg/int2', json, -32768, 32767) }],
|
|
1567
|
+
[
|
|
1568
|
+
'pg/bool',
|
|
1569
|
+
{
|
|
1570
|
+
read: (json) => (typeof json === 'boolean' ? json : refuseJsonValue('pg/bool', 'a boolean')),
|
|
1571
|
+
},
|
|
1572
|
+
],
|
|
1573
|
+
['pg/json', { read: anyJson }],
|
|
1574
|
+
['pg/tsquery', { read: readString('pg/tsquery') }],
|
|
1575
|
+
['pg/int4', { read: (json) => readJsonInteger('pg/int4', json, -(2 ** 31), 2 ** 31 - 1) }],
|
|
1576
|
+
['pg/int8', { read: readInt8 }],
|
|
1577
|
+
['pg/numeric', { params: NUMERIC_PARAMS, read: readNumeric, spell: spellNumeric }],
|
|
1578
|
+
['pg/float4', { read: readFloat4 }],
|
|
1579
|
+
[
|
|
1580
|
+
'pg/float8',
|
|
1581
|
+
{
|
|
1582
|
+
read: (json) => {
|
|
1583
|
+
readJsonFloat('pg/float8', json);
|
|
1584
|
+
return json;
|
|
1585
|
+
},
|
|
1586
|
+
},
|
|
1587
|
+
],
|
|
1588
|
+
['pg/jsonb', { read: anyJson }],
|
|
1589
|
+
['pg/char', { params: CHARACTER_LENGTH_PARAMS, read: readCharacter, spell: spellCharacter }],
|
|
1590
|
+
['pg/varchar', { params: CHARACTER_LENGTH_PARAMS, read: readCharacterVarying }],
|
|
1591
|
+
[
|
|
1592
|
+
'pg/uuid',
|
|
1593
|
+
{
|
|
1594
|
+
read: (json) =>
|
|
1595
|
+
typeof json === 'string' && storedUuid(json) !== undefined
|
|
1596
|
+
? json
|
|
1597
|
+
: refuseJsonValue(
|
|
1598
|
+
'pg/uuid',
|
|
1599
|
+
'a UUID in a spelling PostgreSQL reads: 32 hexadecimal digits in either case, with or without a hyphen after any group of four, optionally in braces',
|
|
1600
|
+
),
|
|
1601
|
+
spell: (json) => (typeof json === 'string' ? (storedUuid(json) ?? json) : json),
|
|
1602
|
+
},
|
|
1603
|
+
],
|
|
1604
|
+
[
|
|
1605
|
+
'pg/inet',
|
|
1606
|
+
{
|
|
1607
|
+
read: (json) =>
|
|
1608
|
+
typeof json === 'string' && storedInet(json) !== undefined
|
|
1609
|
+
? json
|
|
1610
|
+
: refuseJsonValue(
|
|
1611
|
+
'pg/inet',
|
|
1612
|
+
'an IP address or network in a spelling PostgreSQL reads, as in 10.0.0.1 or 2001:db8::/32',
|
|
1613
|
+
),
|
|
1614
|
+
spell: (json) => (typeof json === 'string' ? (storedInet(json) ?? json) : json),
|
|
1615
|
+
},
|
|
1616
|
+
],
|
|
1617
|
+
['pg/bit', { params: BIT_LENGTH_PARAMS, read: readBit }],
|
|
1618
|
+
['pg/varbit', { params: BIT_LENGTH_PARAMS, read: readBitVarying }],
|
|
1619
|
+
[
|
|
1620
|
+
'pg/timetz',
|
|
1621
|
+
{
|
|
1622
|
+
params: PRECISION_PARAMS,
|
|
1623
|
+
...storedTextType(
|
|
1624
|
+
'pg/timetz',
|
|
1625
|
+
postgresDateTime(
|
|
1626
|
+
{ shape: 'timeWithOffset', typeId: 'pg/timetz', maxOffsetHours: 15 },
|
|
1627
|
+
false,
|
|
1628
|
+
),
|
|
1629
|
+
'a time of day with its UTC offset, as in "12:34:56+02:00" or "12:34:56Z"',
|
|
1630
|
+
SECONDS_FRACTION,
|
|
1631
|
+
),
|
|
1632
|
+
},
|
|
1633
|
+
],
|
|
1634
|
+
[
|
|
1635
|
+
'pg/interval',
|
|
1636
|
+
{
|
|
1637
|
+
params: PRECISION_PARAMS,
|
|
1638
|
+
...storedTextType(
|
|
1639
|
+
'pg/interval',
|
|
1640
|
+
intervalStoredText,
|
|
1641
|
+
'an ISO 8601 duration, as in "P1Y2M3DT4H5M6.5S"',
|
|
1642
|
+
INTERVAL_SECONDS_FRACTION,
|
|
1643
|
+
),
|
|
1644
|
+
},
|
|
1645
|
+
],
|
|
1646
|
+
[
|
|
1647
|
+
'pg/bytea',
|
|
1648
|
+
{
|
|
1649
|
+
read: (json) => readJsonMatching('pg/bytea', json, BASE64_TEXT, 'a base64 string'),
|
|
1650
|
+
spell: spellBytea,
|
|
1651
|
+
},
|
|
1652
|
+
],
|
|
1653
|
+
[
|
|
1654
|
+
'pg/date',
|
|
1655
|
+
storedTextType(
|
|
1656
|
+
'pg/date',
|
|
1657
|
+
postgresDateTime(
|
|
1658
|
+
{
|
|
1659
|
+
shape: 'date',
|
|
1660
|
+
typeId: 'pg/date',
|
|
1661
|
+
range: { earliest: '-004713-11-24', latest: '+275760-09-13' },
|
|
1662
|
+
},
|
|
1663
|
+
true,
|
|
1664
|
+
),
|
|
1665
|
+
'a date, as in "2024-01-01", or infinity or -infinity',
|
|
1666
|
+
SECONDS_FRACTION,
|
|
1667
|
+
),
|
|
1668
|
+
],
|
|
1669
|
+
[
|
|
1670
|
+
'pg/time',
|
|
1671
|
+
{
|
|
1672
|
+
params: PRECISION_PARAMS,
|
|
1673
|
+
...storedTextType(
|
|
1674
|
+
'pg/time',
|
|
1675
|
+
postgresDateTime({ shape: 'time', typeId: 'pg/time' }, false),
|
|
1676
|
+
'a time of day, as in "12:34:56"',
|
|
1677
|
+
SECONDS_FRACTION,
|
|
1678
|
+
),
|
|
1679
|
+
},
|
|
1680
|
+
],
|
|
1681
|
+
[
|
|
1682
|
+
'pg/timestamp',
|
|
1683
|
+
{
|
|
1684
|
+
params: PRECISION_PARAMS,
|
|
1685
|
+
...storedTextType(
|
|
1686
|
+
'pg/timestamp',
|
|
1687
|
+
postgresDateTime(
|
|
1688
|
+
{
|
|
1689
|
+
shape: 'dateTime',
|
|
1690
|
+
typeId: 'pg/timestamp',
|
|
1691
|
+
range: { earliest: '-004713-11-24T00:00:00', latest: '+275760-09-13T23:59:59.999999' },
|
|
1692
|
+
},
|
|
1693
|
+
true,
|
|
1694
|
+
),
|
|
1695
|
+
'a date and time of day, as in "2024-01-01T12:34:56", or infinity or -infinity',
|
|
1696
|
+
SECONDS_FRACTION,
|
|
1697
|
+
),
|
|
1698
|
+
},
|
|
1699
|
+
],
|
|
1700
|
+
[
|
|
1701
|
+
'pg/timestamptz',
|
|
1702
|
+
{
|
|
1703
|
+
params: PRECISION_PARAMS,
|
|
1704
|
+
...storedTextType(
|
|
1705
|
+
'pg/timestamptz',
|
|
1706
|
+
postgresDateTime(
|
|
1707
|
+
{
|
|
1708
|
+
shape: 'instant',
|
|
1709
|
+
typeId: 'pg/timestamptz',
|
|
1710
|
+
range: { earliest: '-004713-11-24T00:00:00Z', latest: '+275760-09-13T00:00:00Z' },
|
|
1711
|
+
},
|
|
1712
|
+
true,
|
|
1713
|
+
),
|
|
1714
|
+
'an instant in UTC, as in "2024-01-01T00:00:00Z", or infinity or -infinity',
|
|
1715
|
+
SECONDS_FRACTION,
|
|
1716
|
+
),
|
|
1717
|
+
},
|
|
1718
|
+
],
|
|
1719
|
+
[
|
|
1720
|
+
'postgis/geometry',
|
|
1721
|
+
{
|
|
1722
|
+
params: { srid: optionalInteger(1, Number.POSITIVE_INFINITY) },
|
|
1723
|
+
read: readGeometry,
|
|
1724
|
+
spell: spellGeometry,
|
|
1725
|
+
},
|
|
1726
|
+
],
|
|
1727
|
+
['pgvector/vector', { params: { length: requiredInteger(1, 16000) }, read: readVector }],
|
|
1728
|
+
]);
|
|
1729
|
+
|
|
1730
|
+
function resolvedTypeParams(column: JsonRecord, namedTypes: Json | undefined): Json | undefined {
|
|
1731
|
+
const typeRef = column['typeRef'];
|
|
1732
|
+
const named =
|
|
1733
|
+
typeof typeRef === 'string' && isRecord(namedTypes) ? namedTypes[typeRef] : undefined;
|
|
1734
|
+
const typeParams = column['typeParams'] ?? (isRecord(named) ? named['typeParams'] : undefined);
|
|
1735
|
+
return isRecord(typeParams) && Object.keys(typeParams).length > 0 ? typeParams : undefined;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/** The parameters of the column that its data type declares, or undefined when the type refuses them. */
|
|
1739
|
+
function declaredParams(type: PostgresDataType, typeParams: Json | undefined): Params | undefined {
|
|
1740
|
+
const params: Record<string, Json> = {};
|
|
1741
|
+
for (const [name, accepts] of Object.entries(type.params ?? {})) {
|
|
1742
|
+
const value = isRecord(typeParams) ? typeParams[name] : undefined;
|
|
1743
|
+
if (!accepts(value)) return undefined;
|
|
1744
|
+
if (value !== undefined) params[name] = value;
|
|
1745
|
+
}
|
|
1746
|
+
if (params['scale'] !== undefined && params['precision'] === undefined) return undefined;
|
|
1747
|
+
return params;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
interface ColumnType {
|
|
1751
|
+
readonly id: string;
|
|
1752
|
+
readonly type: PostgresDataType;
|
|
1753
|
+
readonly params: Params;
|
|
1754
|
+
readonly list: boolean;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/** The column's data type and parameters, or undefined when this release does not register the type or refuses the parameters, and so does not read the default. */
|
|
1758
|
+
function columnType(column: JsonRecord, namedTypes: Json | undefined): ColumnType | undefined {
|
|
1759
|
+
const id = column['dataType'];
|
|
1760
|
+
const type = typeof id === 'string' ? POSTGRES_DATA_TYPES.get(id) : undefined;
|
|
1761
|
+
if (typeof id !== 'string' || type === undefined) return undefined;
|
|
1762
|
+
const params = declaredParams(type, resolvedTypeParams(column, namedTypes));
|
|
1763
|
+
if (params === undefined) return undefined;
|
|
1764
|
+
const many = column['many'];
|
|
1765
|
+
return { id, type, params, list: many !== undefined && many !== false };
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
/** A literal default value in the contract form this release stores. */
|
|
1769
|
+
function contractFormOfDefault(value: Json, { type, params }: ColumnType): DefaultForm {
|
|
1770
|
+
let stored: Json;
|
|
1771
|
+
try {
|
|
1772
|
+
const read = type.read(value, params);
|
|
1773
|
+
stored = type.spell === undefined ? read : type.spell(read, params);
|
|
1774
|
+
} catch (error) {
|
|
1775
|
+
if (error instanceof NotAValue) return { kind: 'notAValue', reason: error.message };
|
|
1776
|
+
throw error;
|
|
1777
|
+
}
|
|
1778
|
+
return canonicalizeJson(stored) === canonicalizeJson(value)
|
|
1779
|
+
? { kind: 'unchanged' }
|
|
1780
|
+
: { kind: 'rewritten', value: stored };
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
type StoredDefault =
|
|
1784
|
+
| { readonly kind: 'stored'; readonly value: Json }
|
|
1785
|
+
| { readonly kind: 'refused'; readonly reason: string };
|
|
1786
|
+
|
|
1787
|
+
/** A column's default in the contract form this release stores, element by element on a list column, or why this release refuses it. */
|
|
1788
|
+
function storedDefault(value: Json, columnType: ColumnType): StoredDefault {
|
|
1789
|
+
if (value === null) return { kind: 'stored', value };
|
|
1790
|
+
if (columnType.list && !Array.isArray(value))
|
|
1791
|
+
return {
|
|
1792
|
+
kind: 'refused',
|
|
1793
|
+
reason: `the default ${JSON.stringify(value)} is not a list, and the column holds a list of ${columnType.id}`,
|
|
1794
|
+
};
|
|
1795
|
+
const values = columnType.list && Array.isArray(value) ? value : [value];
|
|
1796
|
+
const stored: Json[] = [];
|
|
1797
|
+
for (const element of values) {
|
|
1798
|
+
const form = element === null ? undefined : contractFormOfDefault(element, columnType);
|
|
1799
|
+
if (form?.kind === 'notAValue')
|
|
1800
|
+
return {
|
|
1801
|
+
kind: 'refused',
|
|
1802
|
+
reason: `the default ${JSON.stringify(element)} is not a value of ${columnType.id} (${form.reason})`,
|
|
1803
|
+
};
|
|
1804
|
+
stored.push(form?.kind === 'rewritten' ? form.value : element);
|
|
1805
|
+
}
|
|
1806
|
+
return { kind: 'stored', value: columnType.list ? stored : (stored[0] ?? null) };
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
/** The scalar values that changed between two defaults, pairing list elements by position, for the literal types of `contract.d.ts`. */
|
|
1810
|
+
function defaultRewrites(from: Json, to: Json): DefaultRewrite[] {
|
|
1811
|
+
const pairs: [Json, Json][] =
|
|
1812
|
+
Array.isArray(from) && Array.isArray(to)
|
|
1813
|
+
? from.length === to.length
|
|
1814
|
+
? from.map((element, index) => [element, to[index] ?? null])
|
|
1815
|
+
: []
|
|
1816
|
+
: [[from, to]];
|
|
1817
|
+
return pairs.flatMap(([a, b]) =>
|
|
1818
|
+
(typeof a === 'string' && typeof b === 'string') ||
|
|
1819
|
+
(typeof a === 'number' && typeof b === 'number')
|
|
1820
|
+
? a === b
|
|
1821
|
+
? []
|
|
1822
|
+
: [{ from: a, to: b }]
|
|
1823
|
+
: [],
|
|
1824
|
+
);
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
/** How `--default` names a column: `<namespace>.<table>.<column>`. */
|
|
1828
|
+
function defaultKey(namespaceId: string, tableName: string, columnName: string): string {
|
|
1829
|
+
return `${namespaceId}.${tableName}.${columnName}`;
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
interface ColumnEntry {
|
|
1833
|
+
readonly namespaceId: string;
|
|
1834
|
+
readonly tableName: string;
|
|
1835
|
+
readonly columnName: string;
|
|
1836
|
+
readonly column: JsonRecord;
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
function columnsOf(contract: JsonRecord): ColumnEntry[] {
|
|
1840
|
+
const storage = contract['storage'];
|
|
1841
|
+
const namespaces = isRecord(storage) ? storage['namespaces'] : undefined;
|
|
1842
|
+
return Object.entries(isRecord(namespaces) ? namespaces : {}).flatMap(
|
|
1843
|
+
([namespaceId, namespace]) => {
|
|
1844
|
+
const entries = isRecord(namespace) ? namespace['entries'] : undefined;
|
|
1845
|
+
const tables = isRecord(entries) ? entries['table'] : undefined;
|
|
1846
|
+
return Object.entries(isRecord(tables) ? tables : {}).flatMap(([tableName, table]) => {
|
|
1847
|
+
const columns = isRecord(table) ? table['columns'] : undefined;
|
|
1848
|
+
return Object.entries(isRecord(columns) ? columns : {}).flatMap(([columnName, column]) =>
|
|
1849
|
+
isRecord(column) ? [{ namespaceId, tableName, columnName, column }] : [],
|
|
1850
|
+
);
|
|
1851
|
+
});
|
|
1852
|
+
},
|
|
1853
|
+
);
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
/** Mutates `copy`: each literal default in the contract form this release stores, element by element on a list column. A default this release refuses takes the value given for its column with `--default`, and each column whose replacement was taken is added to `used`. */
|
|
1857
|
+
function rewriteDefaults(
|
|
1858
|
+
copy: JsonRecord,
|
|
1859
|
+
replacements: ReadonlyMap<string, Json>,
|
|
1860
|
+
used: Set<string>,
|
|
1861
|
+
): {
|
|
1862
|
+
readonly defaults: Map<string, DefaultRewrite[]>;
|
|
1863
|
+
readonly notValues: string[];
|
|
1864
|
+
} {
|
|
1865
|
+
const defaults = new Map<string, DefaultRewrite[]>();
|
|
1866
|
+
const notValues: string[] = [];
|
|
1867
|
+
const storage = copy['storage'];
|
|
1868
|
+
const namedTypes = isRecord(storage) ? storage['types'] : undefined;
|
|
1869
|
+
for (const { namespaceId, tableName, columnName, column } of columnsOf(copy)) {
|
|
1870
|
+
const columnDefault = column['default'];
|
|
1871
|
+
if (!isRecord(columnDefault) || columnDefault['kind'] !== 'literal') continue;
|
|
1872
|
+
const original = columnDefault['value'];
|
|
1873
|
+
const type = columnType(column, namedTypes);
|
|
1874
|
+
if (original === undefined || type === undefined) continue;
|
|
1875
|
+
const place = `namespace ${namespaceId}, table ${tableName}, column ${columnName}`;
|
|
1876
|
+
const key = defaultKey(namespaceId, tableName, columnName);
|
|
1877
|
+
let stored = storedDefault(original, type);
|
|
1878
|
+
if (stored.kind === 'refused') {
|
|
1879
|
+
const replacement = replacements.get(key);
|
|
1880
|
+
if (replacement === undefined) {
|
|
1881
|
+
notValues.push(
|
|
1882
|
+
`${place}: ${stored.reason}; choose the value the database stores and run the script again with --default '${key}=<that value as JSON>'`,
|
|
1883
|
+
);
|
|
1884
|
+
continue;
|
|
1885
|
+
}
|
|
1886
|
+
used.add(key);
|
|
1887
|
+
stored = storedDefault(replacement, type);
|
|
1888
|
+
if (stored.kind === 'refused') {
|
|
1889
|
+
notValues.push(`${place}: --default ${key}: ${stored.reason}`);
|
|
1890
|
+
continue;
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
if (canonicalizeJson(stored.value) === canonicalizeJson(original)) continue;
|
|
1894
|
+
columnDefault['value'] = stored.value;
|
|
1895
|
+
defaults.set(
|
|
1896
|
+
listKey(namespaceId, tableName, columnName),
|
|
1897
|
+
defaultRewrites(original, stored.value),
|
|
1898
|
+
);
|
|
1899
|
+
}
|
|
1900
|
+
return { defaults, notValues };
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
function allowNullElements(holder: JsonRecord): void {
|
|
1904
|
+
const many = holder['many'];
|
|
1905
|
+
if (isRecord(many)) holder['many'] = { ...many, elementNullable: true };
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
/** Mutates `copy`: the domain fields that map a column whose element check was waived. */
|
|
1909
|
+
function fieldsMappingColumns(copy: JsonRecord, columns: ReadonlySet<string>): Set<string> {
|
|
1910
|
+
const fields = new Set<string>();
|
|
1911
|
+
const domain = copy['domain'];
|
|
1912
|
+
const namespaces = isRecord(domain) ? domain['namespaces'] : undefined;
|
|
1913
|
+
for (const [namespaceId, namespace] of isRecord(namespaces) ? Object.entries(namespaces) : []) {
|
|
1914
|
+
const models = isRecord(namespace) ? namespace['models'] : undefined;
|
|
1915
|
+
for (const [modelName, model] of isRecord(models) ? Object.entries(models) : []) {
|
|
1916
|
+
if (!isRecord(model)) continue;
|
|
1917
|
+
const storage = model['storage'];
|
|
1918
|
+
const modelFields = model['fields'];
|
|
1919
|
+
if (!isRecord(storage) || !isRecord(modelFields)) continue;
|
|
1920
|
+
const table = storage['table'];
|
|
1921
|
+
const tableNamespace =
|
|
1922
|
+
typeof storage['namespaceId'] === 'string' ? storage['namespaceId'] : namespaceId;
|
|
1923
|
+
const mapped = storage['fields'];
|
|
1924
|
+
for (const [fieldName, mapping] of isRecord(mapped) ? Object.entries(mapped) : []) {
|
|
1925
|
+
const column = isRecord(mapping) ? mapping['column'] : undefined;
|
|
1926
|
+
const field = modelFields[fieldName];
|
|
1927
|
+
if (typeof table !== 'string' || typeof column !== 'string' || !isRecord(field)) continue;
|
|
1928
|
+
if (!columns.has(listKey(tableNamespace, table, column))) continue;
|
|
1929
|
+
allowNullElements(field);
|
|
1930
|
+
fields.add(listKey(namespaceId, modelName, fieldName));
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
return fields;
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
/** The contract with the key removed from each column, the lists whose element check it waived made element-nullable, and each default in the contract form this release stores. */
|
|
1938
|
+
function rewriteContract(
|
|
1939
|
+
contract: JsonRecord,
|
|
1940
|
+
replacements: ReadonlyMap<string, Json>,
|
|
1941
|
+
used: Set<string>,
|
|
1942
|
+
): Rewrite {
|
|
1943
|
+
const copy = parseJson(JSON.stringify(contract));
|
|
1944
|
+
if (!isRecord(copy))
|
|
1945
|
+
return {
|
|
1946
|
+
contract,
|
|
1947
|
+
changed: false,
|
|
1948
|
+
columns: new Set(),
|
|
1949
|
+
fields: new Set(),
|
|
1950
|
+
defaults: new Map(),
|
|
1951
|
+
notValues: [],
|
|
1952
|
+
};
|
|
1953
|
+
let changed = false;
|
|
1954
|
+
const columns = new Set<string>();
|
|
1955
|
+
const storage = copy['storage'];
|
|
1956
|
+
const namespaces = isRecord(storage) ? storage['namespaces'] : undefined;
|
|
1957
|
+
for (const [namespaceId, namespace] of isRecord(namespaces) ? Object.entries(namespaces) : []) {
|
|
1958
|
+
const entries = isRecord(namespace) ? namespace['entries'] : undefined;
|
|
1959
|
+
const tables = isRecord(entries) ? entries['table'] : undefined;
|
|
1960
|
+
for (const [tableName, table] of isRecord(tables) ? Object.entries(tables) : []) {
|
|
1961
|
+
const tableColumns = isRecord(table) ? table['columns'] : undefined;
|
|
1962
|
+
for (const [columnName, column] of isRecord(tableColumns)
|
|
1963
|
+
? Object.entries(tableColumns)
|
|
1964
|
+
: []) {
|
|
1965
|
+
if (!isRecord(column) || !Object.hasOwn(column, REMOVED_KEY)) continue;
|
|
1966
|
+
const kinds = column[REMOVED_KEY];
|
|
1967
|
+
delete column[REMOVED_KEY];
|
|
1968
|
+
changed = true;
|
|
1969
|
+
if (Array.isArray(kinds) && kinds.includes(ELEMENT_KIND) && isRecord(column['many'])) {
|
|
1970
|
+
allowNullElements(column);
|
|
1971
|
+
columns.add(listKey(namespaceId, tableName, columnName));
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
const { defaults, notValues } =
|
|
1977
|
+
contract['target'] === 'postgres'
|
|
1978
|
+
? rewriteDefaults(copy, replacements, used)
|
|
1979
|
+
: { defaults: new Map<string, DefaultRewrite[]>(), notValues: [] };
|
|
1980
|
+
return {
|
|
1981
|
+
contract: copy,
|
|
1982
|
+
changed: changed || defaults.size > 0,
|
|
1983
|
+
columns,
|
|
1984
|
+
fields: fieldsMappingColumns(copy, columns),
|
|
1985
|
+
defaults,
|
|
1986
|
+
notValues,
|
|
1987
|
+
};
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
function withStorageHash(contract: JsonRecord, hash: string): JsonRecord {
|
|
1991
|
+
const storage = contract['storage'];
|
|
1992
|
+
if (!isRecord(storage) || typeof storage['storageHash'] !== 'string') return contract;
|
|
1993
|
+
return { ...contract, storage: { ...storage, storageHash: hash } };
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
/** The contract written the way the file held it: a snapshot's canonical line, or indented JSON. */
|
|
1997
|
+
function writtenForm(contract: JsonRecord, original: JsonRecord, text: string): string {
|
|
1998
|
+
const newline = text.endsWith('\n') ? '\n' : '';
|
|
1999
|
+
if (text === `${canonicalizeJson(original)}${newline}`)
|
|
2000
|
+
return `${canonicalizeJson(contract)}${newline}`;
|
|
2001
|
+
return `${JSON.stringify(contract, null, 2)}${newline}`;
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
interface Block {
|
|
2005
|
+
readonly start: number;
|
|
2006
|
+
end: number;
|
|
2007
|
+
readonly label: string;
|
|
2008
|
+
readonly parent: Block | undefined;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
function scanBlocks(text: string): Block[] {
|
|
2012
|
+
const blocks: Block[] = [];
|
|
2013
|
+
const open: Block[] = [];
|
|
2014
|
+
let quote: string | undefined;
|
|
2015
|
+
for (let index = 0; index < text.length; index++) {
|
|
2016
|
+
const char = text[index];
|
|
2017
|
+
if (quote !== undefined) {
|
|
2018
|
+
if (char === '\\') index++;
|
|
2019
|
+
else if (char === quote) quote = undefined;
|
|
2020
|
+
continue;
|
|
2021
|
+
}
|
|
2022
|
+
if (char === "'" || char === '"' || char === '`') {
|
|
2023
|
+
quote = char;
|
|
2024
|
+
continue;
|
|
2025
|
+
}
|
|
2026
|
+
if (char === '{') {
|
|
2027
|
+
const before = text.slice(Math.max(0, index - 200), index);
|
|
2028
|
+
const key =
|
|
2029
|
+
/(?:readonly\s+)?([\p{ID_Start}_$][\p{ID_Continue}$]*|'[^']*'|"[^"]*")\s*\??\s*:\s*$/u.exec(
|
|
2030
|
+
before,
|
|
2031
|
+
) ?? /\b(?:type|namespace)\s+([\p{ID_Start}_$][\p{ID_Continue}$]*)\s*=?\s*$/u.exec(before);
|
|
2032
|
+
const block: Block = {
|
|
2033
|
+
start: index,
|
|
2034
|
+
end: text.length,
|
|
2035
|
+
label: key?.[1]?.replace(/^['"]|['"]$/g, '') ?? '',
|
|
2036
|
+
parent: open.at(-1),
|
|
2037
|
+
};
|
|
2038
|
+
open.push(block);
|
|
2039
|
+
blocks.push(block);
|
|
2040
|
+
} else if (char === '}') {
|
|
2041
|
+
const block = open.pop();
|
|
2042
|
+
if (block !== undefined) block.end = index;
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
return blocks;
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
function innermostBlock(blocks: readonly Block[], position: number): Block | undefined {
|
|
2049
|
+
let found: Block | undefined;
|
|
2050
|
+
for (const block of blocks)
|
|
2051
|
+
if (
|
|
2052
|
+
block.start < position &&
|
|
2053
|
+
position < block.end &&
|
|
2054
|
+
(found === undefined || block.start > found.start)
|
|
2055
|
+
)
|
|
2056
|
+
found = block;
|
|
2057
|
+
return found;
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
/** The key of a storage column block (`namespaces.<ns>.entries.table.<table>.columns.<column>`). */
|
|
2061
|
+
function columnBlockKey(block: Block): string | undefined {
|
|
2062
|
+
const table = block.parent?.parent;
|
|
2063
|
+
const namespace = table?.parent?.parent?.parent;
|
|
2064
|
+
if (block.parent?.label !== 'columns' || table?.parent?.label !== 'table') return undefined;
|
|
2065
|
+
if (table.parent.parent?.label !== 'entries' || namespace === undefined) return undefined;
|
|
2066
|
+
return listKey(namespace.label, table.label, block.label);
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
/** The key of a domain field block (`namespaces.<ns>.models.<model>.fields.<field>`). */
|
|
2070
|
+
function fieldBlockKey(block: Block): string | undefined {
|
|
2071
|
+
const model = block.parent?.parent;
|
|
2072
|
+
const namespace = model?.parent?.parent;
|
|
2073
|
+
if (block.parent?.label !== 'fields' || model?.parent?.label !== 'models') return undefined;
|
|
2074
|
+
if (namespace === undefined) return undefined;
|
|
2075
|
+
return listKey(namespace.label, model.label, block.label);
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
const FIELD_TYPE_MAPS = new Set(['FieldOutputTypes', 'FieldInputTypes']);
|
|
2079
|
+
const COLUMN_TYPE_MAPS = new Set(['StorageColumnTypes', 'StorageColumnInputTypes']);
|
|
2080
|
+
|
|
2081
|
+
/** Whether a row type member names a waived list: in the field and column type maps, keyed namespace, model or table, member; or in a `Models` type alias, `<namespace>_<Model>` or `<Model>`. */
|
|
2082
|
+
function isWaivedRowMember(
|
|
2083
|
+
block: Block,
|
|
2084
|
+
member: string,
|
|
2085
|
+
columns: ReadonlySet<string>,
|
|
2086
|
+
fields: ReadonlySet<string>,
|
|
2087
|
+
): boolean {
|
|
2088
|
+
const namespace = block.parent;
|
|
2089
|
+
const map = namespace?.parent;
|
|
2090
|
+
if (map !== undefined && map.parent === undefined) {
|
|
2091
|
+
const key = listKey(namespace?.label ?? '', block.label, member);
|
|
2092
|
+
if (FIELD_TYPE_MAPS.has(map.label)) return fields.has(key);
|
|
2093
|
+
if (COLUMN_TYPE_MAPS.has(map.label)) return columns.has(key);
|
|
2094
|
+
}
|
|
2095
|
+
if (namespace?.label !== 'Models' || namespace.parent !== undefined) return false;
|
|
2096
|
+
return [...fields].some((key) => {
|
|
2097
|
+
const [fieldNamespace, model, field] = key.split('\u0000');
|
|
2098
|
+
return (
|
|
2099
|
+
field === member && (block.label === model || block.label === `${fieldNamespace}_${model}`)
|
|
2100
|
+
);
|
|
2101
|
+
});
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
/** The end of the type argument that starts at `start`: the index of its closing `>`. */
|
|
2105
|
+
function typeArgumentEnd(text: string, start: number): number {
|
|
2106
|
+
let depth = 1;
|
|
2107
|
+
let quote: string | undefined;
|
|
2108
|
+
for (let index = start; index < text.length; index++) {
|
|
2109
|
+
const char = text[index];
|
|
2110
|
+
if (quote !== undefined) {
|
|
2111
|
+
if (char === '\\') index++;
|
|
2112
|
+
else if (char === quote) quote = undefined;
|
|
2113
|
+
} else if (char === "'" || char === '"' || char === '`') quote = char;
|
|
2114
|
+
else if (char === '<') depth++;
|
|
2115
|
+
else if (char === '>' && text[index - 1] !== '=' && --depth === 0) return index;
|
|
2116
|
+
}
|
|
2117
|
+
return -1;
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
function quoted(text: string, quote: string): string {
|
|
2121
|
+
return `${quote}${text.replaceAll('\\', '\\\\').replaceAll(quote, `\\${quote}`)}${quote}`;
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
const NUMBER_TOKEN = /(?<![\w.$'"])-?\d+(?:\.\d+)?(?:e[+-]?\d+)?(?![\w.$'"])/gi;
|
|
2125
|
+
|
|
2126
|
+
/** A default's literal type with each rewritten value replaced: a string in either quote, a number as its own token. */
|
|
2127
|
+
function withRewrittenLiterals(literal: string, rewrites: readonly DefaultRewrite[]): string {
|
|
2128
|
+
let result = literal;
|
|
2129
|
+
const numbers = new Map<number, number>();
|
|
2130
|
+
for (const { from, to } of rewrites) {
|
|
2131
|
+
if (typeof from === 'number' && typeof to === 'number') numbers.set(from, to);
|
|
2132
|
+
if (typeof from === 'string' && typeof to === 'string')
|
|
2133
|
+
for (const quote of ["'", '"'])
|
|
2134
|
+
result = result.replaceAll(quoted(from, quote), quoted(to, quote));
|
|
2135
|
+
}
|
|
2136
|
+
if (numbers.size === 0) return result;
|
|
2137
|
+
return result.replace(NUMBER_TOKEN, (token) => String(numbers.get(Number(token)) ?? token));
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
function rewriteDts(
|
|
2141
|
+
text: string,
|
|
2142
|
+
columns: ReadonlySet<string>,
|
|
2143
|
+
fields: ReadonlySet<string>,
|
|
2144
|
+
defaults: ReadonlyMap<string, readonly DefaultRewrite[]>,
|
|
2145
|
+
hashes: ReadonlyMap<string, string>,
|
|
2146
|
+
): string {
|
|
2147
|
+
const blocks = scanBlocks(text);
|
|
2148
|
+
const edits: { start: number; end: number; text: string }[] = [];
|
|
2149
|
+
for (const match of text.matchAll(/DefaultLiteralValue</g)) {
|
|
2150
|
+
const holder = innermostBlock(blocks, match.index);
|
|
2151
|
+
const column = holder?.label === 'default' ? holder.parent : undefined;
|
|
2152
|
+
const key = column === undefined ? undefined : columnBlockKey(column);
|
|
2153
|
+
const rewrites = key === undefined ? undefined : defaults.get(key);
|
|
2154
|
+
const end = typeArgumentEnd(text, match.index + match[0].length);
|
|
2155
|
+
if (rewrites === undefined || end === -1) continue;
|
|
2156
|
+
const codecEnd = /^\s*(['"])(?:\\.|(?!\1).)*\1/.exec(
|
|
2157
|
+
text.slice(match.index + match[0].length, end),
|
|
2158
|
+
);
|
|
2159
|
+
const start = match.index + match[0].length + (codecEnd?.[0].length ?? 0);
|
|
2160
|
+
edits.push({ start, end, text: withRewrittenLiterals(text.slice(start, end), rewrites) });
|
|
2161
|
+
}
|
|
2162
|
+
const rowMember =
|
|
2163
|
+
/(?:readonly\s+)?([\p{ID_Start}_$][\p{ID_Continue}$]*|'[^']*'|"[^"]*")\s*\??\s*:\s*ReadonlyArray</gu;
|
|
2164
|
+
for (const match of text.matchAll(rowMember)) {
|
|
2165
|
+
const block = innermostBlock(blocks, match.index);
|
|
2166
|
+
const member = match[1]?.replace(/^['"]|['"]$/g, '') ?? '';
|
|
2167
|
+
if (block === undefined || !isWaivedRowMember(block, member, columns, fields)) continue;
|
|
2168
|
+
const elementStart = match.index + match[0].length;
|
|
2169
|
+
const elementEnd = typeArgumentEnd(text, elementStart);
|
|
2170
|
+
if (elementEnd === -1 || /\|\s*null\s*$/.test(text.slice(elementStart, elementEnd))) continue;
|
|
2171
|
+
edits.push({ start: elementEnd, end: elementEnd, text: ' | null' });
|
|
2172
|
+
}
|
|
2173
|
+
for (const match of text.matchAll(/readonly elementNullable:\s*false/g)) {
|
|
2174
|
+
const many = innermostBlock(blocks, match.index);
|
|
2175
|
+
const holder = many?.label === 'many' ? many.parent : undefined;
|
|
2176
|
+
if (holder === undefined) continue;
|
|
2177
|
+
const column = columnBlockKey(holder);
|
|
2178
|
+
const field = fieldBlockKey(holder);
|
|
2179
|
+
if (
|
|
2180
|
+
!(column !== undefined && columns.has(column)) &&
|
|
2181
|
+
!(field !== undefined && fields.has(field))
|
|
2182
|
+
)
|
|
2183
|
+
continue;
|
|
2184
|
+
edits.push({
|
|
2185
|
+
start: match.index,
|
|
2186
|
+
end: match.index + match[0].length,
|
|
2187
|
+
text: 'readonly elementNullable: true',
|
|
2188
|
+
});
|
|
2189
|
+
}
|
|
2190
|
+
let result = text;
|
|
2191
|
+
for (const edit of edits.sort((a, b) => b.start - a.start))
|
|
2192
|
+
result = `${result.slice(0, edit.start)}${edit.text}${result.slice(edit.end)}`;
|
|
2193
|
+
return replaceHashTokens(result, hashes);
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
function replaceHashTokens(text: string, hashes: ReadonlyMap<string, string>): string {
|
|
2197
|
+
return text.replace(
|
|
2198
|
+
/(?<![0-9a-f])[0-9a-f]{64}(?![0-9a-f])/g,
|
|
2199
|
+
(hash: string) => hashes.get(hash) ?? hash,
|
|
2200
|
+
);
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
interface ContractPlan {
|
|
2204
|
+
readonly path: string;
|
|
2205
|
+
readonly snapshot: boolean;
|
|
2206
|
+
readonly oldHash: string;
|
|
2207
|
+
readonly newHash: string;
|
|
2208
|
+
readonly content: string;
|
|
2209
|
+
readonly columns: ReadonlySet<string>;
|
|
2210
|
+
readonly fields: ReadonlySet<string>;
|
|
2211
|
+
readonly defaults: ReadonlyMap<string, readonly DefaultRewrite[]>;
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
function summary(
|
|
2215
|
+
root: string,
|
|
2216
|
+
contractsFound: number,
|
|
2217
|
+
files: number,
|
|
2218
|
+
directories: number,
|
|
2219
|
+
hashes: ReadonlyMap<string, string>,
|
|
2220
|
+
): readonly string[] {
|
|
2221
|
+
if (contractsFound === 0) return [`No SQL contract was found under ${root}; nothing changed.`];
|
|
2222
|
+
if (files === 0 && directories === 0)
|
|
2223
|
+
return ['No contract stores a noCheck key or a default in another form; nothing changed.'];
|
|
2224
|
+
const renamed = count(directories, 'snapshot directory', 'snapshot directories');
|
|
2225
|
+
const changes = `Rewrote ${count(files, 'file', 'files')} and renamed ${renamed}.`;
|
|
2226
|
+
if (hashes.size === 0) return [changes];
|
|
2227
|
+
return [
|
|
2228
|
+
`${changes} Storage hashes changed (old -> new):`,
|
|
2229
|
+
...[...hashes]
|
|
2230
|
+
.sort(([a], [b]) => compareCodeUnits(a, b))
|
|
2231
|
+
.map(([oldHash, newHash]) => ` ${oldHash} -> ${newHash}`),
|
|
2232
|
+
];
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
const JSON_FILES_THAT_MUST_PARSE = new Set(['contract.json', 'migration.json']);
|
|
2236
|
+
|
|
2237
|
+
const USAGE =
|
|
2238
|
+
'Usage: node remove-nocheck.ts [project-root] [--default <namespace>.<table>.<column>=<JSON value>]...';
|
|
2239
|
+
|
|
2240
|
+
interface Args {
|
|
2241
|
+
readonly root: string;
|
|
2242
|
+
readonly replacements: ReadonlyMap<string, Json>;
|
|
2243
|
+
readonly errors: readonly string[];
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
function parseArgs(args: readonly string[]): Args {
|
|
2247
|
+
const errors: string[] = [];
|
|
2248
|
+
const positional: string[] = [];
|
|
2249
|
+
const replacements = new Map<string, Json>();
|
|
2250
|
+
for (let index = 0; index < args.length; index++) {
|
|
2251
|
+
const arg = args[index] ?? '';
|
|
2252
|
+
const given = arg === '--default' ? args[++index] : undefined;
|
|
2253
|
+
const option = arg.startsWith('--default=') ? arg.slice('--default='.length) : given;
|
|
2254
|
+
if (option === undefined && !arg.startsWith('-')) {
|
|
2255
|
+
positional.push(arg);
|
|
2256
|
+
continue;
|
|
2257
|
+
}
|
|
2258
|
+
if (option === undefined && arg !== '--default') {
|
|
2259
|
+
errors.push(`${arg}: unknown option`);
|
|
2260
|
+
continue;
|
|
2261
|
+
}
|
|
2262
|
+
const separator = option?.indexOf('=') ?? -1;
|
|
2263
|
+
const value = option === undefined ? undefined : parseJson(option.slice(separator + 1));
|
|
2264
|
+
if (option === undefined || separator < 1 || value === undefined) {
|
|
2265
|
+
const shown = option === undefined ? '--default' : `--default ${option}`;
|
|
2266
|
+
errors.push(`${shown}: expected <namespace>.<table>.<column>=<JSON value>`);
|
|
2267
|
+
continue;
|
|
2268
|
+
}
|
|
2269
|
+
replacements.set(option.slice(0, separator), value);
|
|
2270
|
+
}
|
|
2271
|
+
if (positional.length > 1) errors.push(`expected one project root, got ${positional.length}`);
|
|
2272
|
+
const root = resolve(positional[0] ?? process.cwd());
|
|
2273
|
+
if (errors.length === 0 && !isDirectory(root)) errors.push(`${root}: not a directory`);
|
|
2274
|
+
if (errors.length > 0) errors.push(USAGE);
|
|
2275
|
+
return { root, replacements, errors };
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
function main({ root, replacements, errors }: Args): number {
|
|
2279
|
+
if (errors.length > 0) {
|
|
2280
|
+
process.stderr.write(`${errors.join('\n')}\n`);
|
|
2281
|
+
return 1;
|
|
2282
|
+
}
|
|
2283
|
+
const display = (path: string): string => relative(root, path).split(sep).join('/');
|
|
2284
|
+
const files = listFiles(root);
|
|
2285
|
+
const plans: ContractPlan[] = [];
|
|
2286
|
+
const stops: string[] = [];
|
|
2287
|
+
let contractsFound = 0;
|
|
2288
|
+
const used = new Set<string>();
|
|
2289
|
+
|
|
2290
|
+
for (const path of files.json) {
|
|
2291
|
+
const text = readFileSync(path, 'utf8');
|
|
2292
|
+
const contract = parseJson(text);
|
|
2293
|
+
if (
|
|
2294
|
+
contract === undefined &&
|
|
2295
|
+
(JSON_FILES_THAT_MUST_PARSE.has(basename(path)) || files.refs.includes(path))
|
|
2296
|
+
) {
|
|
2297
|
+
stops.push(`${display(path)}: not valid JSON`);
|
|
2298
|
+
continue;
|
|
2299
|
+
}
|
|
2300
|
+
if (
|
|
2301
|
+
!isRecord(contract) ||
|
|
2302
|
+
contract['targetFamily'] !== 'sql' ||
|
|
2303
|
+
typeof contract['target'] !== 'string' ||
|
|
2304
|
+
!isRecord(contract['storage'])
|
|
2305
|
+
)
|
|
2306
|
+
continue;
|
|
2307
|
+
contractsFound++;
|
|
2308
|
+
const rewrite = rewriteContract(contract, replacements, used);
|
|
2309
|
+
for (const problem of rewrite.notValues) stops.push(`${display(path)}: ${problem}`);
|
|
2310
|
+
if (!rewrite.changed || rewrite.notValues.length > 0) continue;
|
|
2311
|
+
const snapshot = isSnapshotContract(path);
|
|
2312
|
+
const stored = contract['storage']['storageHash'];
|
|
2313
|
+
const oldHash = snapshot ? basename(dirname(path)) : typeof stored === 'string' ? stored : '';
|
|
2314
|
+
const computed = computeStorageHash(contract);
|
|
2315
|
+
if (computed !== oldHash || (typeof stored === 'string' && stored !== oldHash)) {
|
|
2316
|
+
stops.push(
|
|
2317
|
+
`${display(path)}: the stored storage hash ${oldHash} does not match the contract's content, which hashes to ${computed}; restore the file from version control, or re-emit it, and run the script again`,
|
|
2318
|
+
);
|
|
2319
|
+
continue;
|
|
2320
|
+
}
|
|
2321
|
+
const newHash = computeStorageHash(rewrite.contract);
|
|
2322
|
+
plans.push({
|
|
2323
|
+
path,
|
|
2324
|
+
snapshot,
|
|
2325
|
+
oldHash,
|
|
2326
|
+
newHash,
|
|
2327
|
+
content: writtenForm(withStorageHash(rewrite.contract, newHash), contract, text),
|
|
2328
|
+
columns: rewrite.columns,
|
|
2329
|
+
fields: rewrite.fields,
|
|
2330
|
+
defaults: rewrite.defaults,
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
for (const key of replacements.keys())
|
|
2335
|
+
if (!used.has(key))
|
|
2336
|
+
stops.push(
|
|
2337
|
+
`--default ${key}: no stored contract has a default of this column that this release refuses, so the script replaces nothing`,
|
|
2338
|
+
);
|
|
2339
|
+
|
|
2340
|
+
const hashes = new Map<string, string>();
|
|
2341
|
+
for (const plan of [...plans].sort((a, b) => Number(b.snapshot) - Number(a.snapshot)))
|
|
2342
|
+
if (plan.oldHash !== plan.newHash && !hashes.has(plan.oldHash))
|
|
2343
|
+
hashes.set(plan.oldHash, plan.newHash);
|
|
2344
|
+
|
|
2345
|
+
const newDirectories = new Map<string, Map<string, string>>();
|
|
2346
|
+
const directorySources = new Map<string, string>();
|
|
2347
|
+
const sourceDirectories = new Set<string>();
|
|
2348
|
+
const removals = new Set<string>();
|
|
2349
|
+
const snapshotRewrites: [string, string][] = [];
|
|
2350
|
+
const referenceWrites = new Map<string, string>();
|
|
2351
|
+
const contractWrites = new Map<string, string>();
|
|
2352
|
+
for (const plan of plans) {
|
|
2353
|
+
const dtsPath = plan.snapshot
|
|
2354
|
+
? join(dirname(plan.path), 'contract.d.ts')
|
|
2355
|
+
: `${plan.path.slice(0, -'.json'.length)}.d.ts`;
|
|
2356
|
+
const dtsHashes = new Map([...hashes, [plan.oldHash, plan.newHash]]);
|
|
2357
|
+
const dts = existsSync(dtsPath)
|
|
2358
|
+
? rewriteDts(
|
|
2359
|
+
readFileSync(dtsPath, 'utf8'),
|
|
2360
|
+
plan.columns,
|
|
2361
|
+
plan.fields,
|
|
2362
|
+
plan.defaults,
|
|
2363
|
+
dtsHashes,
|
|
2364
|
+
)
|
|
2365
|
+
: undefined;
|
|
2366
|
+
if (!plan.snapshot) {
|
|
2367
|
+
if (dts !== undefined) referenceWrites.set(dtsPath, dts);
|
|
2368
|
+
contractWrites.set(plan.path, plan.content);
|
|
2369
|
+
continue;
|
|
2370
|
+
}
|
|
2371
|
+
const oldDir = dirname(plan.path);
|
|
2372
|
+
const newDir = join(dirname(oldDir), plan.newHash);
|
|
2373
|
+
sourceDirectories.add(oldDir);
|
|
2374
|
+
if (newDir === oldDir) {
|
|
2375
|
+
if (dts !== undefined) snapshotRewrites.push([dtsPath, dts]);
|
|
2376
|
+
snapshotRewrites.push([plan.path, plan.content]);
|
|
2377
|
+
continue;
|
|
2378
|
+
}
|
|
2379
|
+
removals.add(oldDir);
|
|
2380
|
+
const content = readDirectory(oldDir);
|
|
2381
|
+
content.set('contract.json', plan.content);
|
|
2382
|
+
if (dts !== undefined) content.set('contract.d.ts', dts);
|
|
2383
|
+
const planned = newDirectories.get(newDir);
|
|
2384
|
+
if (planned !== undefined && !sameFiles(planned, content)) {
|
|
2385
|
+
stops.push(`${display(newDir)}: snapshot directory already exists with different content`);
|
|
2386
|
+
continue;
|
|
2387
|
+
}
|
|
2388
|
+
newDirectories.set(newDir, content);
|
|
2389
|
+
directorySources.set(newDir, oldDir);
|
|
2390
|
+
}
|
|
2391
|
+
for (const [dir, content] of newDirectories) {
|
|
2392
|
+
if (sourceDirectories.has(dir) || !existsSync(dir)) continue;
|
|
2393
|
+
if (sameFiles(readDirectory(dir), content)) newDirectories.delete(dir);
|
|
2394
|
+
else stops.push(`${display(dir)}: snapshot directory already exists with different content`);
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
for (const path of files.migrationJson) {
|
|
2398
|
+
const text = readFileSync(path, 'utf8');
|
|
2399
|
+
const metadata = parseJson(text);
|
|
2400
|
+
if (!isRecord(metadata)) continue;
|
|
2401
|
+
const from = metadata['from'];
|
|
2402
|
+
const to = metadata['to'];
|
|
2403
|
+
const nextFrom = typeof from === 'string' ? (hashes.get(from) ?? from) : from;
|
|
2404
|
+
const nextTo = typeof to === 'string' ? (hashes.get(to) ?? to) : to;
|
|
2405
|
+
if (nextFrom === from && nextTo === to) continue;
|
|
2406
|
+
const opsPath = join(dirname(path), 'ops.json');
|
|
2407
|
+
const ops = existsSync(opsPath) ? parseJson(readFileSync(opsPath, 'utf8')) : undefined;
|
|
2408
|
+
if (existsSync(opsPath) && ops === undefined) {
|
|
2409
|
+
stops.push(`${display(opsPath)}: not valid JSON`);
|
|
2410
|
+
continue;
|
|
2411
|
+
}
|
|
2412
|
+
const oldMigrationHash = metadata['migrationHash'];
|
|
2413
|
+
let next = replaceQuotedHashes(text, hashes);
|
|
2414
|
+
if (
|
|
2415
|
+
ops !== undefined &&
|
|
2416
|
+
typeof oldMigrationHash === 'string' &&
|
|
2417
|
+
nextFrom !== undefined &&
|
|
2418
|
+
nextTo !== undefined
|
|
2419
|
+
) {
|
|
2420
|
+
const migrationHash = computeMigrationHash({ ...metadata, from: nextFrom, to: nextTo }, ops);
|
|
2421
|
+
next = next.replace(`"${oldMigrationHash}"`, `"${migrationHash}"`);
|
|
2422
|
+
}
|
|
2423
|
+
referenceWrites.set(path, next);
|
|
2424
|
+
}
|
|
2425
|
+
for (const path of files.refs) {
|
|
2426
|
+
const text = readFileSync(path, 'utf8');
|
|
2427
|
+
const next = replaceQuotedHashes(text, hashes);
|
|
2428
|
+
if (next !== text) referenceWrites.set(path, next);
|
|
2429
|
+
}
|
|
2430
|
+
for (const path of files.migrationTs) {
|
|
2431
|
+
const text = readFileSync(path, 'utf8');
|
|
2432
|
+
const next = replaceHashTokens(text, hashes);
|
|
2433
|
+
if (next !== text) referenceWrites.set(path, next);
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
if (stops.length > 0) {
|
|
2437
|
+
process.stderr.write(`${[...new Set(stops)].join('\n')}\n`);
|
|
2438
|
+
return 1;
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
try {
|
|
2442
|
+
for (const path of files.leftovers) rmSync(path, { recursive: true, force: true });
|
|
2443
|
+
for (const [dir, content] of newDirectories)
|
|
2444
|
+
writeDirectory(dir, content, directorySources.get(dir) ?? dir);
|
|
2445
|
+
for (const [path, text] of snapshotRewrites) writeFile(path, text);
|
|
2446
|
+
for (const [path, text] of referenceWrites) writeFile(path, text);
|
|
2447
|
+
for (const [path, text] of contractWrites) writeFile(path, text);
|
|
2448
|
+
for (const dir of removals) removeDirectory(dir);
|
|
2449
|
+
} catch (error) {
|
|
2450
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2451
|
+
process.stderr.write(
|
|
2452
|
+
`${message}; the upgrade stopped partway, run the script again to finish it\n`,
|
|
2453
|
+
);
|
|
2454
|
+
return 1;
|
|
2455
|
+
}
|
|
2456
|
+
const rewrittenFiles = snapshotRewrites.length + referenceWrites.size + contractWrites.size;
|
|
2457
|
+
const lines = [...summary(root, contractsFound, rewrittenFiles, removals.size, hashes)];
|
|
2458
|
+
process.stdout.write(`${lines.join('\n')}\n`);
|
|
2459
|
+
return 0;
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
process.exitCode = main(parseArgs(process.argv.slice(2)));
|