@guren/orm 2.3.0 → 2.4.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/dist/index.d.ts CHANGED
@@ -45,6 +45,15 @@ interface GroupCondition {
45
45
  }
46
46
  /** A where condition - either simple or grouped. */
47
47
  type WhereCondition = SimpleCondition | GroupCondition;
48
+ /**
49
+ * Callback receiving a nested builder to compose a parenthesized
50
+ * condition group, mirroring Laravel's `where(fn ($q) => ...)`.
51
+ *
52
+ * Only the conditions added on the nested builder are read back —
53
+ * ordering, limits, eager loads, and terminal calls made inside the
54
+ * callback are not part of the group.
55
+ */
56
+ type WhereGroupCallback<TRecord extends PlainObject = PlainObject> = (query: QueryBuilder<TRecord>) => void;
48
57
  /** Options carried by the QueryBuilder for query execution. */
49
58
  interface QueryBuilderOptions {
50
59
  orderBy: Array<{
@@ -93,11 +102,19 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
93
102
  /**
94
103
  * Add a where condition (AND).
95
104
  *
96
- * Supports three calling signatures:
105
+ * Supports four calling signatures:
97
106
  * - `where(field, value)` - equality check
98
107
  * - `where(field, operator, value)` - comparison
99
108
  * - `where(object)` - multiple equality conditions
109
+ * - `where(callback)` - parenthesized condition group, AND-ed with the rest
110
+ *
111
+ * @example
112
+ * // (title LIKE ? OR excerpt LIKE ?) AND published = true
113
+ * await Post.where((q) => {
114
+ * q.where('title', 'like', pattern).orWhere('excerpt', 'like', pattern)
115
+ * }).where('published', true)
100
116
  */
117
+ where(callback: WhereGroupCallback<TRecord>): this;
101
118
  where<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
102
119
  where<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
103
120
  where(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
@@ -106,7 +123,10 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
106
123
  *
107
124
  * Same overloads as `where()`, but joins with OR logic.
108
125
  * Creates an OR group containing the new condition(s).
126
+ * With a callback, the group's conditions are parenthesized as a whole:
127
+ * `(preceding conditions) OR (callback group)`.
109
128
  */
129
+ orWhere(callback: WhereGroupCallback<TRecord>): this;
110
130
  orWhere<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
111
131
  orWhere<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
112
132
  orWhere(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
@@ -272,6 +292,16 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
272
292
  getConditions(): WhereCondition[];
273
293
  /** Get the internal query options (used by adapters). */
274
294
  getOptions(): QueryBuilderOptions;
295
+ /**
296
+ * Run a grouping callback against a nested builder, fold the collected
297
+ * conditions into a single node, and push it joined by `boolean`.
298
+ *
299
+ * The nested builder intentionally skips global scopes (`defaultScope`,
300
+ * SoftDeletes): the outer builder already carries them, and re-applying
301
+ * them inside every group would duplicate — or, inside an OR group,
302
+ * weaken — their filters.
303
+ */
304
+ private pushCallbackGroup;
275
305
  private addSimpleCondition;
276
306
  private executeQuery;
277
307
  /**
@@ -934,6 +964,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
934
964
  * .limit(10)
935
965
  * .get()
936
966
  */
967
+ static where<T extends typeof Model>(this: T, callback: WhereGroupCallback<TRecordFor<T>>): QueryBuilder<TRecordFor<T>>;
937
968
  static where<T extends typeof Model>(this: T, conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
938
969
  static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, value: unknown): QueryBuilder<TRecordFor<T>>;
939
970
  static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
@@ -1332,6 +1363,7 @@ interface TransactionModelScope<T extends typeof Model> {
1332
1363
  find(id: unknown): Promise<TRecordFor<T> | null>;
1333
1364
  findOrFail(id: unknown): Promise<TRecordFor<T>>;
1334
1365
  first(where?: WhereClauseFor<T>): Promise<TRecordFor<T> | null>;
1366
+ where(callback: WhereGroupCallback<TRecordFor<T>>): QueryBuilder<TRecordFor<T>>;
1335
1367
  where(conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
1336
1368
  where(field: FieldFor<T>, value: unknown): QueryBuilder<TRecordFor<T>>;
1337
1369
  where(field: FieldFor<T>, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
@@ -1653,15 +1685,12 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
1653
1685
  * Translates an array of QueryBuilder WhereConditions into a single
1654
1686
  * Drizzle ORM condition expression.
1655
1687
  *
1656
- * The top-level conditions are joined with AND. OR conditions are
1657
- * represented as GroupCondition nodes with `boolean: 'or'`.
1658
- *
1659
- * When an OR group is encountered, it creates:
1660
- * AND(previous_conditions, OR(previous_and_block, or_conditions))
1661
- *
1662
- * This matches the typical SQL builder behavior where:
1688
+ * The list's sequential semantics — top-level conditions AND together,
1689
+ * an OR group folds everything before it into the OR, so
1663
1690
  * .where('a', 1).where('b', 2).orWhere('c', 3)
1664
- * produces: (a = 1 AND b = 2) OR (c = 3)
1691
+ * produces `(a = 1 AND b = 2) OR (c = 3)` — are applied by
1692
+ * `normalizeConditionSequence` (shared with QueryBuilder's grouping
1693
+ * callbacks), leaving only a flat-join tree to render here.
1665
1694
  *
1666
1695
  * @param table - The Drizzle table object
1667
1696
  * @param conditions - Array of WhereCondition objects from QueryBuilder
@@ -1694,7 +1723,7 @@ interface PostgresDatabase {
1694
1723
  closeDatabase(): Promise<void>;
1695
1724
  configureOrm(): Promise<void>;
1696
1725
  seedDatabase(): Promise<void>;
1697
- /** Drops the public schema (and the drizzle tracker schema) so migrations can be re-applied from scratch. */
1726
+ /** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
1698
1727
  resetDatabase(): Promise<void>;
1699
1728
  /** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
1700
1729
  migrationStatus(): Promise<MigrationStatusEntry[]>;
@@ -1721,7 +1750,7 @@ interface MySqlDatabase {
1721
1750
  closeDatabase(): Promise<void>;
1722
1751
  configureOrm(): Promise<void>;
1723
1752
  seedDatabase(): Promise<void>;
1724
- /** Drops every table and view (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
1753
+ /** Drops every table and view (including the drizzle migration tracker), then re-applies migrations — same end state as `guren db:reset`. */
1725
1754
  resetDatabase(): Promise<void>;
1726
1755
  /** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
1727
1756
  migrationStatus(): Promise<MigrationStatusEntry[]>;
@@ -1747,7 +1776,7 @@ interface SqliteDatabase {
1747
1776
  closeDatabase(): Promise<void>;
1748
1777
  configureOrm(): Promise<void>;
1749
1778
  seedDatabase(): Promise<void>;
1750
- /** Drops every table and view (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
1779
+ /** Drops every table and view (including the drizzle migration tracker), then re-applies migrations — same end state as `guren db:reset`. */
1751
1780
  resetDatabase(): Promise<void>;
1752
1781
  /** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
1753
1782
  migrationStatus(): Promise<MigrationStatusEntry[]>;
@@ -1828,7 +1857,7 @@ interface AwsDataApiDatabase {
1828
1857
  closeDatabase(): Promise<void>;
1829
1858
  configureOrm(): Promise<void>;
1830
1859
  seedDatabase(): Promise<void>;
1831
- /** Drops the public schema (and the drizzle tracker schema) so migrations can be re-applied from scratch. */
1860
+ /** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
1832
1861
  resetDatabase(): Promise<void>;
1833
1862
  /** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
1834
1863
  migrationStatus(): Promise<MigrationStatusEntry[]>;
@@ -1879,4 +1908,4 @@ declare function serializeRecord(record: PlainObject, options: {
1879
1908
  /** Serialize an array of records. */
1880
1909
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1881
1910
 
1882
- export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
1911
+ export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
package/dist/index.js CHANGED
@@ -21,6 +21,28 @@ import { and as and2, asc, count, desc, eq as eq2, inArray as inArray2, isNull a
21
21
 
22
22
  // src/adapters/drizzle-conditions.ts
23
23
  import { and, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or } from "drizzle-orm";
24
+
25
+ // src/where-conditions.ts
26
+ function normalizeConditionSequence(conditions) {
27
+ let pending = [];
28
+ for (const condition of conditions) {
29
+ if (!(condition.type === "group" && condition.boolean === "or")) {
30
+ pending.push(condition);
31
+ continue;
32
+ }
33
+ if (condition.conditions.length === 0) continue;
34
+ const andBlock = combine("and", pending);
35
+ pending = [combine("or", andBlock ? [andBlock, ...condition.conditions] : condition.conditions)];
36
+ }
37
+ return combine("and", pending);
38
+ }
39
+ function combine(boolean, parts) {
40
+ if (parts.length === 0) return null;
41
+ if (parts.length === 1) return parts[0];
42
+ return { type: "group", boolean, conditions: [...parts] };
43
+ }
44
+
45
+ // src/adapters/drizzle-conditions.ts
24
46
  function resolveColumn(table, field) {
25
47
  const tableRecord = table;
26
48
  const column = tableRecord[field];
@@ -84,45 +106,8 @@ function buildSingleCondition(table, condition) {
84
106
  return buildGroupCondition(table, condition);
85
107
  }
86
108
  function buildDrizzleConditions(table, conditions) {
87
- if (conditions.length === 0) {
88
- return void 0;
89
- }
90
- let currentAnd = [];
91
- let result;
92
- for (const condition of conditions) {
93
- if (condition.type === "group" && condition.boolean === "or") {
94
- const orParts = condition.conditions.map((c) => buildSingleCondition(table, c)).filter((c) => c !== void 0);
95
- if (orParts.length > 0) {
96
- const andBlock = combineAnd(currentAnd, result);
97
- if (andBlock) {
98
- result = or(andBlock, ...orParts);
99
- } else {
100
- result = orParts.length === 1 ? orParts[0] : or(...orParts);
101
- }
102
- currentAnd = [];
103
- }
104
- } else {
105
- const built = buildSingleCondition(table, condition);
106
- if (built) {
107
- currentAnd.push(built);
108
- }
109
- }
110
- }
111
- return combineAnd(currentAnd, result);
112
- }
113
- function combineAnd(andParts, existing) {
114
- const all = [];
115
- if (existing) {
116
- all.push(existing);
117
- }
118
- all.push(...andParts);
119
- if (all.length === 0) {
120
- return void 0;
121
- }
122
- if (all.length === 1) {
123
- return all[0];
124
- }
125
- return and(...all);
109
+ const normalized = normalizeConditionSequence(conditions);
110
+ return normalized ? buildSingleCondition(table, normalized) : void 0;
126
111
  }
127
112
 
128
113
  // src/adapters/drizzle-adapter.ts
@@ -519,7 +504,7 @@ var ModelNotFoundException = class extends Error {
519
504
 
520
505
  // src/QueryBuilder.ts
521
506
  var PREPARED_UPDATE = /* @__PURE__ */ Symbol("guren.orm.preparedUpdate");
522
- var QueryBuilder = class {
507
+ var QueryBuilder = class _QueryBuilder {
523
508
  conditions = [];
524
509
  options = { orderBy: [] };
525
510
  modelClass;
@@ -535,6 +520,10 @@ var QueryBuilder = class {
535
520
  this.options.trx = options.trx;
536
521
  }
537
522
  where(fieldOrConditions, operatorOrValue, value) {
523
+ if (typeof fieldOrConditions === "function") {
524
+ this.pushCallbackGroup(fieldOrConditions, "and");
525
+ return this;
526
+ }
538
527
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
539
528
  for (const [key, val] of Object.entries(fieldOrConditions)) {
540
529
  if (val !== void 0) {
@@ -552,6 +541,10 @@ var QueryBuilder = class {
552
541
  return this;
553
542
  }
554
543
  orWhere(fieldOrConditions, operatorOrValue, value) {
544
+ if (typeof fieldOrConditions === "function") {
545
+ this.pushCallbackGroup(fieldOrConditions, "or");
546
+ return this;
547
+ }
555
548
  const orConditions = [];
556
549
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
557
550
  for (const [key, val] of Object.entries(fieldOrConditions)) {
@@ -879,6 +872,23 @@ var QueryBuilder = class {
879
872
  getOptions() {
880
873
  return { ...this.options };
881
874
  }
875
+ /**
876
+ * Run a grouping callback against a nested builder, fold the collected
877
+ * conditions into a single node, and push it joined by `boolean`.
878
+ *
879
+ * The nested builder intentionally skips global scopes (`defaultScope`,
880
+ * SoftDeletes): the outer builder already carries them, and re-applying
881
+ * them inside every group would duplicate — or, inside an OR group,
882
+ * weaken — their filters.
883
+ */
884
+ pushCallbackGroup(callback, boolean) {
885
+ const nested = new _QueryBuilder(this.modelClass, { trx: this.options.trx });
886
+ callback(nested);
887
+ const grouped = normalizeConditionSequence(nested.conditions);
888
+ if (!grouped) return;
889
+ const needsWrap = boolean === "or" || grouped.type === "group" && grouped.boolean === "or";
890
+ this.conditions.push(needsWrap ? { type: "group", boolean, conditions: [grouped] } : grouped);
891
+ }
882
892
  addSimpleCondition(field, operator, value) {
883
893
  this.conditions.push({
884
894
  type: "simple",
@@ -1190,6 +1200,9 @@ var Model = class _Model {
1190
1200
  */
1191
1201
  static inTransaction(trx) {
1192
1202
  const where = (fieldOrConditions, operatorOrValue, value) => {
1203
+ if (typeof fieldOrConditions === "function") {
1204
+ return this.newQuery({ trx }).where(fieldOrConditions);
1205
+ }
1193
1206
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
1194
1207
  return this.newQuery({ trx }).where(fieldOrConditions);
1195
1208
  }
@@ -1612,6 +1625,9 @@ var Model = class _Model {
1612
1625
  }
1613
1626
  static where(fieldOrConditions, operatorOrValue, value) {
1614
1627
  const builder = this.newQuery();
1628
+ if (typeof fieldOrConditions === "function") {
1629
+ return builder.where(fieldOrConditions);
1630
+ }
1615
1631
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
1616
1632
  return builder.where(fieldOrConditions);
1617
1633
  }
@@ -3200,6 +3216,7 @@ function createPostgresDatabase(options) {
3200
3216
  await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
3201
3217
  });
3202
3218
  migrations.reset();
3219
+ await migrations.get();
3203
3220
  }
3204
3221
  async function migrationStatus() {
3205
3222
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
@@ -3366,6 +3383,7 @@ function createMySqlDatabase(options) {
3366
3383
  }
3367
3384
  });
3368
3385
  migrations.reset();
3386
+ await migrations.get();
3369
3387
  }
3370
3388
  async function migrationStatus() {
3371
3389
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
@@ -3487,6 +3505,7 @@ function createSqliteDatabase(options) {
3487
3505
  sqliteClient.exec("PRAGMA foreign_keys = ON;");
3488
3506
  }
3489
3507
  migrations.reset();
3508
+ await migrations.get();
3490
3509
  },
3491
3510
  async migrationStatus() {
3492
3511
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
@@ -3689,6 +3708,7 @@ function createAwsDataApiDatabase(options) {
3689
3708
  await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
3690
3709
  });
3691
3710
  migrations.reset();
3711
+ await migrations.get();
3692
3712
  }
3693
3713
  async function migrationStatus() {
3694
3714
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {