@guren/orm 2.11.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # @guren/orm
2
+
3
+ Eloquent-style models for [Guren](https://guren.dev/), a Bun-first fullstack TypeScript framework with Laravel-style conventions. A Model API over [Drizzle ORM](https://orm.drizzle.team/), with PostgreSQL, MySQL, SQLite, and Cloudflare D1 behind one interface.
4
+
5
+ ## Installation
6
+
7
+ Application code gets the Model API from [`@guren/core`](https://www.npmjs.com/package/@guren/core), which re-exports it:
8
+
9
+ ```bash
10
+ bun add @guren/core
11
+ ```
12
+
13
+ Starting a new app? Scaffold one and pick a database:
14
+
15
+ ```bash
16
+ bunx create-guren-app my-app
17
+ ```
18
+
19
+ ## Defining a model
20
+
21
+ Tables are declared with Drizzle's schema DSL, re-exported per dialect so the app pins one copy of `drizzle-orm`:
22
+
23
+ ```typescript
24
+ // db/schema.ts
25
+ import { sqliteTable, integer, text } from '@guren/orm/drizzle/sqlite'
26
+
27
+ export const posts = sqliteTable('posts', {
28
+ id: integer('id').primaryKey({ autoIncrement: true }),
29
+ title: text('title').notNull(),
30
+ body: text('body').notNull(),
31
+ published: integer('published', { mode: 'boolean' }).notNull().default(false),
32
+ createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
33
+ })
34
+ ```
35
+
36
+ ```typescript
37
+ // app/Models/Post.ts
38
+ import { defineModel } from '@guren/core'
39
+ import { posts } from '@/db/schema'
40
+
41
+ export class Post extends defineModel(posts) {
42
+ static fillable = ['title', 'body']
43
+ }
44
+ ```
45
+
46
+ ## Querying
47
+
48
+ ```typescript
49
+ const post = await Post.find(1) // null when missing
50
+ const post = await Post.findOrFail(1) // throws ModelNotFoundException (404)
51
+ const published = await Post.where('published', true).orderBy('createdAt', 'desc').get()
52
+ const page = await Post.paginate({ page: 1, perPage: 20 })
53
+ const post = await Post.create({ title: 'Hello', body: 'World' })
54
+ ```
55
+
56
+ Relationships, scopes, soft deletes, observers, accessors and mutators, and eager loading are documented in the [database guide](https://guren.dev/docs/guides/database).
57
+
58
+ ## Mass assignment
59
+
60
+ `fillable` is the allowlist, and it is always strict: primary keys are excluded, and an `AuthenticatableModel` refuses password hashes and remember tokens whatever the list says. Trusted values go through `forceCreate()` and `forceUpdate()`.
61
+
62
+ ## Dialect subpaths
63
+
64
+ | Import | Contents |
65
+ |--------|----------|
66
+ | `@guren/orm/drizzle/pg` | Drizzle's PostgreSQL schema DSL, plus `sql` |
67
+ | `@guren/orm/drizzle/mysql` | The MySQL schema DSL |
68
+ | `@guren/orm/drizzle/sqlite` | The SQLite and D1 schema DSL |
69
+
70
+ ## Documentation
71
+
72
+ [guren.dev/docs](https://guren.dev/docs)
73
+
74
+ ## License
75
+
76
+ MIT
package/dist/index.d.ts CHANGED
@@ -5,6 +5,56 @@ import { AwsDataApiPgDatabase } from "drizzle-orm/aws-data-api/pg";
5
5
  import { SQLiteBunDatabase } from "drizzle-orm/bun-sqlite";
6
6
  import { MySql2Database } from "drizzle-orm/mysql2";
7
7
  import { RDSDataClientConfig } from "@aws-sdk/client-rds-data";
8
+ //#region src/relation-definitions.d.ts
9
+ interface BaseRelationDefinition {
10
+ type: 'hasMany' | 'hasOne' | 'belongsTo' | 'belongsToMany' | 'hasManyThrough' | 'morphMany' | 'morphTo';
11
+ name: string;
12
+ related: typeof Model | (() => typeof Model | Promise<typeof Model>);
13
+ }
14
+ interface HasManyRelationDefinition extends BaseRelationDefinition {
15
+ type: 'hasMany';
16
+ foreignKey: string;
17
+ localKey: string;
18
+ }
19
+ interface HasOneRelationDefinition extends BaseRelationDefinition {
20
+ type: 'hasOne';
21
+ foreignKey: string;
22
+ localKey: string;
23
+ }
24
+ interface BelongsToRelationDefinition extends BaseRelationDefinition {
25
+ type: 'belongsTo';
26
+ foreignKey: string;
27
+ ownerKey: string;
28
+ }
29
+ interface BelongsToManyRelationDefinition extends BaseRelationDefinition {
30
+ type: 'belongsToMany';
31
+ pivotTable: unknown;
32
+ foreignPivotKey: string;
33
+ relatedPivotKey: string;
34
+ parentKey: string;
35
+ relatedKey: string;
36
+ }
37
+ interface HasManyThroughRelationDefinition extends BaseRelationDefinition {
38
+ type: 'hasManyThrough';
39
+ through: typeof Model | (() => typeof Model | Promise<typeof Model>);
40
+ firstKey: string;
41
+ secondKey: string;
42
+ localKey: string;
43
+ secondLocalKey: string;
44
+ }
45
+ type RelationDefinition = HasManyRelationDefinition | HasOneRelationDefinition | BelongsToRelationDefinition | BelongsToManyRelationDefinition | HasManyThroughRelationDefinition | MorphManyRelationDefinition | MorphToRelationDefinition;
46
+ interface MorphManyRelationDefinition extends BaseRelationDefinition {
47
+ type: 'morphMany';
48
+ morphName: string;
49
+ localKey: string;
50
+ }
51
+ interface MorphToRelationDefinition {
52
+ type: 'morphTo';
53
+ name: string;
54
+ related: undefined;
55
+ morphName: string;
56
+ }
57
+ //#endregion
8
58
  //#region src/attributes.d.ts
9
59
  /** Accessor function: transforms a record field value after reading from DB. */
10
60
  type AccessorFn<T = unknown> = (record: PlainObject) => T;
@@ -33,6 +83,10 @@ declare const SEAL_SCOPES: unique symbol;
33
83
  declare const READ_TRANSFORMS: unique symbol;
34
84
  /** Rows as the adapter read them, for the joins a relation loader makes. */
35
85
  declare const RAW_RESULTS: unique symbol;
86
+ /** Explicit physical deletion, used by SoftDeletes.forceDelete. */
87
+ declare const PHYSICAL_DELETE: unique symbol;
88
+ /** A static delete run inside the model's lifecycle, shared with SoftDeletes. */
89
+ declare const LIFECYCLE_DELETE: unique symbol;
36
90
  //#endregion
37
91
  //#region src/QueryBuilder.d.ts
38
92
  type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
@@ -244,7 +298,17 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
244
298
  * would be a supported way to bypass mass-assignment protection entirely.
245
299
  */
246
300
  [PREPARED_UPDATE](payload: PlainObject): Promise<TRecord>;
301
+ /**
302
+ * The object-where a basic adapter takes; a condition the flat object cannot
303
+ * carry (an OR group, an operator, two values on one field) refuses rather
304
+ * than writing with it dropped.
305
+ */
306
+ private simpleWhereFor;
307
+ /** Returns the adapter narrowed to the operation, so no call site needs a non-null assertion. */
308
+ private assertWritable;
309
+ private assertWriteOptions;
247
310
  delete(): Promise<number | PlainObject | void>;
311
+ [PHYSICAL_DELETE](): Promise<number | PlainObject | void>;
248
312
  /** Makes the builder awaitable, resolving to `get()`. */
249
313
  then<TResult1 = TResult[], TResult2 = never>(onfulfilled?: ((value: TResult[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
250
314
  catch<TCatch = never>(onrejected?: ((reason: unknown) => TCatch | PromiseLike<TCatch>) | null): Promise<TResult[] | TCatch>;
@@ -278,7 +342,10 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
278
342
  private assertFiltersSurvived;
279
343
  private addSimpleCondition;
280
344
  private executeQuery;
281
- /** Null when the conditions are too complex for a basic adapter's WhereClause. */
345
+ /**
346
+ * The flat object a basic adapter's WhereClause takes: `{}` for no conditions
347
+ * at all, null when the conditions are too complex for it.
348
+ */
282
349
  private toSimpleWhereClause;
283
350
  /**
284
351
  * Paths are delegated to Model.loadRelationsInto, which recurses the
@@ -311,6 +378,12 @@ interface ORMAdapterAdvanced extends ORMAdapter {
311
378
  aggregateAdvanced?(table: unknown, fn: AggregateFunction, field: string, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<unknown>;
312
379
  /** The handle a query built outside the ORM runs on: `trx`, else the open transaction, else the database. */
313
380
  executor?(queryOptions?: AdapterQueryOptions): unknown;
381
+ /**
382
+ * Makes awaiting a query built on {@link executor} wait, as the adapter's own
383
+ * calls do, for a transaction the caller is not inside where the driver shares
384
+ * one connection. Patches `query` in place and returns it.
385
+ */
386
+ queueExecution?<TQuery>(query: TQuery, queryOptions?: AdapterQueryOptions): TQuery;
314
387
  /** `SELECT field, COUNT(*) ... GROUP BY field` under `conditions`. */
315
388
  countByAdvanced?(table: unknown, field: string, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<Array<{
316
389
  key: unknown;
@@ -537,9 +610,8 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
537
610
  /** A query with no global scopes applied, `defaultScope` included. */
538
611
  static withoutGlobalScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
539
612
  /**
540
- * Both write entry points fork on `hasScopes()`, and only one arm reaches a
541
- * builder — so the refusal belongs above the fork, where every adapter is
542
- * still in scope.
613
+ * Ahead of the `updating`/`deleting` hooks, which must not fire for a write
614
+ * that is refused; the builder repeats the check for its own callers.
543
615
  */
544
616
  private static assertFiltersSurvived;
545
617
  /** Applies hidden/visible filtering, accessors and appends. */
@@ -689,6 +761,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
689
761
  static forceUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
690
762
  protected static runUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean): Promise<TRecordFor<T>>;
691
763
  static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
764
+ /**
765
+ * Runs `write` between the `deleting` and `deleted` events, for `delete()`
766
+ * and the SoftDeletes overrides. Symbol-keyed and kept out of the package
767
+ * entry point; each caller checks its own adapter capability first.
768
+ */
769
+ static [LIFECYCLE_DELETE](this: typeof Model, where: object, method: string, write: () => Promise<number | PlainObject | void>): Promise<number | PlainObject | void>;
692
770
  /**
693
771
  * A raw Drizzle builder starting at `select().from(table)`. Carries no model
694
772
  * scopes, casts or accessors.
@@ -777,54 +855,6 @@ interface TransactionModelScope<T extends typeof Model> {
777
855
  delete(where: WhereClauseFor<T>): Promise<number | PlainObject | void>;
778
856
  paginate(options?: PaginateOptions<TRecordFor<T>>): Promise<PaginatedResult<TRecordFor<T>>>;
779
857
  }
780
- interface BaseRelationDefinition {
781
- type: 'hasMany' | 'hasOne' | 'belongsTo' | 'belongsToMany' | 'hasManyThrough' | 'morphMany' | 'morphTo';
782
- name: string;
783
- related: typeof Model | (() => typeof Model | Promise<typeof Model>);
784
- }
785
- interface HasManyRelationDefinition extends BaseRelationDefinition {
786
- type: 'hasMany';
787
- foreignKey: string;
788
- localKey: string;
789
- }
790
- interface HasOneRelationDefinition extends BaseRelationDefinition {
791
- type: 'hasOne';
792
- foreignKey: string;
793
- localKey: string;
794
- }
795
- interface BelongsToRelationDefinition extends BaseRelationDefinition {
796
- type: 'belongsTo';
797
- foreignKey: string;
798
- ownerKey: string;
799
- }
800
- interface BelongsToManyRelationDefinition extends BaseRelationDefinition {
801
- type: 'belongsToMany';
802
- pivotTable: unknown;
803
- foreignPivotKey: string;
804
- relatedPivotKey: string;
805
- parentKey: string;
806
- relatedKey: string;
807
- }
808
- interface HasManyThroughRelationDefinition extends BaseRelationDefinition {
809
- type: 'hasManyThrough';
810
- through: typeof Model | (() => typeof Model | Promise<typeof Model>);
811
- firstKey: string;
812
- secondKey: string;
813
- localKey: string;
814
- secondLocalKey: string;
815
- }
816
- type RelationDefinition = HasManyRelationDefinition | HasOneRelationDefinition | BelongsToRelationDefinition | BelongsToManyRelationDefinition | HasManyThroughRelationDefinition | MorphManyRelationDefinition | MorphToRelationDefinition;
817
- interface MorphManyRelationDefinition extends BaseRelationDefinition {
818
- type: 'morphMany';
819
- morphName: string;
820
- localKey: string;
821
- }
822
- interface MorphToRelationDefinition {
823
- type: 'morphTo';
824
- name: string;
825
- related: undefined;
826
- morphName: string;
827
- }
828
858
  type HasManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
829
859
  type BelongsToRelationResult<T extends typeof Model> = TRecordFor<T> | null;
830
860
  type HasManyRecord<TRecord extends PlainObject> = TRecord[];
@@ -952,7 +982,7 @@ interface SoftDeletesStatic {
952
982
  */
953
983
  declare function SoftDeletes<TBase extends typeof Model>(Base: TBase): TBase & SoftDeletesStatic;
954
984
  //#endregion
955
- //#region src/adapters/drizzle-adapter.d.ts
985
+ //#region src/adapters/drizzle-types.d.ts
956
986
  type DrizzleLikeSelect = {
957
987
  where?: (clause: unknown) => DrizzleLikeSelect;
958
988
  orderBy?: (...clauses: unknown[]) => DrizzleLikeSelect;
@@ -990,6 +1020,8 @@ type DrizzleDatabase = {
990
1020
  run?(query: unknown): Promise<unknown>;
991
1021
  transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
992
1022
  };
1023
+ //#endregion
1024
+ //#region src/adapters/drizzle-adapter.d.ts
993
1025
  declare const DrizzleAdapter: ORMAdapterAdvanced & {
994
1026
  configure(db: DrizzleDatabase): void;
995
1027
  getDatabase<TDatabase extends DrizzleDatabase = DrizzleDatabase>(): TDatabase;