@farming-labs/orm 0.0.10 → 0.0.11

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
@@ -1,4 +1,7 @@
1
- type ScalarKind = "id" | "string" | "boolean" | "datetime";
1
+ type ScalarKind = "id" | "string" | "boolean" | "datetime" | "integer" | "json";
2
+ type JsonValue = null | string | number | boolean | {
3
+ [key: string]: JsonValue;
4
+ } | JsonValue[];
2
5
  type FieldReference = `${string}.${string}`;
3
6
  type FieldConfig<Kind extends ScalarKind = ScalarKind, Nullable extends boolean = boolean> = {
4
7
  kind: Kind;
@@ -10,25 +13,33 @@ type FieldConfig<Kind extends ScalarKind = ScalarKind, Nullable extends boolean
10
13
  references?: FieldReference;
11
14
  description?: string;
12
15
  };
13
- type AnyFieldBuilder = FieldBuilder<ScalarKind, boolean>;
14
- declare class FieldBuilder<Kind extends ScalarKind, Nullable extends boolean = false> {
16
+ type ScalarValue<Kind extends ScalarKind> = Kind extends "id" ? string : Kind extends "string" ? string : Kind extends "boolean" ? boolean : Kind extends "datetime" ? Date : Kind extends "integer" ? number : JsonValue;
17
+ type AnyFieldBuilder = FieldBuilder<ScalarKind, boolean, ScalarValue<ScalarKind>>;
18
+ declare class FieldBuilder<Kind extends ScalarKind, Nullable extends boolean = false, Value = ScalarValue<Kind>> {
15
19
  readonly config: FieldConfig<Kind, Nullable>;
16
20
  readonly _tag = "field";
21
+ readonly __kind?: Kind;
22
+ readonly __nullable?: Nullable;
23
+ readonly __value?: Value;
17
24
  constructor(config: FieldConfig<Kind, Nullable>);
18
- unique(): FieldBuilder<Kind, Nullable>;
19
- nullable(): FieldBuilder<Kind, true>;
20
- default(value: unknown): FieldBuilder<Kind, Nullable>;
21
- defaultNow(): FieldBuilder<Kind, Nullable>;
22
- references(reference: FieldReference): FieldBuilder<Kind, Nullable>;
23
- map(name: string): FieldBuilder<Kind, Nullable>;
24
- describe(description: string): FieldBuilder<Kind, Nullable>;
25
+ unique(): FieldBuilder<Kind, Nullable, ScalarValue<Kind>>;
26
+ nullable(): FieldBuilder<Kind, true, Value>;
27
+ default(value: unknown): FieldBuilder<Kind, Nullable, ScalarValue<Kind>>;
28
+ defaultNow(): FieldBuilder<Kind, Nullable, ScalarValue<Kind>>;
29
+ references(reference: FieldReference): FieldBuilder<Kind, Nullable, ScalarValue<Kind>>;
30
+ map(name: string): FieldBuilder<Kind, Nullable, ScalarValue<Kind>>;
31
+ describe(description: string): FieldBuilder<Kind, Nullable, ScalarValue<Kind>>;
25
32
  }
26
- type ScalarValue<Kind extends ScalarKind> = Kind extends "id" ? string : Kind extends "string" ? string : Kind extends "boolean" ? boolean : Date;
27
- type FieldOutput<TField> = TField extends FieldBuilder<infer Kind, infer Nullable> ? Nullable extends true ? ScalarValue<Kind> | null : ScalarValue<Kind> : never;
28
- declare function id(): FieldBuilder<"id", false>;
29
- declare function string(): FieldBuilder<"string", false>;
30
- declare function boolean(): FieldBuilder<"boolean", false>;
31
- declare function datetime(): FieldBuilder<"datetime", false>;
33
+ type FieldOutput<TField> = TField extends {
34
+ __nullable?: infer Nullable;
35
+ __value?: infer Value;
36
+ } ? Nullable extends true ? Value | null : Value : never;
37
+ declare function id(): FieldBuilder<"id", false, string>;
38
+ declare function string(): FieldBuilder<"string", false, string>;
39
+ declare function boolean(): FieldBuilder<"boolean", false, boolean>;
40
+ declare function datetime(): FieldBuilder<"datetime", false, Date>;
41
+ declare function integer(): FieldBuilder<"integer", false, number>;
42
+ declare function json<TValue extends JsonValue = JsonValue>(): FieldBuilder<"json", false, TValue>;
32
43
 
33
44
  type RelationKind = "belongsTo" | "hasOne" | "hasMany" | "manyToMany";
34
45
  type RelationDefinition<Target extends string = string, Kind extends RelationKind = RelationKind> = Kind extends "manyToMany" ? {
@@ -121,7 +132,6 @@ type RelationForName<TSchema, TName extends ModelName<TSchema>, TRelationName ex
121
132
  type RelationTarget<TSchema, TName extends ModelName<TSchema>, TRelationName extends RelationName<TSchema, TName>> = RelationForName<TSchema, TName, TRelationName> extends RelationDefinition<infer Target, any> ? Extract<Target, ModelName<TSchema>> : never;
122
133
 
123
134
  type Direction = "asc" | "desc";
124
- type Primitive = string | number | boolean | Date | null;
125
135
  type Comparable = string | number | Date;
126
136
  type ValueFilter<T> = T extends string ? T | {
127
137
  eq?: T;
@@ -141,7 +151,7 @@ type ValueFilter<T> = T extends string ? T | {
141
151
  in?: T[];
142
152
  not?: T;
143
153
  };
144
- type Where<TRecord extends Record<string, Primitive>> = {
154
+ type Where<TRecord extends Record<string, unknown>> = {
145
155
  [K in keyof TRecord]?: ValueFilter<TRecord[K]>;
146
156
  } & {
147
157
  AND?: Array<Where<TRecord>>;
@@ -315,6 +325,8 @@ type ManifestUniqueLookup = {
315
325
  values: Record<string, unknown>;
316
326
  constraint?: ManifestConstraint;
317
327
  };
328
+ declare function isOperatorFilterObject(value: unknown): value is Record<string, unknown>;
329
+ declare function equalValues(left: unknown, right: unknown): boolean;
318
330
  declare function requireUniqueLookup(model: ManifestModel, where: Record<string, unknown>, operation: string): ManifestUniqueLookup;
319
331
  declare function resolveRowIdentityLookup(model: ManifestModel, row: Record<string, unknown>): ManifestUniqueLookup;
320
332
  declare function toUniqueLookupWhere(lookup: ManifestUniqueLookup): {
@@ -329,4 +341,4 @@ declare function createManifest<TSchema extends SchemaDefinition<Record<string,
329
341
  type MemoryStore<TSchema extends SchemaDefinition<any>> = Partial<Record<ModelName<TSchema>, Array<Record<string, unknown>>>>;
330
342
  declare function createMemoryDriver<TSchema extends SchemaDefinition<any>>(seed?: MemoryStore<TSchema>): OrmDriver<TSchema>;
331
343
 
332
- export { type AnyFieldBuilder, type AnyModelDefinition, type AnyRelation, type BatchTask, type ConstraintFieldName, type ConstraintFieldSet, type CountArgs, type CreateArgs, type CreateManyArgs, type DeleteArgs, type DeleteManyArgs, type DrizzleGenerationOptions, FieldBuilder, type FieldConfig, type FieldMap, type FieldOutput, type FieldReference, type FindFirstArgs, type FindManyArgs, type FindOneArgs, type FindUniqueArgs, type ManifestConstraint, type ManifestField, type ManifestModel, type ManifestUniqueLookup, type ModelClient, type ModelConstraints, type ModelDefinition, type ModelFields, type ModelForName, type ModelName, type ModelRelations, type OrmClient, type OrmDriver, type PrismaGenerationOptions, type RelationDefinition, type RelationForName, type RelationKind, type RelationMap, type RelationName, type RelationTarget, type ScalarKind, type ScalarRecord, type ScalarValue, type SchemaDefinition, type SchemaManifest, type SchemaModels, type SelectShape, type SelectedRecord, type SqlGenerationOptions, type UpdateArgs, type UpdateManyArgs, type UpsertArgs, type Where, belongsTo, boolean, createManifest, createMemoryDriver, createOrm, datetime, defineSchema, hasMany, hasOne, id, manyToMany, mergeUniqueLookupCreateData, model, renderDrizzleSchema, renderPrismaSchema, renderSafeSql, replaceGeneratedBlock, requireUniqueLookup, resolveRowIdentityLookup, string, toUniqueLookupWhere, validateUniqueLookupUpdateData };
344
+ export { type AnyFieldBuilder, type AnyModelDefinition, type AnyRelation, type BatchTask, type ConstraintFieldName, type ConstraintFieldSet, type CountArgs, type CreateArgs, type CreateManyArgs, type DeleteArgs, type DeleteManyArgs, type DrizzleGenerationOptions, FieldBuilder, type FieldConfig, type FieldMap, type FieldOutput, type FieldReference, type FindFirstArgs, type FindManyArgs, type FindOneArgs, type FindUniqueArgs, type JsonValue, type ManifestConstraint, type ManifestField, type ManifestModel, type ManifestUniqueLookup, type ModelClient, type ModelConstraints, type ModelDefinition, type ModelFields, type ModelForName, type ModelName, type ModelRelations, type OrmClient, type OrmDriver, type PrismaGenerationOptions, type RelationDefinition, type RelationForName, type RelationKind, type RelationMap, type RelationName, type RelationTarget, type ScalarKind, type ScalarRecord, type ScalarValue, type SchemaDefinition, type SchemaManifest, type SchemaModels, type SelectShape, type SelectedRecord, type SqlGenerationOptions, type UpdateArgs, type UpdateManyArgs, type UpsertArgs, type Where, belongsTo, boolean, createManifest, createMemoryDriver, createOrm, datetime, defineSchema, equalValues, hasMany, hasOne, id, integer, isOperatorFilterObject, json, manyToMany, mergeUniqueLookupCreateData, model, renderDrizzleSchema, renderPrismaSchema, renderSafeSql, replaceGeneratedBlock, requireUniqueLookup, resolveRowIdentityLookup, string, toUniqueLookupWhere, validateUniqueLookupUpdateData };
package/dist/index.js CHANGED
@@ -70,6 +70,9 @@ var FieldBuilder = class {
70
70
  this.config = config;
71
71
  }
72
72
  _tag = "field";
73
+ __kind;
74
+ __nullable;
75
+ __value;
73
76
  unique() {
74
77
  return cloneField({
75
78
  ...this.config,
@@ -142,19 +145,39 @@ function datetime() {
142
145
  unique: false
143
146
  });
144
147
  }
148
+ function integer() {
149
+ return new FieldBuilder({
150
+ kind: "integer",
151
+ nullable: false,
152
+ unique: false
153
+ });
154
+ }
155
+ function json() {
156
+ return new FieldBuilder({
157
+ kind: "json",
158
+ nullable: false,
159
+ unique: false
160
+ });
161
+ }
145
162
 
146
163
  // src/manifest.ts
147
- function equalLookupValues(left, right) {
148
- if (left instanceof Date && right instanceof Date) {
149
- return left.getTime() === right.getTime();
150
- }
151
- return Object.is(left, right);
152
- }
164
+ import { isDeepStrictEqual } from "util";
165
+ var filterOperatorKeys = /* @__PURE__ */ new Set(["eq", "contains", "in", "not", "gt", "gte", "lt", "lte"]);
153
166
  function isFilterObject(value) {
154
167
  return !!value && typeof value === "object" && !(value instanceof Date) && !Array.isArray(value);
155
168
  }
169
+ function isOperatorFilterObject(value) {
170
+ if (!isFilterObject(value)) {
171
+ return false;
172
+ }
173
+ const keys = Object.keys(value);
174
+ return keys.length > 0 && keys.every((key) => filterOperatorKeys.has(key));
175
+ }
176
+ function equalValues(left, right) {
177
+ return isDeepStrictEqual(left, right);
178
+ }
156
179
  function extractEqualityValue(filter) {
157
- if (!isFilterObject(filter)) {
180
+ if (!isOperatorFilterObject(filter)) {
158
181
  return {
159
182
  supported: true,
160
183
  value: filter
@@ -286,7 +309,7 @@ function mergeUniqueLookupCreateData(model2, createData, lookup, operation) {
286
309
  for (const field of lookup.fields) {
287
310
  const currentValue = output[field.name];
288
311
  const expectedValue = lookup.values[field.name];
289
- if (currentValue !== void 0 && !equalLookupValues(currentValue, expectedValue)) {
312
+ if (currentValue !== void 0 && !equalValues(currentValue, expectedValue)) {
290
313
  throw new Error(
291
314
  `${operation} on model "${model2.name}" requires create.${field.name} to match where.${field.name}.`
292
315
  );
@@ -298,7 +321,7 @@ function mergeUniqueLookupCreateData(model2, createData, lookup, operation) {
298
321
  function validateUniqueLookupUpdateData(model2, updateData, lookup, operation) {
299
322
  for (const field of lookup.fields) {
300
323
  const nextValue = updateData[field.name];
301
- if (nextValue !== void 0 && !equalLookupValues(nextValue, lookup.values[field.name])) {
324
+ if (nextValue !== void 0 && !equalValues(nextValue, lookup.values[field.name])) {
302
325
  throw new Error(
303
326
  `${operation} on model "${model2.name}" cannot change the conflict field "${field.name}".`
304
327
  );
@@ -415,6 +438,10 @@ function prismaType(field) {
415
438
  return "Boolean";
416
439
  case "datetime":
417
440
  return "DateTime";
441
+ case "integer":
442
+ return "Int";
443
+ case "json":
444
+ return "Json";
418
445
  }
419
446
  }
420
447
  function drizzleConstraintProperty(constraint) {
@@ -435,6 +462,12 @@ function drizzleImports(dialect, manifest) {
435
462
  const needsDate = models.some(
436
463
  (model2) => Object.values(model2.fields).some((field) => field.kind === "datetime")
437
464
  );
465
+ const needsInteger = models.some(
466
+ (model2) => Object.values(model2.fields).some((field) => field.kind === "integer")
467
+ );
468
+ const needsJson = models.some(
469
+ (model2) => Object.values(model2.fields).some((field) => field.kind === "json")
470
+ );
438
471
  const needsIndexes = models.some(
439
472
  (model2) => model2.constraints.indexes.length || model2.constraints.unique.length
440
473
  );
@@ -443,7 +476,9 @@ function drizzleImports(dialect, manifest) {
443
476
  "pgTable",
444
477
  "text",
445
478
  needsBoolean ? "boolean" : null,
479
+ needsInteger ? "integer" : null,
446
480
  needsDate ? "timestamp" : null,
481
+ needsJson ? "jsonb" : null,
447
482
  needsIndexes ? "index" : null,
448
483
  needsIndexes ? "uniqueIndex" : null
449
484
  ].filter(Boolean);
@@ -454,7 +489,9 @@ function drizzleImports(dialect, manifest) {
454
489
  "varchar",
455
490
  "text",
456
491
  needsBoolean ? "boolean" : null,
492
+ needsInteger ? "int" : null,
457
493
  needsDate ? "datetime" : null,
494
+ needsJson ? "json" : null,
458
495
  needsIndexes ? "index" : null,
459
496
  needsIndexes ? "uniqueIndex" : null
460
497
  ].filter(Boolean);
@@ -468,6 +505,10 @@ function drizzleImports(dialect, manifest) {
468
505
  ].filter(Boolean);
469
506
  }
470
507
  function drizzleColumn(field, dialect, options = {}) {
508
+ const renderDefault = () => {
509
+ if (field.defaultValue === void 0 || field.kind === "json") return "";
510
+ return `.default(${JSON.stringify(field.defaultValue)})`;
511
+ };
471
512
  if (field.kind === "id") {
472
513
  if (dialect === "mysql") {
473
514
  return `varchar("${field.column}", { length: 191 }).primaryKey()`;
@@ -477,15 +518,30 @@ function drizzleColumn(field, dialect, options = {}) {
477
518
  if (field.kind === "string") {
478
519
  if (dialect === "mysql") {
479
520
  const base = field.unique || field.references || options.indexed ? `varchar("${field.column}", { length: 191 })` : `text("${field.column}")`;
480
- return `${base}${field.nullable ? "" : ".notNull()"}${field.unique ? ".unique()" : ""}${field.defaultValue !== void 0 ? `.default(${JSON.stringify(field.defaultValue)})` : ""}`;
521
+ return `${base}${field.nullable ? "" : ".notNull()"}${field.unique ? ".unique()" : ""}${renderDefault()}`;
481
522
  }
482
- return `text("${field.column}")${field.nullable ? "" : ".notNull()"}${field.unique ? ".unique()" : ""}${field.defaultValue !== void 0 ? `.default(${JSON.stringify(field.defaultValue)})` : ""}`;
523
+ return `text("${field.column}")${field.nullable ? "" : ".notNull()"}${field.unique ? ".unique()" : ""}${renderDefault()}`;
483
524
  }
484
525
  if (field.kind === "boolean") {
485
526
  if (dialect === "sqlite") {
486
- return `integer("${field.column}", { mode: "boolean" })${field.nullable ? "" : ".notNull()"}${field.defaultValue !== void 0 ? `.default(${String(field.defaultValue)})` : ""}`;
527
+ return `integer("${field.column}", { mode: "boolean" })${field.nullable ? "" : ".notNull()"}${renderDefault()}`;
528
+ }
529
+ return `boolean("${field.column}")${field.nullable ? "" : ".notNull()"}${renderDefault()}`;
530
+ }
531
+ if (field.kind === "integer") {
532
+ if (dialect === "mysql") {
533
+ return `int("${field.column}")${field.nullable ? "" : ".notNull()"}${renderDefault()}`;
487
534
  }
488
- return `boolean("${field.column}")${field.nullable ? "" : ".notNull()"}${field.defaultValue !== void 0 ? `.default(${String(field.defaultValue)})` : ""}`;
535
+ return `integer("${field.column}")${field.nullable ? "" : ".notNull()"}${renderDefault()}`;
536
+ }
537
+ if (field.kind === "json") {
538
+ if (dialect === "pg") {
539
+ return `jsonb("${field.column}")${field.nullable ? "" : ".notNull()"}`;
540
+ }
541
+ if (dialect === "mysql") {
542
+ return `json("${field.column}")${field.nullable ? "" : ".notNull()"}`;
543
+ }
544
+ return `text("${field.column}", { mode: "json" })${field.nullable ? "" : ".notNull()"}`;
489
545
  }
490
546
  if (dialect === "mysql") {
491
547
  return `datetime("${field.column}", { mode: "date" })${field.nullable ? "" : ".notNull()"}`;
@@ -505,6 +561,14 @@ function sqlType(field, dialect, options = {}) {
505
561
  if (field.kind === "boolean") {
506
562
  return dialect === "sqlite" ? "integer" : "boolean";
507
563
  }
564
+ if (field.kind === "integer") {
565
+ return "integer";
566
+ }
567
+ if (field.kind === "json") {
568
+ if (dialect === "postgres") return "jsonb";
569
+ if (dialect === "mysql") return "json";
570
+ return "text";
571
+ }
508
572
  if (dialect === "mysql") {
509
573
  return "datetime";
510
574
  }
@@ -558,7 +622,7 @@ function renderPrismaSchema(schema, options = {}) {
558
622
  if (field.kind === "id") modifiers.push("@id");
559
623
  if (field.generated === "id") modifiers.push("@default(cuid())");
560
624
  if (field.generated === "now") modifiers.push("@default(now())");
561
- if (field.defaultValue !== void 0 && field.generated === void 0) {
625
+ if (field.defaultValue !== void 0 && field.generated === void 0 && field.kind !== "json") {
562
626
  modifiers.push(
563
627
  typeof field.defaultValue === "string" ? `@default("${field.defaultValue}")` : `@default(${String(field.defaultValue)})`
564
628
  );
@@ -716,7 +780,7 @@ function renderSafeSql(schema, options) {
716
780
  if (field.kind === "id") parts.push("primary key");
717
781
  if (!field.nullable) parts.push("not null");
718
782
  if (field.unique && field.kind !== "id") parts.push("unique");
719
- if (field.defaultValue !== void 0) {
783
+ if (field.defaultValue !== void 0 && field.kind !== "json") {
720
784
  parts.push(
721
785
  `default ${typeof field.defaultValue === "string" ? `'${field.defaultValue}'` : String(field.defaultValue)}`
722
786
  );
@@ -767,7 +831,6 @@ ${block}
767
831
 
768
832
  // src/memory.ts
769
833
  import { randomUUID } from "crypto";
770
- var isDate = (value) => value instanceof Date;
771
834
  var manifestCache = /* @__PURE__ */ new WeakMap();
772
835
  function getManifest(schema) {
773
836
  const cached = manifestCache.get(schema);
@@ -777,15 +840,15 @@ function getManifest(schema) {
777
840
  return next;
778
841
  }
779
842
  function evaluateFilter(value, filter) {
780
- if (filter === void 0 || filter === null || typeof filter !== "object" || isDate(filter) || Array.isArray(filter)) {
781
- return value === filter;
843
+ if (!isOperatorFilterObject(filter)) {
844
+ return equalValues(value, filter);
782
845
  }
783
846
  const record = filter;
784
- if ("eq" in record && value !== record.eq) return false;
785
- if ("not" in record && value === record.not) return false;
847
+ if ("eq" in record && !equalValues(value, record.eq)) return false;
848
+ if ("not" in record && equalValues(value, record.not)) return false;
786
849
  if ("in" in record) {
787
850
  const values = Array.isArray(record.in) ? record.in : [];
788
- if (!values.includes(value)) return false;
851
+ if (!values.some((candidate) => equalValues(candidate, value))) return false;
789
852
  }
790
853
  if ("contains" in record) {
791
854
  if (typeof value !== "string" || typeof record.contains !== "string") return false;
@@ -1120,9 +1183,13 @@ export {
1120
1183
  createOrm,
1121
1184
  datetime,
1122
1185
  defineSchema,
1186
+ equalValues,
1123
1187
  hasMany,
1124
1188
  hasOne,
1125
1189
  id,
1190
+ integer,
1191
+ isOperatorFilterObject,
1192
+ json,
1126
1193
  manyToMany,
1127
1194
  mergeUniqueLookupCreateData,
1128
1195
  model,