uql-orm 0.114.4 → 0.115.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.
Files changed (84) hide show
  1. package/dist/cockroachdb/cockroachDialect.d.ts +2 -0
  2. package/dist/cockroachdb/cockroachDialect.js +5 -0
  3. package/dist/d1/d1Querier.d.ts +2 -4
  4. package/dist/d1/d1Querier.js +0 -4
  5. package/dist/d1/d1SqliteDialect.js +1 -1
  6. package/dist/dialect/abstractDialect.d.ts +17 -8
  7. package/dist/dialect/abstractDialect.js +30 -16
  8. package/dist/dialect/abstractSqlDialect.d.ts +11 -2
  9. package/dist/dialect/abstractSqlDialect.js +17 -2
  10. package/dist/dialect/mysqlLikeSqlDialect.js +2 -0
  11. package/dist/dialect/operators.d.ts +2 -2
  12. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -1
  13. package/dist/dialect/pgLikeSqlDialect.js +20 -0
  14. package/dist/entity/columnOptionsBuilder.d.ts +2 -1
  15. package/dist/entity/columnOptionsBuilder.js +3 -0
  16. package/dist/entity/metadata/definedFixture/author.d.ts +1 -1
  17. package/dist/entity/metadata/definedFixture/book.d.ts +2 -2
  18. package/dist/entity/metadata/definedFixture/folder.d.ts +1 -1
  19. package/dist/entity/metadata/definition.js +69 -30
  20. package/dist/http/api.d.ts +1 -1
  21. package/dist/http/wireQuery.js +1 -1
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.js +2 -0
  24. package/dist/migrate/ddl/tableDdl.d.ts +5 -0
  25. package/dist/migrate/ddl/tableDdl.js +9 -0
  26. package/dist/migrate/drift/driftDetector.js +2 -1
  27. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +3 -1
  28. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
  29. package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -1
  30. package/dist/migrate/introspection/postgresIntrospector.js +14 -1
  31. package/dist/migrate/introspection/tableSchemaAST.js +1 -0
  32. package/dist/migrate/policySql.d.ts +12 -0
  33. package/dist/migrate/policySql.js +74 -0
  34. package/dist/migrate/schemaChange.js +1 -0
  35. package/dist/migrate/schemaGenerator.d.ts +2 -0
  36. package/dist/migrate/schemaGenerator.js +37 -11
  37. package/dist/mongodb/mongoDialect.js +3 -1
  38. package/dist/mongodb/mongodbQuerier.d.ts +0 -2
  39. package/dist/mongodb/mongodbQuerier.js +0 -4
  40. package/dist/mssql/mssqlDialect.js +2 -0
  41. package/dist/neon/neonQuerier.d.ts +1 -2
  42. package/dist/nestjs/uqlContextInterceptor.d.ts +1 -1
  43. package/dist/nestjs/uqlContextInterceptor.js +1 -1
  44. package/dist/nestjs/uqlModule.d.ts +2 -2
  45. package/dist/nestjs/uqlModule.js +1 -1
  46. package/dist/querier/abstractQuerier.d.ts +31 -4
  47. package/dist/querier/abstractQuerier.js +120 -52
  48. package/dist/querier/abstractQuerierPool.js +2 -0
  49. package/dist/querier/abstractSqlQuerier.d.ts +16 -6
  50. package/dist/querier/abstractSqlQuerier.js +66 -6
  51. package/dist/querier/queryError.js +1 -0
  52. package/dist/schema/schemaAST.js +1 -0
  53. package/dist/schema/schemaASTBuilder.d.ts +3 -1
  54. package/dist/schema/schemaASTBuilder.js +1 -0
  55. package/dist/schema/schemaASTDiffer.js +4 -2
  56. package/dist/schema/types.d.ts +12 -4
  57. package/dist/sqlite/bindValues.d.ts +1 -1
  58. package/dist/sqlite/hranaQuerier.d.ts +2 -2
  59. package/dist/sqlite/sqliteDialect.js +2 -0
  60. package/dist/turso/tursoSessionQuerier.d.ts +2 -2
  61. package/dist/type/column.d.ts +10 -0
  62. package/dist/type/definedEntity.d.ts +9 -4
  63. package/dist/type/dialect.d.ts +13 -0
  64. package/dist/type/entity.d.ts +10 -0
  65. package/dist/type/index.d.ts +1 -0
  66. package/dist/type/index.js +1 -0
  67. package/dist/type/migration.d.ts +5 -1
  68. package/dist/type/policy.d.ts +91 -0
  69. package/dist/type/policy.js +1 -0
  70. package/dist/type/querier.d.ts +14 -0
  71. package/dist/type/querierPool.d.ts +2 -2
  72. package/dist/type/query.d.ts +18 -31
  73. package/dist/type/query.js +2 -0
  74. package/dist/util/contextRefs.d.ts +6 -0
  75. package/dist/util/contextRefs.js +5 -0
  76. package/dist/util/dialect.util.d.ts +10 -11
  77. package/dist/util/dialect.util.js +70 -56
  78. package/dist/util/fieldOption.util.js +1 -0
  79. package/dist/util/policy.util.d.ts +100 -0
  80. package/dist/util/policy.util.js +234 -0
  81. package/dist/util/uqlError.d.ts +2 -5
  82. package/dist/util/uqlError.js +2 -5
  83. package/package.json +1 -1
  84. package/skills/uql-orm/SKILL.md +23 -13
@@ -140,44 +140,53 @@ export const Book = defineEntity({
140
140
  ```
141
141
 
142
142
  - Columns are the same builders. No `!` or `?` to write: a `.nullable()` column reads `| null`, a default makes it optional on insert, `f.enum()` gives the literal union. A constructor's type argument narrows the column, a brand or a JSON payload with no runtime schema: `f.uuid<UserId>().id()`, `f.json<Settings>()`. It checks the type against the column and exists only in types; a default is written as that type. A filter then takes the branded type, and a foreign key to a branded key must carry the same brand, whether a relation or a decorated property declares it. Name its rows with an interface, `export interface Author extends InstanceType<typeof Author> {}`: hovers and errors then print `Author`, which a type alias expands.
143
- - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `hooks`, then `relations` last; only a `filters` reading through relations follows it.
143
+ - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `policies`, `hooks`, then `relations` last; only `filters` and `policies` follow it, and of two reading through relations the one chained last may read them.
144
144
  - A relation is a thunk, so entities pointing at each other can sit in any order and file. A foreign key is a plain field that a `manyToOne` names as `references`, checked against the target's key type. `relations`' second callback declares aggregate fields: aggregates over a to-many, or expressions mixing them with columns.
145
145
  - A JSON column's payload is any Standard Schema (Zod, Valibot, ArkType), typed by its output. uql never runs it, so a write is not validated.
146
146
  - A hook is a function of the row and the same second argument. Behaviour is a plain function of the row (`label(author: Author)`): a row reads back as a plain object, so a method would never be there.
147
147
 
148
- ### Filters, soft delete and tenants
148
+ ### Filters, soft delete, tenants and policies
149
149
 
150
- A filter is a named `$where` fragment applied to every read, update and delete of its entity, so never repeat it in a query.
150
+ A filter is a named `$where` fragment applied to every read, update and delete of its entity, so never repeat it in a query. A policy is what must hold whatever a call asks: tenants and row-level security.
151
151
 
152
152
  ```ts
153
- import { Entity, f, Field, withContext } from 'uql-orm';
153
+ import { $context, Entity, explainPolicies, f, Field, withContext } from 'uql-orm';
154
154
 
155
155
  declare module 'uql-orm' {
156
156
  interface UqlContext {
157
157
  tenantId?: number;
158
+ userId?: string;
159
+ role?: string;
158
160
  }
159
161
  }
160
162
 
161
163
  @Entity({
162
- filters: {
163
- active: { where: { status: 'active' }, default: false },
164
- tenant: { where: (ctx) => (ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined), security: true },
165
- },
164
+ filters: { active: { where: { status: 'active' }, default: false } },
165
+ policies: [
166
+ { allow: { ownerId: $context.userId }, check: { status: { $ne: 'void' } } },
167
+ { allow: {}, ops: ['read'], when: { role: ['auditor', 'admin'] } },
168
+ ],
166
169
  })
167
170
  export class Invoice {
168
171
  @Field(f.number().autoIncrement()) id?: number;
169
- @Field(f.number()) companyId!: number;
172
+ @Field(f.number().tenant()) companyId?: number;
173
+ @Field(f.string()) ownerId!: string;
170
174
  @Field(f.string().nullable()) status?: string | null;
171
175
  @Field(f.date().nullable().softDelete()) deletedAt?: Date | null;
172
176
  }
173
177
 
174
- await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
178
+ await withContext({ tenantId: 42, userId: 'u1' }, () => pool.findMany(Invoice, {}));
175
179
  ```
176
180
 
177
181
  - A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
178
182
  - `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
179
- - A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
180
- - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. `ops: ['insert', 'update', 'delete']` makes one hold those statements alone (anyone reads a row, only its author writes it); an update or delete is also held to the read ones. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
183
+ - A filter's `where` may read the context as data, `{ authorId: $context.userId }`, and is skipped where the context lacks a key it reads; or it may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
184
+ - `.tenant()` on one column makes it the row's tenant, read off `$context.tenantId` (`.tenant($context.orgId)` names another, which must hold the column's type): every statement is held to it, and an insert leaving it out is given it.
185
+ - A policy is data: `{ allow: where }` or `{ must: where }`, beside `ops` (`'read'`, `'insert'`, `'update'`, `'delete'`, every one where unset), `check` (what a written row must hold, the `where` where unset), `when` (context keys at a value, or one of a list) and `name`. A row is reached when any `allow` holding the statement reaches it and every `must` holds. An entity declaring no `allow` is allowed every row its `must`s (and tenant) leave; one declaring some reaches no row in a statement none of them holds. An update or delete is held to the `read` ones too. `{}` reaches every row. A policy stated once as a constant serves every entity with the fields it names.
186
+ - `explainPolicies(Invoice, 'read')` answers the `where` the querier ANDs in under the ambient context (and `check` for a write): what to look at when a read reaches no row.
187
+ - `$context.tenantId` reads the context key in a predicate, typed by `UqlContext`: once it declares keys, a misspelled one, or one in `when`, does not compile; a relation is read like any `$where` (`{ allow: { members: { userId: $context.userId } } }`). A key the context lacks or holds null matches nothing, as SQL's NULL compares: no context, no rows.
188
+ - Policies hold every read, populate, relation filter and count, and every write: an insert gets each field a policy pins to one value (`companyId`), a write setting another is refused with `UqlSecurityError`, and a check the row alone cannot settle is read back in the write's transaction (MongoDB needs `transaction()` for one; D1 refuses it). Nothing per call turns a policy off: run trusted, cross-tenant work on a pool built with `{ policies: false }`.
189
+ - `{ policies: 'native' }` on a Postgres or CockroachDB pool has the database hold them: migrations install `CREATE POLICY` (RLS enabled and forced), each transaction binds the context with `set_config`, and raw SQL is held too. Connect it as a role that is no superuser and lacks `BYPASSRLS`; a statement under a context is refused otherwise. CockroachDB takes no relation in a native policy, and a Postgres insert must be readable by the context inserting it. https://uql-orm.dev/multi-tenancy.md
181
190
 
182
191
  ## Queries
183
192
 
@@ -196,6 +205,7 @@ const users = await pool.findMany(User, {
196
205
  ```
197
206
 
198
207
  - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `estimatedCount`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Whether anything matches is `exists`, which stops at the first row, never `count(...) > 0`. Signatures: https://uql-orm.dev/querying/methods.md
208
+ - `$` marks the query language: clauses, operators, `$old`/`$new` in a trigger's predicate and `$context` reads. Field, relation and context key names never take it, and neither do a definition's or a call's options (`policies: [{ allow, ops, when }]`, `{ filters: false }`).
199
209
  - Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`, `$lock`. `$select: { password: false }` reads every field but `password`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
200
210
  - Results are narrowed to what the query selected and populated, at every depth. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing typed `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`.
201
211
  - `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
@@ -287,7 +297,7 @@ export const handler = toFetchHandler(api); // on a catch-all under /api/v1
287
297
  - What a client may do is the definition's `wire`, every operation where unset. An entity's (`@Entity({ wire: ['read', 'update'] })`, `defineEntity({ wire })`) lists what it takes of `'read'`, `'insert'`, `'update'`, `'delete'`, a subclass declaring none taking its base's; `wire: false` keeps it off every API, and `createApi` refuses one in `include`. A member's: `f.string().wire(false)` hides a field, `.wire(['read'])` makes it read-only, `.wire(['insert'])` write-once; a relation takes `wire` in its options (`rel.oneToMany(Session, { mappedBy, wire: false })`, `@OneToMany(() => Session, { mappedBy, wire: false })`). It holds wherever the entity is reached, through any relation. A write the querier would drop, to a computed field or an update of an `updatable(false)` one, is refused instead; a save may insert, so it takes the latter.
288
298
  - `read` covers every clause naming the member (`$select`, `$where`, `$sort`, `$count`, `$populate`), and a read with no `$select` leaves out what it may not read. `.eager(false)` is no guard, since a client's `$select` still reads it: hide a secret with `.wire(false)`.
289
299
  - A middleware is `(call, context, next) => next(call)`, run after the call is checked: reshape the call before `next`, or what `next` resolves to after it. The API's `use` runs on every call, and `serve(Entity, { use })` in `include` on that entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). Refuse a client with `throw new UqlRequestError('unauthorized', 401)` from `uql-orm`; any other error answers generically by its kind, or `500`.
290
- - Scope tenants with a `security` filter and `contextOf`, never with a middleware adding to `$where`. Without `contextOf` a call keeps its caller's context. On NestJS, `UqlModule.forRoot({ pool, contextOf })` does the same for your own routes.
300
+ - Scope tenants with a policy and `contextOf`, never with a middleware adding to `$where`. Without `contextOf` a call keeps its caller's context. On NestJS, `UqlModule.forRoot({ pool, contextOf })` does the same for your own routes.
291
301
  - The API serves one entity per call: no `aggregate`, upsert, stream or transaction. Write your own routes for those beside it; `toFetchHandler` answers `404` and `toExpress` falls through to `next()` on paths it does not serve.
292
302
  - The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport. It has the pool's find, `count`, `exists`, insert, save, update and delete methods and answers what they answer (rows, not `{ data }`), reading each row back by its entity, which must be registered (importing it does): a `Date` field is a `Date` and a `bigint` exact, so a cache persisting rows needs a serializer. `httpTransport` rejects with a `RequestError` carrying `status`, `kind` and `path`.
293
303
  - For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.