@guren/orm 2.0.0 → 2.2.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
@@ -935,6 +935,14 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
935
935
  * @returns A fresh QueryBuilder instance with no scopes applied
936
936
  */
937
937
  static newQueryWithoutScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
938
+ /**
939
+ * Whether this model carries a filter that every query must apply.
940
+ *
941
+ * The entry points that talk to the adapter directly check this to decide
942
+ * whether they can take the fast path; anything that returns a QueryBuilder
943
+ * goes through `newQuery()` unconditionally.
944
+ */
945
+ protected static hasScopes(): boolean;
938
946
  /**
939
947
  * Apply a named query scope.
940
948
  *
@@ -1375,6 +1383,27 @@ type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model,
1375
1383
  };
1376
1384
  /** A key that can appear in a model's create payload: a table column, or a named field its base contributes. */
1377
1385
  type CreateKey<TTable extends TableShape, TBase extends typeof Model> = keyof InferModelInsert<TTable> | keyof TCreateFor<TBase>;
1386
+ /**
1387
+ * Named fields a base class contributes to the create payload, such as
1388
+ * `AuthenticatableModel`'s virtual `password`. A plain `Model` base has no
1389
+ * declared createType, so its keys collapse to `string` — guard against that
1390
+ * collapse, or every misspelling would pass the allowlist checks below.
1391
+ */
1392
+ type BaseContributedKey<TBase extends typeof Model> = string extends keyof TCreateFor<TBase> & string ? never : keyof TCreateFor<TBase> & string;
1393
+ /** A key valid in a `fillable` allowlist: an insertable column, or a base-contributed field. */
1394
+ type FillableKey<TTable extends TableShape, TBase extends typeof Model> = (keyof InferModelInsert<TTable> & string) | BaseContributedKey<TBase>;
1395
+ /** A key of the record read back from the table. */
1396
+ type RecordKey<TTable extends TableShape> = keyof InferModelRecord<TTable> & string;
1397
+ /**
1398
+ * Accessor map keyed by TKey whose functions receive the table's inferred
1399
+ * record. A homomorphic mapped type so TypeScript infers the key union from
1400
+ * the object literal's keys — a plain `Record<string, fn>` constraint fails
1401
+ * here: the accessor functions are context-sensitive, which defers inference
1402
+ * past the point where the key type parameter falls back to its default.
1403
+ */
1404
+ type AccessorsShape<TTable extends TableShape, TKey extends string> = {
1405
+ [K in TKey]: (record: InferModelRecord<TTable>) => unknown;
1406
+ };
1378
1407
  type CreateShape<TTable extends TableShape, TBase extends typeof Model, TOptional extends keyof InferModelInsert<TTable>, TRequire extends CreateKey<TTable, TBase>> = Partial<Pick<InferModelInsert<TTable>, TOptional>> & Omit<InferModelInsert<TTable>, TOptional> & TCreateFor<TBase> & Required<Pick<InferModelInsert<TTable> & TCreateFor<TBase>, TRequire & keyof (InferModelInsert<TTable> & TCreateFor<TBase>)>>;
1379
1408
  /**
1380
1409
  * Create a table-backed model base class from a Drizzle table.
@@ -1386,16 +1415,27 @@ type CreateShape<TTable extends TableShape, TBase extends typeof Model, TOptiona
1386
1415
  * virtual field required. `optionalOnCreate` and `requireOnCreate` reshape the
1387
1416
  * inferred type without any cast.
1388
1417
  *
1418
+ * The allowlist statics (`fillable`, `hidden`, `visible`, `accessors`,
1419
+ * `appends`) can be passed here instead of declared on the subclass: the
1420
+ * option form checks every name against the table's columns (plus fields the
1421
+ * `base` contributes), so a typo is a compile error instead of a silently
1422
+ * ineffective entry. A `static` declaration on the subclass still works and
1423
+ * shadows the option, matching normal class semantics.
1424
+ *
1389
1425
  * @example
1390
- * export class Post extends defineModel(posts) {}
1426
+ * export class Post extends defineModel(posts, {
1427
+ * fillable: ['title', 'body'],
1428
+ * }) {}
1391
1429
  *
1392
1430
  * export class User extends defineModel(users, {
1393
1431
  * base: AuthenticatableModel,
1394
1432
  * optionalOnCreate: ['passwordHash'],
1395
1433
  * requireOnCreate: ['password'],
1434
+ * fillable: ['name', 'email', 'password'],
1435
+ * hidden: ['passwordHash', 'rememberToken'],
1396
1436
  * }) {}
1397
1437
  */
