postgrelize 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +289 -0
- package/LICENSE +21 -0
- package/README.md +131 -2
- package/dist/associations/alias-minifier.d.ts +43 -0
- package/dist/associations/association-accessors.d.ts +21 -0
- package/dist/associations/association-key-types.d.ts +44 -0
- package/dist/associations/association-keys.d.ts +98 -0
- package/dist/associations/association-lookup.d.ts +26 -0
- package/dist/associations/association-shape.d.ts +25 -0
- package/dist/associations/association.d.ts +95 -0
- package/dist/associations/belongs-to-many.d.ts +86 -0
- package/dist/associations/belongs-to.d.ts +45 -0
- package/dist/associations/has-many.d.ts +79 -0
- package/dist/associations/has-one.d.ts +44 -0
- package/dist/associations/include-assembler.d.ts +21 -0
- package/dist/associations/include-columns.d.ts +24 -0
- package/dist/associations/include-joins.d.ts +17 -0
- package/dist/associations/include-loader.d.ts +48 -0
- package/dist/associations/include-order.d.ts +22 -0
- package/dist/associations/include-query-builder.d.ts +54 -0
- package/dist/associations/include-resolver.d.ts +29 -0
- package/dist/associations/include-rows.d.ts +47 -0
- package/dist/associations/include-sub-query.d.ts +35 -0
- package/dist/associations/include.d.ts +112 -0
- package/dist/associations/junction-keys.d.ts +23 -0
- package/dist/associations/nested-creator.d.ts +44 -0
- package/dist/associations/nested-saver.d.ts +30 -0
- package/dist/associations/owner-keys.d.ts +34 -0
- package/dist/associations/separate-include-loader.d.ts +24 -0
- package/dist/associations/types.d.ts +139 -0
- package/dist/connection/after-connect-hook.d.ts +24 -0
- package/dist/connection/connect-hooks.d.ts +26 -0
- package/dist/connection/connection-config.d.ts +33 -0
- package/dist/connection/connection-manager.d.ts +65 -0
- package/dist/connection/connection-types.d.ts +21 -0
- package/dist/connection/copy-from-stdin.d.ts +52 -0
- package/dist/connection/copy-runner.d.ts +30 -0
- package/dist/connection/copy-to-stdout.d.ts +49 -0
- package/dist/connection/copy.d.ts +22 -0
- package/dist/connection/notifications.d.ts +28 -0
- package/dist/connection/options.d.ts +165 -0
- package/dist/connection/query-logger.d.ts +41 -0
- package/dist/connection/replica-router.d.ts +20 -0
- package/dist/connection/statement-cache.d.ts +36 -0
- package/dist/connection/statement-timeout.d.ts +22 -0
- package/dist/data-types/abstract-data-type.d.ts +58 -0
- package/dist/data-types/array-literal-parser.d.ts +17 -0
- package/dist/data-types/array-type.d.ts +18 -0
- package/dist/data-types/bit-type.d.ts +14 -0
- package/dist/data-types/blob-type.d.ts +12 -0
- package/dist/data-types/char-type.d.ts +12 -0
- package/dist/data-types/composite-fields.d.ts +26 -0
- package/dist/data-types/composite-type.d.ts +32 -0
- package/dist/data-types/data-types.d.ts +176 -0
- package/dist/data-types/date-type.d.ts +14 -0
- package/dist/data-types/decimal-type.d.ts +13 -0
- package/dist/data-types/default-value-generator.d.ts +15 -0
- package/dist/data-types/enum-type.d.ts +19 -0
- package/dist/data-types/ewkb-reader.d.ts +18 -0
- package/dist/data-types/ewkb-writer.d.ts +17 -0
- package/dist/data-types/float-type.d.ts +12 -0
- package/dist/data-types/geometric-text.d.ts +65 -0
- package/dist/data-types/geometric-type.d.ts +46 -0
- package/dist/data-types/hstore-type.d.ts +16 -0
- package/dist/data-types/integer-type.d.ts +24 -0
- package/dist/data-types/json-type.d.ts +16 -0
- package/dist/data-types/multirange-type.d.ts +19 -0
- package/dist/data-types/range-type.d.ts +28 -0
- package/dist/data-types/record-text.d.ts +29 -0
- package/dist/data-types/scalar-type.d.ts +13 -0
- package/dist/data-types/spatial-type.d.ts +20 -0
- package/dist/data-types/string-type.d.ts +12 -0
- package/dist/data-types/text-type.d.ts +12 -0
- package/dist/data-types/timestamp-type.d.ts +15 -0
- package/dist/data-types/virtual-type.d.ts +15 -0
- package/dist/data-types/wall-clock.d.ts +14 -0
- package/dist/ddl/column-ddl.d.ts +73 -0
- package/dist/ddl/constraint-ddl.d.ts +30 -0
- package/dist/ddl/ddl-generator.d.ts +181 -0
- package/dist/ddl/ddl-guards.d.ts +60 -0
- package/dist/ddl/ddl-types.d.ts +204 -0
- package/dist/ddl/enum-ddl.d.ts +42 -0
- package/dist/ddl/extension-ddl.d.ts +57 -0
- package/dist/ddl/function-ddl.d.ts +98 -0
- package/dist/ddl/index-ddl.d.ts +29 -0
- package/dist/ddl/index-element-ddl.d.ts +19 -0
- package/dist/ddl/partition-ddl.d.ts +88 -0
- package/dist/ddl/partition-types.d.ts +94 -0
- package/dist/ddl/policy-ddl.d.ts +137 -0
- package/dist/ddl/routine-guards.d.ts +63 -0
- package/dist/ddl/sequence-ddl.d.ts +103 -0
- package/dist/ddl/sql-literal.d.ts +61 -0
- package/dist/ddl/table-ddl.d.ts +35 -0
- package/dist/ddl/trigger-ddl.d.ts +81 -0
- package/dist/ddl/view-ddl.d.ts +122 -0
- package/dist/decorators/association-applier.d.ts +18 -0
- package/dist/decorators/association-decorators.d.ts +72 -0
- package/dist/decorators/column-decorators.d.ts +147 -0
- package/dist/decorators/decorator-factory.d.ts +45 -0
- package/dist/decorators/decorator-signature.d.ts +26 -0
- package/dist/decorators/decorator-types.d.ts +24 -0
- package/dist/decorators/foreign-key-decorator.d.ts +21 -0
- package/dist/decorators/hook-decorators.d.ts +393 -0
- package/dist/decorators/init-arguments.d.ts +29 -0
- package/dist/decorators/model-decorators.d.ts +18 -0
- package/dist/decorators/model-metadata.d.ts +70 -0
- package/dist/decorators/table-decorators.d.ts +43 -0
- package/dist/decorators/timestamp-decorators.d.ts +38 -0
- package/dist/errors/base-error.d.ts +40 -0
- package/dist/errors/connection-errors.d.ts +152 -0
- package/dist/errors/database-errors.d.ts +186 -0
- package/dist/errors/errors.d.ts +5 -0
- package/dist/errors/map-pg-error.d.ts +27 -0
- package/dist/errors/misc-errors.d.ts +232 -0
- package/dist/errors/validation-errors.d.ts +141 -0
- package/dist/exports-associations.d.ts +6 -0
- package/dist/exports-core.d.ts +95 -0
- package/dist/exports-decorators.d.ts +8 -0
- package/dist/exports-errors.d.ts +2 -0
- package/dist/exports-model.d.ts +21 -0
- package/dist/exports-schema.d.ts +19 -0
- package/dist/expressions/call-expressions.d.ts +54 -0
- package/dist/expressions/condition-expressions.d.ts +51 -0
- package/dist/expressions/expression.d.ts +52 -0
- package/dist/expressions/jsonpath-helpers.d.ts +37 -0
- package/dist/expressions/logic.d.ts +25 -0
- package/dist/expressions/methods.d.ts +188 -0
- package/dist/expressions/op.d.ts +182 -0
- package/dist/expressions/query-expressions.d.ts +110 -0
- package/dist/expressions/row-expressions.d.ts +35 -0
- package/dist/expressions/search-helpers.d.ts +138 -0
- package/dist/expressions/trigram-helpers.d.ts +40 -0
- package/dist/hooks/hooks.d.ts +125 -0
- package/dist/index.cjs +21864 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +21688 -0
- package/dist/index.js.map +1 -0
- package/dist/model/attribute-columns.d.ts +85 -0
- package/dist/model/attribute-normalizer.d.ts +42 -0
- package/dist/model/attribute-options.d.ts +121 -0
- package/dist/model/bulk-insert-builder.d.ts +24 -0
- package/dist/model/bulk-options.d.ts +173 -0
- package/dist/model/copy-options.d.ts +51 -0
- package/dist/model/cte-builder.d.ts +134 -0
- package/dist/model/definition-normalizer.d.ts +26 -0
- package/dist/model/delete-query-builder.d.ts +42 -0
- package/dist/model/find-options.d.ts +144 -0
- package/dist/model/find-query-builder.d.ts +38 -0
- package/dist/model/inflector.d.ts +28 -0
- package/dist/model/insert-query-builder.d.ts +41 -0
- package/dist/model/instance-destroyer.d.ts +44 -0
- package/dist/model/instance-lifecycle-services.d.ts +61 -0
- package/dist/model/instance-lifecycle.d.ts +128 -0
- package/dist/model/instance-saver.d.ts +25 -0
- package/dist/model/instance-state.d.ts +48 -0
- package/dist/model/instance-validation.d.ts +35 -0
- package/dist/model/instance-values.d.ts +88 -0
- package/dist/model/instance-writer.d.ts +59 -0
- package/dist/model/join-source-builder.d.ts +25 -0
- package/dist/model/lateral-keys-builder.d.ts +25 -0
- package/dist/model/merge-action-builder.d.ts +31 -0
- package/dist/model/merge-options.d.ts +72 -0
- package/dist/model/merge-query-builder.d.ts +29 -0
- package/dist/model/merge-source-builder.d.ts +22 -0
- package/dist/model/mixins/model-aggregates.d.ts +69 -0
- package/dist/model/mixins/model-associations.d.ts +113 -0
- package/dist/model/mixins/model-constructor.d.ts +7 -0
- package/dist/model/mixins/model-finders.d.ts +140 -0
- package/dist/model/mixins/model-hooks.d.ts +142 -0
- package/dist/model/mixins/model-postgres.d.ts +198 -0
- package/dist/model/mixins/model-schema-binding.d.ts +36 -0
- package/dist/model/mixins/model-schema.d.ts +100 -0
- package/dist/model/mixins/model-scopes.d.ts +57 -0
- package/dist/model/mixins/model-writers.d.ts +175 -0
- package/dist/model/mixins/named-hooks.d.ts +28 -0
- package/dist/model/model-accessors.d.ts +22 -0
- package/dist/model/model-base.d.ts +83 -0
- package/dist/model/model-definition.d.ts +130 -0
- package/dist/model/model-instance-persistence.d.ts +132 -0
- package/dist/model/model-instance-values.d.ts +197 -0
- package/dist/model/model-operations.d.ts +22 -0
- package/dist/model/model-registry.d.ts +152 -0
- package/dist/model/model-services.d.ts +46 -0
- package/dist/model/model-state.d.ts +68 -0
- package/dist/model/model-values.d.ts +86 -0
- package/dist/model/model.d.ts +629 -0
- package/dist/model/on-conflict-builder.d.ts +111 -0
- package/dist/model/operations/bulk-create-operation.d.ts +40 -0
- package/dist/model/operations/copy-from-source.d.ts +51 -0
- package/dist/model/operations/copy-operation.d.ts +54 -0
- package/dist/model/operations/count-operation.d.ts +52 -0
- package/dist/model/operations/create-operation.d.ts +31 -0
- package/dist/model/operations/destroy-operation.d.ts +65 -0
- package/dist/model/operations/find-cursor.d.ts +23 -0
- package/dist/model/operations/find-lookups.d.ts +99 -0
- package/dist/model/operations/find-operation.d.ts +47 -0
- package/dist/model/operations/increment-operation.d.ts +40 -0
- package/dist/model/operations/insert-operation.d.ts +71 -0
- package/dist/model/operations/merge-operation.d.ts +56 -0
- package/dist/model/operations/model-operation.d.ts +33 -0
- package/dist/model/operations/update-operation.d.ts +45 -0
- package/dist/model/operations/upsert-operation.d.ts +39 -0
- package/dist/model/options.d.ts +103 -0
- package/dist/model/returning-old.d.ts +52 -0
- package/dist/model/row-mapper.d.ts +78 -0
- package/dist/model/row-plan.d.ts +31 -0
- package/dist/model/runtime.d.ts +56 -0
- package/dist/model/scope-registry.d.ts +81 -0
- package/dist/model/select-aggregates.d.ts +37 -0
- package/dist/model/select-lock.d.ts +13 -0
- package/dist/model/select-options.d.ts +92 -0
- package/dist/model/select-query-builder.d.ts +73 -0
- package/dist/model/select-targets.d.ts +77 -0
- package/dist/model/source-option-builder.d.ts +23 -0
- package/dist/model/source-options.d.ts +108 -0
- package/dist/model/statement-builder.d.ts +77 -0
- package/dist/model/statement-services.d.ts +2 -0
- package/dist/model/sync-hooks.d.ts +18 -0
- package/dist/model/table-sample-builder.d.ts +13 -0
- package/dist/model/types.d.ts +85 -0
- package/dist/model/unnest-insert-builder.d.ts +24 -0
- package/dist/model/update-query-builder.d.ts +39 -0
- package/dist/model/v6-conflict-builder.d.ts +37 -0
- package/dist/model/value-cloner.d.ts +17 -0
- package/dist/model/values-writer.d.ts +12 -0
- package/dist/model/where-options.d.ts +164 -0
- package/dist/model/write-options.d.ts +160 -0
- package/dist/model/written-rows.d.ts +56 -0
- package/dist/package-version.d.ts +8 -0
- package/dist/query/query-result-shaper.d.ts +93 -0
- package/dist/query/raw-query.d.ts +27 -0
- package/dist/query-interface/alter-planner.d.ts +40 -0
- package/dist/query-interface/bulk-data.d.ts +44 -0
- package/dist/query-interface/column-commands.d.ts +52 -0
- package/dist/query-interface/column-describer.d.ts +17 -0
- package/dist/query-interface/enum-commands.d.ts +36 -0
- package/dist/query-interface/index-commands.d.ts +57 -0
- package/dist/query-interface/model-tables.d.ts +58 -0
- package/dist/query-interface/object-commands.d.ts +71 -0
- package/dist/query-interface/partition-commands.d.ts +43 -0
- package/dist/query-interface/policy-commands.d.ts +54 -0
- package/dist/query-interface/query-interface-catalog.d.ts +180 -0
- package/dist/query-interface/query-interface-objects.d.ts +108 -0
- package/dist/query-interface/query-interface-partitions.d.ts +66 -0
- package/dist/query-interface/query-interface-policies.d.ts +86 -0
- package/dist/query-interface/query-interface-routines.d.ts +120 -0
- package/dist/query-interface/query-interface-tables.d.ts +179 -0
- package/dist/query-interface/query-interface-types.d.ts +62 -0
- package/dist/query-interface/query-interface-views.d.ts +84 -0
- package/dist/query-interface/query-interface.d.ts +256 -0
- package/dist/query-interface/routine-commands.d.ts +71 -0
- package/dist/query-interface/schema-synchronizer.d.ts +110 -0
- package/dist/query-interface/statement-runner.d.ts +40 -0
- package/dist/query-interface/sync-planner.d.ts +26 -0
- package/dist/query-interface/table-commands.d.ts +63 -0
- package/dist/query-interface/table-introspector.d.ts +58 -0
- package/dist/query-interface/view-commands.d.ts +47 -0
- package/dist/sequelize/instance-hook-adders.d.ts +72 -0
- package/dist/sequelize/sequelize-base.d.ts +196 -0
- package/dist/sequelize/sequelize-constructor.d.ts +7 -0
- package/dist/sequelize/sequelize-helpers.d.ts +133 -0
- package/dist/sequelize/sequelize-hooks.d.ts +99 -0
- package/dist/sequelize/sequelize-internals.d.ts +87 -0
- package/dist/sequelize/sequelize-notifications.d.ts +66 -0
- package/dist/sequelize/sequelize-schema.d.ts +125 -0
- package/dist/sequelize/sequelize-transactions.d.ts +96 -0
- package/dist/sequelize.d.ts +1175 -0
- package/dist/sql/ast-clauses.d.ts +137 -0
- package/dist/sql/ast-expressions.d.ts +88 -0
- package/dist/sql/ast-statements.d.ts +80 -0
- package/dist/sql/ast.d.ts +21 -0
- package/dist/sql/compile.d.ts +21 -0
- package/dist/sql/dml-compiler.d.ts +54 -0
- package/dist/sql/expression-compiler.d.ts +56 -0
- package/dist/sql/from-compiler.d.ts +39 -0
- package/dist/sql/identifier-quoter.d.ts +15 -0
- package/dist/sql/merge-compiler.d.ts +20 -0
- package/dist/sql/order.d.ts +15 -0
- package/dist/sql/query-compiler.d.ts +45 -0
- package/dist/sql/sql-chunks.d.ts +50 -0
- package/dist/sql/with-compiler.d.ts +19 -0
- package/dist/transaction/advisory-locks.d.ts +28 -0
- package/dist/transaction/cls-namespace.d.ts +44 -0
- package/dist/transaction/transaction-constants.d.ts +35 -0
- package/dist/transaction/transaction-runner.d.ts +78 -0
- package/dist/transaction/transaction-starter.d.ts +25 -0
- package/dist/transaction/transaction-statements.d.ts +29 -0
- package/dist/transaction/transaction.d.ts +201 -0
- package/dist/validation/attribute-validators.d.ts +23 -0
- package/dist/validation/builtin-attribute-validator.d.ts +19 -0
- package/dist/validation/builtin-validators.d.ts +16 -0
- package/dist/validation/core-validator.d.ts +16 -0
- package/dist/validation/custom-validators.d.ts +13 -0
- package/dist/validation/instance-validator.d.ts +25 -0
- package/dist/validation/schema-items.d.ts +22 -0
- package/dist/validation/standard-schema-validator.d.ts +30 -0
- package/dist/validation/standard-schema.d.ts +39 -0
- package/dist/validation/types.d.ts +36 -0
- package/dist/validation/validation-target.d.ts +13 -0
- package/dist/where/comparison-compiler.d.ts +27 -0
- package/dist/where/condition-compiler.d.ts +18 -0
- package/dist/where/operand-resolver.d.ts +10 -0
- package/dist/where/operator-allowlist.d.ts +14 -0
- package/dist/where/where-support.d.ts +52 -0
- package/dist/where/where.d.ts +46 -0
- package/dist/where/window-compiler.d.ts +14 -0
- package/llm/USAGE.md +423 -0
- package/package.json +103 -4
- package/skills/postgrelize/SKILL.md +57 -0
- package/skills/postgrelize/reference/associations.md +108 -0
- package/skills/postgrelize/reference/errors.md +37 -0
- package/skills/postgrelize/reference/migrating-from-sequelize.md +15 -0
- package/skills/postgrelize/reference/postgresql-features.md +157 -0
- package/skills/postgrelize/reference/querying.md +111 -0
- package/skills/postgrelize/reference/schema.md +135 -0
- package/skills/postgrelize/reference/security.md +34 -0
- package/skills/postgrelize/reference/transactions-and-sessions.md +122 -0
- package/skills/postgrelize/reference/writing.md +198 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from './standard-schema.ts';
|
|
2
|
+
/** Custom attribute validator; throw (or reject) to fail. Called with the instance as `this`. */
|
|
3
|
+
export type AttributeValidatorFunction = (value: unknown) => unknown;
|
|
4
|
+
/** Built-in validator setting: `true`, arguments, or `{ args, msg }`. */
|
|
5
|
+
export type BuiltinValidatorOption = boolean | unknown | ValidatorSetting;
|
|
6
|
+
/** `{ args, msg }` form of a built-in validator setting. */
|
|
7
|
+
export type ValidatorSetting = Readonly<{
|
|
8
|
+
/** Arguments passed to the validator. */
|
|
9
|
+
args?: unknown;
|
|
10
|
+
/** Custom error message. */
|
|
11
|
+
msg?: string;
|
|
12
|
+
}>;
|
|
13
|
+
/**
|
|
14
|
+
* Attribute `validate` option: Sequelize v6 built-in validators (validator.js names plus `is`, `not`,
|
|
15
|
+
* `len`, `notEmpty`, `min`, `max`, ...), custom functions, and `schema` — any Standard Schema
|
|
16
|
+
* (zod, valibot, arktype; PostgreSQL-independent extension).
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const validate: AttributeValidateOptions = {
|
|
21
|
+
* isEmail: true,
|
|
22
|
+
* len: { args: [3, 120], msg: 'Email must be 3-120 characters' },
|
|
23
|
+
* noGmail(value: unknown) {
|
|
24
|
+
* if (String(value).endsWith('@gmail.com')) throw new Error('Gmail is not allowed');
|
|
25
|
+
* },
|
|
26
|
+
* };
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export type AttributeValidateOptions = Readonly<Record<string, BuiltinValidatorOption | AttributeValidatorFunction> & {
|
|
30
|
+
/** Standard Schema the value must satisfy. */
|
|
31
|
+
schema?: StandardSchemaV1;
|
|
32
|
+
/** Custom message for `allowNull: false` violations. */
|
|
33
|
+
notNull?: boolean | ValidatorSetting;
|
|
34
|
+
}>;
|
|
35
|
+
/** Model-level validator (`validate` model option); throw to fail. Called with the instance as `this`. */
|
|
36
|
+
export type ModelValidatorFunction = () => unknown;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ModelDefinition } from '../model/model-definition.ts';
|
|
2
|
+
/** Data needed to validate one instance. */
|
|
3
|
+
export type ValidationTarget = Readonly<{
|
|
4
|
+
instance: object;
|
|
5
|
+
definition: ModelDefinition;
|
|
6
|
+
values: Readonly<Record<string, unknown>>;
|
|
7
|
+
previous: Readonly<Record<string, unknown>>;
|
|
8
|
+
isNewRecord: boolean;
|
|
9
|
+
}>;
|
|
10
|
+
/** Which attributes / model validators to skip. */
|
|
11
|
+
export type ValidationScope = Readonly<{
|
|
12
|
+
skip: ReadonlySet<string>;
|
|
13
|
+
}>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ExprNode } from '../sql/ast.ts';
|
|
2
|
+
import { ExprConverter, JsonAccess, Operand } from './where-support.ts';
|
|
3
|
+
/** `IS NULL` / `IS NOT NULL`. */
|
|
4
|
+
export declare const nullCheck: (left: Operand, negated: boolean) => ExprNode;
|
|
5
|
+
/** True for the values accepted by `Op.is`. */
|
|
6
|
+
export declare const isNullOrBoolean: (value: unknown) => value is boolean | null;
|
|
7
|
+
/** `IS [NOT] NULL|TRUE|FALSE`. */
|
|
8
|
+
export declare const isCheck: (left: Operand, value: boolean | null, negated: boolean) => ExprNode;
|
|
9
|
+
/** `Op.is`: `IS NULL|TRUE|FALSE`. */
|
|
10
|
+
export declare const isOperator: (left: Operand, value: unknown) => ExprNode;
|
|
11
|
+
/**
|
|
12
|
+
* Value comparisons: binary operators with `ANY` / `ALL` quantifiers, `IN` lists (as `= ANY` above
|
|
13
|
+
* the threshold), `BETWEEN`, the `LIKE` shortcuts and jsonb operators on JSON paths.
|
|
14
|
+
*/
|
|
15
|
+
export declare class ComparisonCompiler {
|
|
16
|
+
#private;
|
|
17
|
+
/** `left <sqlOp> value`, with `ANY` / `ALL` quantifiers and JSON value casts. */
|
|
18
|
+
comparison(compiler: ExprConverter, sqlOp: string, left: Operand, value: unknown): ExprNode;
|
|
19
|
+
/** `Op.startsWith` / `Op.endsWith` / `Op.substring` as `LIKE`. */
|
|
20
|
+
pattern(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode;
|
|
21
|
+
/** `[NOT] IN`; empty lists become `FALSE` / `TRUE`, long lists `= ANY($n)` / `<> ALL($n)`. */
|
|
22
|
+
inList(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode;
|
|
23
|
+
/** `[NOT] BETWEEN low AND high`. */
|
|
24
|
+
between(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode;
|
|
25
|
+
/** jsonb key existence / containment operator on the jsonb value at a JSON path (`#>`). */
|
|
26
|
+
jsonb(compiler: ExprConverter, sqlOp: string, op: symbol, json: JsonAccess, value: unknown): ExprNode;
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ExprNode } from '../sql/ast.ts';
|
|
2
|
+
import { ComparisonCompiler } from './comparison-compiler.ts';
|
|
3
|
+
import { ExprConverter, Operand } from './where-support.ts';
|
|
4
|
+
/**
|
|
5
|
+
* Compiles the value of one attribute condition (`{ attr: value }`): plain values, `Op.*` objects,
|
|
6
|
+
* nested JSON conditions and the logical combinators applied to the same attribute.
|
|
7
|
+
*/
|
|
8
|
+
export declare class ConditionCompiler {
|
|
9
|
+
#private;
|
|
10
|
+
/**
|
|
11
|
+
* @param comparisons - Value comparisons.
|
|
12
|
+
*/
|
|
13
|
+
constructor(comparisons: ComparisonCompiler);
|
|
14
|
+
/** Condition of `left` against a where value (plain value, array, `Op.*` object, JSON object). */
|
|
15
|
+
condition(compiler: ExprConverter, left: Operand, value: unknown): ExprNode;
|
|
16
|
+
/** Applies one `Op.*` operator; only operators of the allowlist are accepted. */
|
|
17
|
+
operator(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode;
|
|
18
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Operand, WhereContext } from './where-support.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Resolves a where key into its left-hand operand: `$table.column$` paths, attribute names mapped
|
|
4
|
+
* to columns, `attr.a.b` JSON paths and `attr::type` casts.
|
|
5
|
+
*/
|
|
6
|
+
export declare class OperandResolver {
|
|
7
|
+
#private;
|
|
8
|
+
/** Operand of a where key. */
|
|
9
|
+
operand(context: WhereContext, key: string): Operand;
|
|
10
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Checks a `attribute::type` cast against the allowlist. */
|
|
2
|
+
export declare const validCastType: (type: string) => string;
|
|
3
|
+
/** Checks the string comparator of `where(attr, comparator, value)` against the allowlist. */
|
|
4
|
+
export declare const validComparator: (comparator: string) => string;
|
|
5
|
+
/** Operators compiled to a binary SQL operator. */
|
|
6
|
+
export declare const binaryOps: ReadonlyMap<symbol, string>;
|
|
7
|
+
/** jsonb key existence and jsonpath operators; their values are never serialized as JSON. */
|
|
8
|
+
export declare const KEY_OPERATORS: ReadonlySet<symbol>;
|
|
9
|
+
/** Containment operators (jsonb when applied to a JSON path). */
|
|
10
|
+
export declare const CONTAINMENT_OPERATORS: ReadonlySet<symbol>;
|
|
11
|
+
/** Families of the operators that are not plain binary SQL operators. */
|
|
12
|
+
export type OperatorFamily = 'equality' | 'membership' | 'pattern' | 'logical' | 'quantifier';
|
|
13
|
+
/** Operator family of every non-binary operator. */
|
|
14
|
+
export declare const operatorFamilies: ReadonlyMap<symbol, OperatorFamily>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { ExprNode } from '../sql/ast.ts';
|
|
2
|
+
/** Attribute facts the where compiler needs; supplied by the model layer. */
|
|
3
|
+
export type AttributeRef = Readonly<{
|
|
4
|
+
field: string;
|
|
5
|
+
isJson?: boolean;
|
|
6
|
+
castType?: string;
|
|
7
|
+
serialize?: (value: unknown) => unknown;
|
|
8
|
+
}>;
|
|
9
|
+
/** Attribute resolver and options injected into a `WhereCompiler`. */
|
|
10
|
+
export type WhereContext = Readonly<{
|
|
11
|
+
tableAlias?: string;
|
|
12
|
+
resolve: (attribute: string) => AttributeRef | undefined;
|
|
13
|
+
inAsAnyThreshold?: number;
|
|
14
|
+
/** Allows `excluded()` (only inside `ON CONFLICT DO UPDATE`). */
|
|
15
|
+
allowExcluded?: boolean;
|
|
16
|
+
}>;
|
|
17
|
+
/** JSON(B) column and the key path read from it. */
|
|
18
|
+
export type JsonAccess = Readonly<{
|
|
19
|
+
base: ExprNode;
|
|
20
|
+
path: readonly string[];
|
|
21
|
+
}>;
|
|
22
|
+
/** Left-hand side of a condition: the AST node plus the attribute or JSON path it came from. */
|
|
23
|
+
export type Operand = Readonly<{
|
|
24
|
+
node: ExprNode;
|
|
25
|
+
ref?: AttributeRef;
|
|
26
|
+
json?: JsonAccess;
|
|
27
|
+
}>;
|
|
28
|
+
/** Plain conditions object of a `where` value. */
|
|
29
|
+
export type Conditions = Readonly<Record<string | symbol, unknown>>;
|
|
30
|
+
/** Where context plus value conversion (implemented by `WhereCompiler`). */
|
|
31
|
+
export type ExprConverter = Readonly<{
|
|
32
|
+
context: WhereContext;
|
|
33
|
+
toExpr(value: unknown, ref?: AttributeRef): ExprNode;
|
|
34
|
+
}>;
|
|
35
|
+
/** True for a plain conditions object (not an array, date, buffer or expression). */
|
|
36
|
+
export declare const isPlainObject: (value: unknown) => value is Conditions;
|
|
37
|
+
/** String and symbol keys of an object. */
|
|
38
|
+
export declare const ownKeys: (value: object) => readonly (string | symbol)[];
|
|
39
|
+
/** True for an `Op.*` key. */
|
|
40
|
+
export declare const isOpKey: (key: string | symbol) => key is symbol;
|
|
41
|
+
/** True when a conditions object has at least one `Op.*` key. */
|
|
42
|
+
export declare const hasOpKeys: (value: Conditions) => boolean;
|
|
43
|
+
/** Dot-separated column path (or `*`) as an AST node. */
|
|
44
|
+
export declare const columnPath: (path: string) => ExprNode;
|
|
45
|
+
/** Applies the attribute serializer, when there is one. */
|
|
46
|
+
export declare const serializeWith: (ref: AttributeRef | undefined, value: unknown) => unknown;
|
|
47
|
+
/** Text value at the path of a JSON column (`#>>`). */
|
|
48
|
+
export declare const jsonOperand: (json: JsonAccess) => Operand;
|
|
49
|
+
/** jsonb value at the path of a JSON operand (`#>`), for jsonb operators. */
|
|
50
|
+
export declare const jsonbAt: (json: JsonAccess) => ExprNode;
|
|
51
|
+
/** Wraps an operand in a cast when a type is given. */
|
|
52
|
+
export declare const withCast: (operand: Operand, type: string | undefined) => Operand;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { ExprNode } from '../sql/ast.ts';
|
|
2
|
+
import { Cast, Col, Excluded, Exists, Fn, Json, Literal, Over, SqlExpressionVisitor, Subquery, Tuple, Where } from '../expressions/methods.ts';
|
|
3
|
+
import { AttributeRef, WhereContext } from './where-support.ts';
|
|
4
|
+
export type { AttributeRef, WhereContext } from './where-support.ts';
|
|
5
|
+
/**
|
|
6
|
+
* Compiles Sequelize v6 `where` / `having` values and expression builders into AST nodes.
|
|
7
|
+
* Attribute names are resolved through the injected {@link WhereContext}; one instance can be
|
|
8
|
+
* reused for any number of conditions over the same context.
|
|
9
|
+
*/
|
|
10
|
+
export declare class WhereCompiler implements SqlExpressionVisitor<ExprNode> {
|
|
11
|
+
#private;
|
|
12
|
+
/** Attribute resolver, table alias and options. */
|
|
13
|
+
readonly context: WhereContext;
|
|
14
|
+
/**
|
|
15
|
+
* @param context - Attribute resolver, table alias and options.
|
|
16
|
+
*/
|
|
17
|
+
constructor(context: WhereContext);
|
|
18
|
+
/** True when a where value has no conditions. */
|
|
19
|
+
static isEmpty(where: unknown): boolean;
|
|
20
|
+
/** Compiles a Sequelize v6 `where` value (object, array or expression) into an AST condition. */
|
|
21
|
+
compile(where: unknown): ExprNode;
|
|
22
|
+
/** Converts an expression builder or a plain value (bound as a parameter) into an AST node. */
|
|
23
|
+
toExpr(value: unknown, ref?: AttributeRef): ExprNode;
|
|
24
|
+
/** @internal */
|
|
25
|
+
visitLiteral(value: Literal): ExprNode;
|
|
26
|
+
/** @internal */
|
|
27
|
+
visitFn(value: Fn): ExprNode;
|
|
28
|
+
/** @internal */
|
|
29
|
+
visitCol(value: Col): ExprNode;
|
|
30
|
+
/** @internal */
|
|
31
|
+
visitCast(value: Cast): ExprNode;
|
|
32
|
+
/** @internal */
|
|
33
|
+
visitJson(value: Json): ExprNode;
|
|
34
|
+
/** @internal */
|
|
35
|
+
visitWhere(value: Where): ExprNode;
|
|
36
|
+
/** @internal */
|
|
37
|
+
visitSubquery(value: Subquery): ExprNode;
|
|
38
|
+
/** @internal */
|
|
39
|
+
visitExists(value: Exists): ExprNode;
|
|
40
|
+
/** @internal */
|
|
41
|
+
visitTuple(value: Tuple): ExprNode;
|
|
42
|
+
/** @internal */
|
|
43
|
+
visitOver(value: Over): ExprNode;
|
|
44
|
+
/** @internal */
|
|
45
|
+
visitExcluded(value: Excluded): ExprNode;
|
|
46
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Over } from '../expressions/methods.ts';
|
|
2
|
+
import { ExprNode } from '../sql/ast.ts';
|
|
3
|
+
import { OperandResolver } from './operand-resolver.ts';
|
|
4
|
+
import { ExprConverter } from './where-support.ts';
|
|
5
|
+
/** Compiles window function calls (`over()`): `PARTITION BY` and `ORDER BY` items. */
|
|
6
|
+
export declare class WindowCompiler {
|
|
7
|
+
#private;
|
|
8
|
+
/**
|
|
9
|
+
* @param operands - Resolves attribute names.
|
|
10
|
+
*/
|
|
11
|
+
constructor(operands: OperandResolver);
|
|
12
|
+
/** `fn OVER (PARTITION BY ... ORDER BY ...)`. */
|
|
13
|
+
over(compiler: ExprConverter, value: Over): ExprNode;
|
|
14
|
+
}
|
package/llm/USAGE.md
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
<!-- Generated by `npm run llm:build` from docs/llm and docs/examples/llm-usage.ts. Do not edit. -->
|
|
2
|
+
# postgrelize usage guide (for LLMs and agents)
|
|
3
|
+
|
|
4
|
+
`postgrelize` is a PostgreSQL-only ORM for Node.js and TypeScript. It implements the **Sequelize v6 public API** (same names, options, return values, error classes, hook order), so Sequelize v6 knowledge and code carry over. On top of that it adds PostgreSQL features as **new** options and methods (`onConflict`, `Model.insert`, `merge`, CTEs, `copyFrom`, `listen`, advisory locks, `returningOld`). It never changes v6 semantics.
|
|
5
|
+
|
|
6
|
+
This file is generated from code that is type-checked and run in CI (`docs/examples/llm-usage.ts` and the other `docs/examples/*.ts`), so every snippet compiles and works against the current version. Types are in the package's `.d.ts` files (`node_modules/postgrelize/dist/index.d.ts`); every public item there has TSDoc.
|
|
7
|
+
|
|
8
|
+
Requirements: Node.js 20+, PostgreSQL 16/17/18, the `pg` package (peer dependency).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install postgrelize pg
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Imports read `from 'postgrelize'` (all snippets below use that). ES modules and CommonJS are both shipped. The old name `@tormozz48/postgrelize` (GitHub Packages) is deprecated.
|
|
17
|
+
|
|
18
|
+
## Imports used in the snippets
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import {
|
|
22
|
+
AllowNull,
|
|
23
|
+
Column,
|
|
24
|
+
DataTypes,
|
|
25
|
+
DatabaseError,
|
|
26
|
+
ForeignKey,
|
|
27
|
+
HasMany,
|
|
28
|
+
Model,
|
|
29
|
+
Op,
|
|
30
|
+
PrimaryKey,
|
|
31
|
+
AutoIncrement,
|
|
32
|
+
QueryTypes,
|
|
33
|
+
Sequelize,
|
|
34
|
+
Table,
|
|
35
|
+
UniqueConstraintError,
|
|
36
|
+
ValidationError,
|
|
37
|
+
col,
|
|
38
|
+
fn,
|
|
39
|
+
literal,
|
|
40
|
+
} from 'postgrelize';
|
|
41
|
+
import type { CreationOptional, InferAttributes, InferCreationAttributes } from 'postgrelize';
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Connect
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
export const openConnection = (url: string): Sequelize =>
|
|
48
|
+
new Sequelize(url, { logging: false, pool: { max: 10 } });
|
|
49
|
+
// call `await sequelize.authenticate()` to check it; `await sequelize.close()` on shutdown
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Create **one** `Sequelize` instance per database. It accepts a URI, `(database, user, password, options)`, or an options object (`host`, `port`, `database`, `username`, `password`, `ssl`, `pool`, `dialectOptions` passed to `pg`, `replication: { read, write }`, `timezone` default `'+00:00'`). `dialect` may be omitted; anything but `'postgres'` throws. Connection failures are `ConnectionError` subclasses.
|
|
53
|
+
|
|
54
|
+
## Define models
|
|
55
|
+
|
|
56
|
+
Three equivalent styles. Types: `InferAttributes`, `InferCreationAttributes`, `CreationOptional`, `ForeignKey`, `NonAttribute`.
|
|
57
|
+
|
|
58
|
+
Class + `init` (typed):
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
|
|
62
|
+
declare id: CreationOptional<number>;
|
|
63
|
+
declare email: string;
|
|
64
|
+
declare active: CreationOptional<boolean>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
User.init(
|
|
68
|
+
{
|
|
69
|
+
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
|
70
|
+
email: { type: DataTypes.STRING, allowNull: false, unique: true },
|
|
71
|
+
active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
|
|
72
|
+
},
|
|
73
|
+
{ sequelize, tableName: 'llm_users' },
|
|
74
|
+
);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`sequelize.define` (untyped attributes, returns a model class):
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const Note = sequelize.define(
|
|
81
|
+
'Note',
|
|
82
|
+
{ text: DataTypes.TEXT, meta: DataTypes.JSONB, tags: DataTypes.ARRAY(DataTypes.TEXT) },
|
|
83
|
+
{ tableName: 'llm_notes', paranoid: true },
|
|
84
|
+
);
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Decorators (TC39 or legacy signatures; register with `sequelize.addModels`):
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
@Table({ tableName: 'llm_teams' })
|
|
91
|
+
class Team extends Model {
|
|
92
|
+
@PrimaryKey
|
|
93
|
+
@AutoIncrement
|
|
94
|
+
@Column(DataTypes.INTEGER)
|
|
95
|
+
id!: number;
|
|
96
|
+
|
|
97
|
+
@AllowNull(false)
|
|
98
|
+
@Column(DataTypes.TEXT)
|
|
99
|
+
name!: string;
|
|
100
|
+
|
|
101
|
+
@HasMany(() => Player)
|
|
102
|
+
players?: Player[];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
@Table({ tableName: 'llm_players' })
|
|
106
|
+
class Player extends Model {
|
|
107
|
+
@PrimaryKey
|
|
108
|
+
@AutoIncrement
|
|
109
|
+
@Column(DataTypes.INTEGER)
|
|
110
|
+
id!: number;
|
|
111
|
+
|
|
112
|
+
@Column(DataTypes.TEXT)
|
|
113
|
+
nick!: string;
|
|
114
|
+
|
|
115
|
+
@ForeignKey(() => Team)
|
|
116
|
+
@Column(DataTypes.INTEGER)
|
|
117
|
+
teamId!: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
sequelize.addModels([Team, Player]);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Common model options: `tableName`, `freezeTableName`, `schema`, `timestamps` (default `true`: `createdAt`/`updatedAt`), `paranoid` (soft delete with `deletedAt`), `underscored`, `version` (optimistic locking, `OptimisticLockError`), `indexes`, `hooks`, `scopes`, `defaultScope`, `validate`. Data types: `DataTypes.INTEGER`, `BIGINT` (returned as string), `DECIMAL` (string), `TEXT`, `STRING(n)`, `BOOLEAN`, `DATE` (timestamptz), `UUID`, `JSONB`, `ARRAY(type)`, `ENUM(...)`, range types, `GEOMETRY` for DDL.
|
|
124
|
+
|
|
125
|
+
Create tables with `await sequelize.sync()` (tests, prototypes). For production use migrations through `sequelize.getQueryInterface()` (see Schema).
|
|
126
|
+
|
|
127
|
+
## CRUD cheat sheet
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
const ann = await User.create({ email: 'ann@example.com' });
|
|
131
|
+
await User.bulkCreate([
|
|
132
|
+
{ email: 'bob@example.com' },
|
|
133
|
+
{ email: 'eve@example.com', active: false },
|
|
134
|
+
]);
|
|
135
|
+
|
|
136
|
+
const byKey = await User.findByPk(ann.id);
|
|
137
|
+
const one = await User.findOne({ where: { email: 'bob@example.com' } });
|
|
138
|
+
const [cid, created] = await User.findOrCreate({
|
|
139
|
+
where: { email: 'cid@example.com' },
|
|
140
|
+
defaults: { active: true },
|
|
141
|
+
});
|
|
142
|
+
const all = await User.findAll({ where: { active: true }, order: [['email', 'ASC']], limit: 10 });
|
|
143
|
+
const total = await User.count();
|
|
144
|
+
|
|
145
|
+
ann.active = false; // change tracking: save() writes only changed attributes
|
|
146
|
+
await ann.save();
|
|
147
|
+
await ann.update({ email: 'ann@corp.example.com' });
|
|
148
|
+
await ann.reload();
|
|
149
|
+
await User.update({ active: true }, { where: { email: { [Op.like]: '%@example.com' } } });
|
|
150
|
+
await User.destroy({ where: { id: cid.id } }); // paranoid models soft-delete; { force: true } removes
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Also available as in v6: `findAndCountAll`, `findOrBuild`, `build` + `save`, `bulkCreate`, `restore`, `increment`/`decrement`, `instance.destroy()`, `instance.set()`/`get()`/`changed()`, `toJSON()`. `rejectOnEmpty: true` makes finders throw `EmptyResultError` instead of returning `null`. `raw: true` returns plain objects; `nest: true` nests dotted keys.
|
|
154
|
+
|
|
155
|
+
Nested creation: `Model.create(values, { include: [{ association: 'posts' }] })` where `values` contains the nested array. Nested values are not creation attributes in the types, so pass `values` as a variable, not an object literal.
|
|
156
|
+
|
|
157
|
+
## Where, operators, query options
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
const matches = await Note.findAll({
|
|
161
|
+
where: {
|
|
162
|
+
[Op.and]: [
|
|
163
|
+
{ text: { [Op.iLike]: '%pg%' } },
|
|
164
|
+
{ [Op.or]: [{ 'meta.level': 'info' }, { tags: { [Op.contains]: ['sql'] } }] },
|
|
165
|
+
{ id: { [Op.notIn]: [0, -1] } },
|
|
166
|
+
],
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
// other operators: Op.eq ne gt gte lt lte between in is not like notLike regexp overlap
|
|
170
|
+
// contains contained hasKey any all isDistinctFrom; compare columns with col('other')
|
|
171
|
+
// PostgreSQL: Op.similarTo jsonPathExists containedOrEqual trigramSimilar; full text:
|
|
172
|
+
// where(toTsVector(col('body')), Op.match, websearchToTsQuery(text)), order by tsRank()
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`Op` has all v6 operators plus PostgreSQL ones. Write JSON paths as dotted keys (`'meta.level'`) or nested objects. Compare columns with `col('name')`. `where(fn/col, Op.x, value)` builds comparisons on expressions.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
const { count, rows } = await Note.findAndCountAll({
|
|
179
|
+
attributes: ['id', 'text'],
|
|
180
|
+
order: [['id', 'DESC']],
|
|
181
|
+
limit: 1,
|
|
182
|
+
offset: 0,
|
|
183
|
+
raw: true,
|
|
184
|
+
});
|
|
185
|
+
const perTag = await Note.findAll({
|
|
186
|
+
attributes: [
|
|
187
|
+
[fn('unnest', col('tags')), 'tag'],
|
|
188
|
+
[fn('count', col('id')), 'n'],
|
|
189
|
+
],
|
|
190
|
+
group: ['tag'],
|
|
191
|
+
raw: true,
|
|
192
|
+
});
|
|
193
|
+
const sum = await Note.sum('id');
|
|
194
|
+
await Note.destroy({ where: { text: 'misc' } }); // soft delete, the row stays with deletedAt set
|
|
195
|
+
const withDeleted = await Note.findAll({ paranoid: false });
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Other options: `attributes: { include, exclude }`, `include`, `distinct`, `group`, `having`, `lock`, `transaction`, `paranoid`, `logging`, `benchmark`, scopes via `Model.scope('name')` / `Model.scope({ method: ['name', arg] })`, `findEach` / `findAll` with `limit`/`offset`, keyset pagination with `where(tuple(col('rank'), col('id')), Op.lt, tuple(3, 1))`.
|
|
199
|
+
|
|
200
|
+
## Associations and include
|
|
201
|
+
|
|
202
|
+
`hasOne`, `hasMany`, `belongsTo`, `belongsToMany` work as in v6 and generate accessors (`getPosts`, `addTag`, `createPost`, `countPosts`, ...). Declare accessor types with `declare` on the class when using TypeScript.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
const team = await Team.create({ name: 'blue' });
|
|
206
|
+
await Player.create({ nick: 'ace', teamId: team.id });
|
|
207
|
+
const teams = await Team.findAll({
|
|
208
|
+
include: [{ association: 'players', required: true, attributes: ['nick'] }],
|
|
209
|
+
});
|
|
210
|
+
// teams[0].players?.[0].nick === 'ace'; accessors such as team.getPlayers() are generated too
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Include options: `association` (or `model` + `as`), `where`, `required`, `right`, `attributes`, nested `include`, `separate`, `through`, `paranoid`, `all: true`. Eager loading uses JOINs like v6.
|
|
214
|
+
|
|
215
|
+
## Transactions
|
|
216
|
+
|
|
217
|
+
Managed (commit on resolve, rollback on throw) and explicit:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const placed = await sequelize.transaction(async (transaction) => {
|
|
221
|
+
const user = await User.create({ email: 'tx@example.com' }, { transaction });
|
|
222
|
+
await Note.create({ text: `for ${user.email}` }, { transaction });
|
|
223
|
+
return user.id; // commits when the callback resolves, rolls back when it throws
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
const manual = await sequelize.transaction();
|
|
227
|
+
try {
|
|
228
|
+
await User.update({ active: false }, { where: { id: placed }, transaction: manual });
|
|
229
|
+
await manual.commit();
|
|
230
|
+
} catch (error) {
|
|
231
|
+
await manual.rollback();
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Pass `{ transaction }` to every query that must take part. Nested `sequelize.transaction({ transaction: outer }, fn)` creates a savepoint. Options: `isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ`, `readOnly: true`, `settings: { 'app.user_id': 42 }` (SET LOCAL). Row locks: `lock: true` or `Transaction.LOCK.UPDATE`, `skipLocked`, `noWait`. Hooks after commit: `transaction.afterCommit(fn)`.
|
|
237
|
+
|
|
238
|
+
CLS (implicit transaction in callbacks, a **process-wide** switch; `AsyncLocalStorage` by default, or pass a `cls-hooked` style namespace as in v6: `Sequelize.useCLS(namespace)` stores the transaction under `namespace.get('transaction')`, and a nested `sequelize.transaction(fn)` then opens its own transaction like v6 instead of a savepoint):
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
Sequelize.useCLS(); // global switch: managed transactions now apply to queries inside the callback
|
|
242
|
+
await sequelize.transaction(async () => {
|
|
243
|
+
await User.update({ active: true }, { where: {} }); // runs in the transaction, no option needed
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
## Hooks and validation
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
const log: string[] = [];
|
|
251
|
+
User.beforeCreate((user: User) => {
|
|
252
|
+
user.email = user.email.toLowerCase();
|
|
253
|
+
});
|
|
254
|
+
User.addHook('afterUpdate', 'log-update', (user: User) => {
|
|
255
|
+
log.push(`updated ${user.id}`);
|
|
256
|
+
});
|
|
257
|
+
const mixed = await User.create({ email: 'MiXed@Example.com' });
|
|
258
|
+
await mixed.update({ active: false });
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
Hook order for `create`: `beforeValidate`, `afterValidate` (or `validationFailed`), `beforeCreate`, `afterCreate`. Updates use `beforeUpdate`/`afterUpdate`; also `beforeSave`/`afterSave`, `beforeDestroy`, `beforeUpsert`, `beforeBulkCreate`, `beforeFind`, `afterFind`. Bulk operations run row hooks only with `individualHooks: true`; `hooks: false` skips hooks for one call. Model lifecycle hooks, `beforeConnect`, `afterConnect` (once per new pooled connection, `(connection, config)`; may run queries on `connection`) and the sync hooks are executed; define hooks (`beforeDefine`, ...) are accepted but never called.
|
|
262
|
+
|
|
263
|
+
Validators in attribute definitions work as in v6 (`validate: { isEmail: true, len: [2, 50] }`, custom functions, model-level `validate`). Extra: `validate: { schema: z.email() }` and model option `validationSchema` accept any Standard Schema library (zod, valibot, arktype).
|
|
264
|
+
|
|
265
|
+
## Upserts, ON CONFLICT, RETURNING
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
const [row] = await User.upsert({ id: ann.id, email: 'ann@corp.example.com', active: true });
|
|
269
|
+
// v6 shape: [instance, null]; pass onConflict to get a real inserted/updated boolean
|
|
270
|
+
const [visit, wasInserted] = await User.upsert(
|
|
271
|
+
{ email: 'new@example.com' },
|
|
272
|
+
{ onConflict: { target: ['email'], action: { update: { active: true } } } },
|
|
273
|
+
);
|
|
274
|
+
const written = await User.insert(
|
|
275
|
+
[{ email: 'new@example.com' }, { email: 'other@example.com' }],
|
|
276
|
+
{ onConflict: { target: ['email'], action: 'nothing' } },
|
|
277
|
+
); // returns the rows that were actually inserted
|
|
278
|
+
const [changed, updated = []] = await User.update(
|
|
279
|
+
{ active: false },
|
|
280
|
+
{ where: { email: 'new@example.com' }, returning: true },
|
|
281
|
+
);
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
- v6 `upsert` returns `[instance, null]` (PostgreSQL does not say whether it inserted). Pass `onConflict` to get a boolean.
|
|
285
|
+
- `onConflict: { target: ['a', 'b'] | { constraint } | { columns, where }, action: 'nothing' | { update: ['col'] | { col: expression }, where } }` works in `upsert`, `bulkCreate`, `Model.insert`. Expressions: `excluded('col')`, `literal(...)`, `fn(...)`, `col(...)`. `Model.insert` returns instances with `wasInserted`.
|
|
286
|
+
- `returning: true` on `update` / `destroy` returns instances. `returningOld: true` adds `instance.oldValues` (PostgreSQL 18+ only).
|
|
287
|
+
- v6 `bulkCreate` options `updateOnDuplicate` with `conflictAttributes`, and `ignoreDuplicates`, still work.
|
|
288
|
+
|
|
289
|
+
More: `Model.update(values, { where, from: { d: Delivery } })` (UPDATE ... FROM), `Model.destroy({ where, using })`, `Model.insertFrom(subquery, { columns })`, `Model.merge({ source, on, whenMatched, whenNotMatched, whenNotMatchedBySource, returning })` (MERGE, PostgreSQL 17+ for `returning`):
|
|
290
|
+
|
|
291
|
+
Example: `docs/examples/merge-returning.ts` in the repository (`Stock.merge({ source: [{ sku: 'a', qty: 3 }], on: { sku: col('source.sku') }, whenMatched: { update: { qty: col('source.qty') } }, whenNotMatched: { insert: true }, returning: true })` resolves to `{ rows: [{ action, instance }] }`).
|
|
292
|
+
|
|
293
|
+
## Subqueries, CTEs, windows
|
|
294
|
+
|
|
295
|
+
`Model.subquery(findOptions)` builds an embeddable SELECT (use in `Op.in`, attributes, `exists()`). `with: { name: { query, recursive?, materialized? } }` adds CTEs to finders/`count`; `source: 'cte'` reads from one. Window functions through `over(...)`; `distinctOn`. Recursive CTE example: `docs/examples/advanced-queries.ts` (region `recursive-cte`) in the repository.
|
|
296
|
+
|
|
297
|
+
## COPY, listen/notify, locks
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
const fromArray = await Event.copyFrom([
|
|
301
|
+
{ kind: 'signup', payload: { plan: 'pro' }, tags: ['web'] },
|
|
302
|
+
{ kind: 'login', payload: null, tags: null },
|
|
303
|
+
]);
|
|
304
|
+
|
|
305
|
+
const fromStream = await Event.copyFrom(readEvents(), { columns: ['kind', 'payload'] });
|
|
306
|
+
// fromArray === 2, fromStream === 1000; createdAt / updatedAt are filled in
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
`Model.copyTo(options)` streams `COPY ... TO STDOUT` (async iterable of Buffer). `await sequelize.listen('channel', (payload) => ...)` returns an `unlisten` function; `sequelize.notify(channel, payload, { transaction })` delivers on commit. `transaction.advisoryLock(key)` / `tryAdvisoryLock(key)` take transaction-level advisory locks; `sequelize.withAdvisoryLock(key, fn)` runs `fn` in a transaction holding the lock.
|
|
310
|
+
|
|
311
|
+
## Raw queries
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
const found = (await sequelize.query('SELECT id FROM llm_users WHERE email = :email', {
|
|
315
|
+
replacements: { email: 'ann@corp.example.com' },
|
|
316
|
+
type: QueryTypes.SELECT,
|
|
317
|
+
})) as { id: number }[];
|
|
318
|
+
const ordered = await User.findAll({ order: [literal('"email" DESC NULLS LAST')] });
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
`sequelize.query(sql, { replacements | bind, type: QueryTypes.SELECT, plain, raw, transaction })`. `replacements` use `:name` or `?`, `bind` uses `$1` / `$name`. Set `type: QueryTypes.SELECT` to get the rows array directly.
|
|
322
|
+
|
|
323
|
+
## Schema, sync, migrations
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
export const up = async (queryInterface: QueryInterface): Promise<void> => {
|
|
327
|
+
await queryInterface.createTable('accounts', {
|
|
328
|
+
id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true },
|
|
329
|
+
email: { type: DataTypes.TEXT, allowNull: false, unique: true },
|
|
330
|
+
plan: { type: DataTypes.ENUM('free', 'pro'), allowNull: false, defaultValue: 'free' },
|
|
331
|
+
created_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
|
|
332
|
+
});
|
|
333
|
+
await queryInterface.createTable('sessions', {
|
|
334
|
+
id: { type: DataTypes.UUID, primaryKey: true },
|
|
335
|
+
account_id: {
|
|
336
|
+
type: DataTypes.BIGINT,
|
|
337
|
+
allowNull: false,
|
|
338
|
+
references: { model: 'accounts', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED },
|
|
339
|
+
onDelete: 'CASCADE',
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
await queryInterface.addIndex('sessions', ['account_id']);
|
|
343
|
+
await queryInterface.addColumn('accounts', 'note', { type: DataTypes.TEXT });
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
export const down = async (queryInterface: QueryInterface): Promise<void> => {
|
|
347
|
+
await queryInterface.dropTable('sessions');
|
|
348
|
+
await queryInterface.dropTable('accounts');
|
|
349
|
+
await queryInterface.dropEnum('enum_accounts_plan');
|
|
350
|
+
};
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
`sequelize.sync()` creates missing tables; `{ alter: true }` adjusts columns; `{ force: true }` drops first (never in production). `sequelize.getQueryInterface()` offers `createTable`, `dropTable`, `addColumn`, `removeColumn`, `changeColumn`, `addIndex`, `addConstraint`, `describeTable`, `showAllTables`, `tableExists`, `dropEnum`, `bulkInsert`, ... Indexes in model options support `unique`, `where` (partial), `using`, `nullsNotDistinct`. `describeTable`, `showAllTables` and `tableExists` default to `current_schema()`.
|
|
354
|
+
|
|
355
|
+
## Errors to catch
|
|
356
|
+
|
|
357
|
+
All are exported classes, as in v6.
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
const duplicate = await User.create({ email: 'new@example.com' }).catch(
|
|
361
|
+
(error: unknown) => error,
|
|
362
|
+
);
|
|
363
|
+
const invalid = await User.create({ email: null as unknown as string }).catch(
|
|
364
|
+
(error: unknown) => error,
|
|
365
|
+
);
|
|
366
|
+
const bad = await sequelize
|
|
367
|
+
.query('SELECT * FROM "no_such_table"')
|
|
368
|
+
.catch((error: unknown) => error);
|
|
369
|
+
// UniqueConstraintError and ValidationError extend ValidationError/BaseError; DatabaseError wraps
|
|
370
|
+
// any other server error: `error.parent` holds the pg error with `code`, `detail`, `constraint`
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
| Class | When |
|
|
374
|
+
| --- | --- |
|
|
375
|
+
| `ValidationError` (`.errors[]` of `ValidationErrorItem`) | validators, `allowNull`, schema validation |
|
|
376
|
+
| `UniqueConstraintError`, `ForeignKeyConstraintError`, `ExclusionConstraintError` | constraint violation (SQLSTATE 23xxx) |
|
|
377
|
+
| `DatabaseError` (`.parent`, `.sql`) | any other server error (syntax, read-only transaction, lock not available, ...) |
|
|
378
|
+
| `OptimisticLockError` | stale `version` on save |
|
|
379
|
+
| `EmptyResultError` | `rejectOnEmpty` found nothing |
|
|
380
|
+
| `ConnectionError` and subclasses (`ConnectionRefusedError`, `ConnectionTimedOutError`, `AccessDeniedError`, ...) | cannot reach or authenticate |
|
|
381
|
+
| `TimeoutError` | statement or query timeout |
|
|
382
|
+
| `BaseError` | parent of all of them |
|
|
383
|
+
|
|
384
|
+
## Top mistakes
|
|
385
|
+
|
|
386
|
+
1. **Forgetting `transaction`.** Queries without `{ transaction }` run on another connection and do not see uncommitted rows (unless CLS is on).
|
|
387
|
+
2. **Wrong package name.** Import from `'postgrelize'`; `@tormozz48/postgrelize` is the deprecated GitHub Packages name. Do not install `sequelize` next to it.
|
|
388
|
+
3. **Expecting `upsert` to report insert vs update.** It returns `[instance, null]`; use `onConflict`.
|
|
389
|
+
4. **`BIGINT` / `DECIMAL` are strings** in results. Convert explicitly.
|
|
390
|
+
5. **Using `sync()` as a migration tool in production.** Use `QueryInterface` migrations.
|
|
391
|
+
6. **Building SQL from user input** (see Security). Use `where`, `replacements`, `bind`.
|
|
392
|
+
7. **Using other dialects or v7 API** (`@sequelize/core`). Only PostgreSQL and the v6 API exist.
|
|
393
|
+
8. **Using define hooks** (`beforeDefine`, `afterDefine`, ...). They are never called.
|
|
394
|
+
9. **`Sequelize.useCLS()` is global.** Call it once at startup, not per instance.
|
|
395
|
+
10. **`create(values, { ignoreDuplicates })`** is not supported; use `onConflict: { action: 'nothing' }` or `bulkCreate(..., { ignoreDuplicates })`.
|
|
396
|
+
|
|
397
|
+
## Differences from Sequelize v6
|
|
398
|
+
|
|
399
|
+
postgrelize fixes v6 bugs on PostgreSQL instead of copying them (JSON `where` keys with special characters, `upsert` on partial unique indexes, `sync({ alter })` sequences, schema-aware `describeTable`, `Op.any` shorthand, unchecked function names and isolation levels, and more). The full list with issue numbers: <https://tormozz48.github.io/postgrelize/sequelize-issues>. Migration notes: <https://tormozz48.github.io/postgrelize/guide/migrating>.
|
|
400
|
+
|
|
401
|
+
Not available from v6: other dialects, `Model.schema('tenant')` (use the `schema` option or `search_path` via `dialectOptions: { options: '-c search_path=tenant' }`), the `searchPath` option, named/shared `ENUM` types (each `ENUM` column gets `enum_<table>_<column>`), `create({ ignoreDuplicates })`.
|
|
402
|
+
|
|
403
|
+
## PostgreSQL features that are NOT supported
|
|
404
|
+
|
|
405
|
+
Source of truth: <https://tormozz48.github.io/postgrelize/postgresql-coverage> (generated from `docs/coverage/postgresql-features.ts`). "Planned" and "out of scope" rows; most can be done with `sequelize.query()` raw SQL or `literal()`:
|
|
406
|
+
|
|
407
|
+
- **SELECT clauses**: ONLY (table inheritance)
|
|
408
|
+
- **Data types**: pg_lsn, txid_snapshot and other system types
|
|
409
|
+
- **DDL (sync and QueryInterface)**: Rules (CREATE RULE)
|
|
410
|
+
- **Session features**: Two-phase commit (PREPARE TRANSACTION)
|
|
411
|
+
- **Out of scope**: Roles, GRANT / REVOKE, default privileges; Replication setup (publications, subscriptions, slots, logical decoding); Tablespaces; VACUUM, ANALYZE, REINDEX, CLUSTER, pg_stat views; Procedural languages (PL/pgSQL bodies, DO blocks, procedures); Extension internals (writing or configuring extensions); Foreign data wrappers and foreign tables; Server configuration (ALTER SYSTEM, pg_hba.conf, event triggers)
|
|
412
|
+
|
|
413
|
+
## Security rules
|
|
414
|
+
|
|
415
|
+
- **Values are always bound** (`$1..$n`) in `where`, `create`, `update`, `upsert`, `insert`, `merge`, `replacements`, `bind`, `NOTIFY` payloads, advisory keys and `settings`. Never concatenate user input into SQL text.
|
|
416
|
+
- **Identifiers** (column, table, alias, schema, channel names) are quoted. Operators, function names, cast types, lock strengths, isolation levels and `order` directions are checked against allowlists and throw on anything else. If a column name comes from a user, map it through your own allowlist anyway.
|
|
417
|
+
- **`literal()`, raw `sequelize.query` text and string `where` are raw by design** and not escaped. Use them only with constants you wrote.
|
|
418
|
+
|
|
419
|
+
Full table of inputs and protections: <https://tormozz48.github.io/postgrelize/security>.
|
|
420
|
+
|
|
421
|
+
## Verify by running
|
|
422
|
+
|
|
423
|
+
Run the code against a real PostgreSQL (`docker run -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:17`) and read the result; do not assume a query works. Log SQL with `new Sequelize(url, { logging: console.log })`. When unsure about a signature, read the TSDoc in `node_modules/postgrelize/dist/*.d.ts` or the API reference at <https://tormozz48.github.io/postgrelize/api/>. Full documentation for LLMs: <https://tormozz48.github.io/postgrelize/llms.txt> and <https://tormozz48.github.io/postgrelize/llms-full.txt>.
|