1398
- declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model, const TOptional extends keyof InferModelInsert<TTable> = never, const TRequire extends CreateKey<TTable, TBase> = never>(table: TTable, options?: {
1438
+ declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model, const TOptional extends keyof InferModelInsert<TTable> = never, const TRequire extends CreateKey<TTable, TBase> = never, TAccessorKey extends string = never>(table: TTable, options?: {
1399
1439
  base?: TBase;
1400
1440
  /**
1401
1441
  * Columns the model fills in itself, so callers need not pass them.
@@ -1409,6 +1449,33 @@ declare function defineModel<TTable extends TableShape, TBase extends typeof Mod
1409
1449
  * Type-level only.
1410
1450
  */
1411
1451
  requireOnCreate?: readonly TRequire[];
1452
+ /**
1453
+ * Typed form of `static fillable`: mass-assignment allowlist checked
1454
+ * against insertable columns and base-contributed fields.
1455
+ */
1456
+ fillable?: readonly FillableKey<TTable, TBase>[];
1457
+ /**
1458
+ * Typed form of `static hidden`: fields excluded from serialization,
1459
+ * checked against record columns and declared accessors.
1460
+ */
1461
+ hidden?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
1462
+ /**
1463
+ * Typed form of `static visible`: serialization allowlist, checked
1464
+ * against record columns and declared accessors.
1465
+ */
1466
+ visible?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
1467
+ /**
1468
+ * Typed form of `static accessors`: each function receives the table's
1469
+ * inferred record. Names declared here are what `appends` may reference.
1470
+ * The Record intersection rejects non-object values — with no keys to
1471
+ * infer, the mapped type alone collapses to `{}`, which admits anything.
1472
+ */
1473
+ accessors?: AccessorsShape<TTable, TAccessorKey> & Record<string, (record: InferModelRecord<TTable>) => unknown>;
1474
+ /**
1475
+ * Typed form of `static appends`: virtual attributes to serialize,
1476
+ * checked against the names declared in `accessors`.
1477
+ */
1478
+ appends?: readonly NoInfer<TAccessorKey>[];
1412
1479
  }): ModelClassWithTable<TTable, TBase, CreateShape<TTable, TBase, TOptional, TRequire>>;
1413
1480
 
1414
1481
  /**
package/dist/index.js CHANGED
@@ -866,6 +866,11 @@ var QueryBuilder = class {
866
866
  }, { trx: this.options.trx });
867
867
  }
868
868
  const simpleWhere = this.toSimpleWhereClause();
869
+ if (simpleWhere === null && this.conditions.length > 0) {
870
+ throw new Error(
871
+ `${this.modelClass.name}: this query uses conditions the configured adapter cannot express (it implements neither findManyAdvanced nor countAdvanced). Running it would drop every condition, including any global scope, and return unfiltered rows.`
872
+ );
873
+ }
869
874
  return this.adapter.findMany(this.table, {
870
875
  where: simpleWhere ?? void 0,
871
876
  orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
@@ -887,15 +892,18 @@ var QueryBuilder = class {
887
892
  if (condition.type !== "simple") {
888
893
  return null;
889
894
  }
890
- if (condition.operator === "=") {
891
- result[condition.field] = condition.value;
892
- } else if (condition.operator === "in") {
893
- result[condition.field] = condition.value;
895
+ let value;
896
+ if (condition.operator === "=" || condition.operator === "in") {
897
+ value = condition.value;
894
898
  } else if (condition.operator === "is null") {
895
- result[condition.field] = null;
899
+ value = null;
896
900
  } else {
897
901
  return null;
898
902
  }
903
+ if (condition.field in result && !Object.is(result[condition.field], value)) {
904
+ return null;
905
+ }
906
+ result[condition.field] = value;
899
907
  }
900
908
  return result;
901
909
  }
@@ -1445,8 +1453,7 @@ var Model = class _Model {
1445
1453
  * const users = await User.all()
1446
1454
  */
1447
1455
  static async all(queryOptions) {
1448
- const hasGlobalScopes = this.globalScopeRegistry && this.globalScopeRegistry.size > 0;
1449
- if (this.defaultScope || hasGlobalScopes) {
1456
+ if (this.hasScopes()) {
1450
1457
  return this.newQuery(queryOptions).get();
1451
1458
  }
1452
1459
  const table = this.resolveTable();
@@ -1468,7 +1475,7 @@ var Model = class _Model {
1468
1475
  * const userByEmail = await User.find('john@example.com', 'email')
1469
1476
  */
1470
1477
  static async find(id, key = "id", queryOptions) {
1471
- if (this.defaultScope || this.globalScopeRegistry && this.globalScopeRegistry.size > 0) {
1478
+ if (this.hasScopes()) {
1472
1479
  return this.newQuery(queryOptions).where(key, id).first();
1473
1480
  }
1474
1481
  const table = this.resolveTable();
@@ -1532,7 +1539,7 @@ var Model = class _Model {
1532
1539
  * const admin = await User.first({ role: 'admin' })
1533
1540
  */
1534
1541
  static async first(where, queryOptions) {
1535
- if (this.defaultScope || this.globalScopeRegistry && this.globalScopeRegistry.size > 0) {
1542
+ if (this.hasScopes()) {
1536
1543
  const builder = this.newQuery(queryOptions).limit(1);
1537
1544
  if (where) {
1538
1545
  builder.where(where);
@@ -1549,7 +1556,7 @@ var Model = class _Model {
1549
1556
  return record;
1550
1557
  }
1551
1558
  static where(fieldOrConditions, operatorOrValue, value) {
1552
- const builder = new QueryBuilder(this);
1559
+ const builder = this.newQuery();
1553
1560
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
1554
1561
  return builder.where(fieldOrConditions);
1555
1562
  }
@@ -1566,14 +1573,14 @@ var Model = class _Model {
1566
1573
  * @param field - Column to check for NULL
1567
1574
  */
1568
1575
  static whereNull(field) {
1569
- return new QueryBuilder(this).whereNull(field);
1576
+ return this.newQuery().whereNull(field);
1570
1577
  }
1571
1578
  /**
1572
1579
  * Start a fluent query with a WHERE NOT NULL condition.
1573
1580
  * @param field - Column to check for NOT NULL
1574
1581
  */
1575
1582
  static whereNotNull(field) {
1576
- return new QueryBuilder(this).whereNotNull(field);
1583
+ return this.newQuery().whereNotNull(field);
1577
1584
  }
1578
1585
  /**
1579
1586
  * Start a fluent query with a WHERE IN condition.
@@ -1581,7 +1588,7 @@ var Model = class _Model {
1581
1588
  * @param values - Array of values to match against
1582
1589
  */
1583
1590
  static whereIn(field, values) {
1584
- return new QueryBuilder(this).whereIn(field, values);
1591
+ return this.newQuery().whereIn(field, values);
1585
1592
  }
1586
1593
  /**
1587
1594
  * Start a fluent query with a WHERE NOT IN condition.
@@ -1589,7 +1596,7 @@ var Model = class _Model {
1589
1596
  * @param values - Array of values to exclude
1590
1597
  */
1591
1598
  static whereNotIn(field, values) {
1592
- return new QueryBuilder(this).whereNotIn(field, values);
1599
+ return this.newQuery().whereNotIn(field, values);
1593
1600
  }
1594
1601
  /**
1595
1602
  * Start a fluent query with a typed field selection.
@@ -1599,7 +1606,7 @@ var Model = class _Model {
1599
1606
  * const first = await User.select('id').first()
1600
1607
  */
1601
1608
  static select(...fields) {
1602
- return new QueryBuilder(this).select(...fields);
1609
+ return this.newQuery().select(...fields);
1603
1610
  }
1604
1611
  /**
1605
1612
  * Start a new QueryBuilder for fluent query construction.
@@ -1633,6 +1640,16 @@ var Model = class _Model {
1633
1640
  static newQueryWithoutScopes(queryOptions) {
1634
1641
  return new QueryBuilder(this, queryOptions);
1635
1642
  }
1643
+ /**
1644
+ * Whether this model carries a filter that every query must apply.
1645
+ *
1646
+ * The entry points that talk to the adapter directly check this to decide
1647
+ * whether they can take the fast path; anything that returns a QueryBuilder
1648
+ * goes through `newQuery()` unconditionally.
1649
+ */
1650
+ static hasScopes() {
1651
+ return Boolean(this.defaultScope) || Boolean(this.globalScopeRegistry && this.globalScopeRegistry.size > 0);
1652
+ }
1636
1653
  /**
1637
1654
  * Apply a named query scope.
1638
1655
  *
@@ -1648,7 +1665,7 @@ var Model = class _Model {
1648
1665
  if (!scopes || typeof scopes[name] !== "function") {
1649
1666
  throw new Error(`${this.name}: unknown scope "${name}".`);
1650
1667
  }
1651
- const builder = new QueryBuilder(this);
1668
+ const builder = this.newQuery();
1652
1669
  return scopes[name](builder);
1653
1670
  }
1654
1671
  /**
@@ -1858,8 +1875,18 @@ var Model = class _Model {
1858
1875
  * await User.orderBy('name', { status: 'active' })
1859
1876
  */
1860
1877
  static async orderBy(order, where, queryOptions) {
1861
- const table = this.resolveTable();
1862
1878
  const orderBy = normalizeOrderBy(order);
1879
+ if (this.hasScopes()) {
1880
+ const builder = this.newQuery(queryOptions);
1881
+ if (where && Object.keys(where).length > 0) {
1882
+ builder.where(where);
1883
+ }
1884
+ for (const clause of orderBy) {
1885
+ builder.orderBy(clause.column, clause.direction);
1886
+ }
1887
+ return builder.get();
1888
+ }
1889
+ const table = this.resolveTable();
1863
1890
  const options = { orderBy };
1864
1891
  if (where && Object.keys(where).length > 0) {
1865
1892
  options.where = where;
@@ -1887,6 +1914,18 @@ var Model = class _Model {
1887
1914
  * })
1888
1915
  */
1889
1916
  static async paginate(options = {}, queryOptions) {
1917
+ if (this.hasScopes()) {
1918
+ const builder = this.newQuery(queryOptions);
1919
+ if (options.where && Object.keys(options.where).length > 0) {
1920
+ builder.where(options.where);
1921
+ }
1922
+ if (options.orderBy) {
1923
+ for (const clause of normalizeOrderBy(options.orderBy)) {
1924
+ builder.orderBy(clause.column, clause.direction);
1925
+ }
1926
+ }
1927
+ return builder.paginate({ page: options.page, perPage: options.perPage });
1928
+ }
1890
1929
  const table = this.resolveTable();
1891
1930
  const adapter = this.getAdapter();
1892
1931
  const requestedPage = typeof options.page === "number" ? options.page : 1;
@@ -2514,6 +2553,11 @@ function defineModel(table, options = {}) {
2514
2553
  DefinedModel.table = table;
2515
2554
  DefinedModel.recordType = {};
2516
2555
  DefinedModel.createType = {};
2556
+ if (options.fillable) DefinedModel.fillable = [...options.fillable];
2557
+ if (options.hidden) DefinedModel.hidden = [...options.hidden];
2558
+ if (options.visible) DefinedModel.visible = [...options.visible];
2559
+ if (options.accessors) DefinedModel.accessors = options.accessors;
2560
+ if (options.appends) DefinedModel.appends = [...options.appends];
2517
2561
  return DefinedModel;
2518
2562
  }
2519
2563
  function normalizeOrderBy(order) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {