@expressive/sql 0.3.0 → 0.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.mjs CHANGED
@@ -11,8 +11,8 @@ function underscore(str) {
11
11
  function escape(value) {
12
12
  if (typeof value != "string")
13
13
  return value;
14
- value = value.replace(/[\0\n\r\b\t\\'"\x1a]/g, (s) => s == "\0" ? "\\0" : s == "\n" ? "\\n" : s == "\r" ? "\\r" : s == "\b" ? "\\b" : s == " " ? "\\t" : s == "" ? "\\Z" : "\\" + s).replace(/[\x00-\x1f\x7f-\x9f]/g, (ch) => "\\x" + ch.charCodeAt(0).toString(16).padStart(2, "0"));
15
- return `'${value}'`;
14
+ const escaped = value.replace(/[\0\n\r\b\t\\'"\x1a]/g, (s) => s == "\0" ? "\\0" : s == "\n" ? "\\n" : s == "\r" ? "\\r" : s == "\b" ? "\\b" : s == " " ? "\\t" : s == "" ? "\\Z" : "\\" + s).replace(/[\x00-\x1f\x7f-\x9f]/g, (ch) => "\\x" + ch.charCodeAt(0).toString(16).padStart(2, "0"));
15
+ return `'${escaped}'`;
16
16
  }
17
17
  var {
18
18
  assign,
@@ -26,33 +26,21 @@ var {
26
26
  } = Object;
27
27
 
28
28
  // src/type/Field.ts
29
- var REGISTER = /* @__PURE__ */ new Map();
30
29
  var Field = class {
31
30
  constructor() {
32
31
  this.type = "";
33
32
  this.unique = false;
34
33
  this.nullable = false;
35
34
  this.optional = false;
35
+ this.absent = false;
36
36
  this.increment = false;
37
37
  }
38
38
  /** Real datatype of this field in database. */
39
39
  get datatype() {
40
40
  return this.type;
41
41
  }
42
- get column() {
43
- return underscore(this.property);
44
- }
45
- set column(value) {
46
- Object.defineProperty(this, "column", { value });
47
- }
48
- static new(options) {
49
- return Object.assign(new this(), options);
50
- }
51
- create(property, parent) {
52
- const field = create(this);
53
- field.parent = parent;
54
- field.property = property;
55
- return field;
42
+ static new(...options) {
43
+ return Object.assign(new this(), ...options.map((x) => typeof x === "string" ? { column: x } : x === null ? { nullable: true } : x));
56
44
  }
57
45
  /**
58
46
  * This method dictates behavior of this field when converted from a javascript context to SQL.
@@ -71,49 +59,10 @@ var Field = class {
71
59
  get(value) {
72
60
  return value;
73
61
  }
74
- raw(value) {
75
- return escape(this.set(value));
76
- }
77
- /**
78
- * This method is used to compare this field with another value in a query.
79
- *
80
- * @param acc Set of comparisons to be added to if not part of a group.
81
- */
82
- where() {
83
- const use = (op2) => (right, orEqual) => this.query.where(this, op2 + (orEqual ? "=" : ""), right);
84
- return {
85
- is: use("="),
86
- in: use("IN"),
87
- not: use("<>"),
88
- over: use(">"),
89
- under: use("<")
90
- };
91
- }
92
62
  };
93
63
  defineProperty(Field, "does", {
94
64
  value: (callback) => callback
95
65
  });
96
- function fields(from) {
97
- let fields2 = REGISTER.get(from);
98
- if (!fields2) {
99
- fields2 = /* @__PURE__ */ new Map();
100
- REGISTER.set(from, fields2);
101
- const reference = new from();
102
- for (const key in reference) {
103
- const { value } = getOwnPropertyDescriptor(reference, key);
104
- if (value instanceof Field) {
105
- const instance = value.create(key, from);
106
- from.fields.set(key, instance);
107
- freeze(instance);
108
- } else if (typeof value === "function") {
109
- value(from, key);
110
- } else throw new Error(
111
- `Entities do not support normal values, only fields. Did you forget to import \`${capitalize(typeof value)}\`?`
112
- );
113
- }
114
- }
115
- return fields2;
116
- }
117
66
 
118
67
  // src/columns/Bool.ts
119
68
  var BooleanColumn = class extends Field {
@@ -128,8 +77,9 @@ var BooleanColumn = class extends Field {
128
77
  return value ? TRUE : FALSE;
129
78
  }
130
79
  };
131
- function Bool(opts) {
132
- return Bool.Type.new(opts);
80
+ function Bool(...opts) {
81
+ return Bool.Type.new(...opts);
82
+ ;
133
83
  }
134
84
  Bool.Type = BooleanColumn;
135
85
 
@@ -141,8 +91,8 @@ var NumericColumn = class extends Field {
141
91
  return value;
142
92
  }
143
93
  };
144
- function Num(opts) {
145
- return Num.Type.new(opts);
94
+ function Num(...opts) {
95
+ return Num.Type.new(...opts);
146
96
  }
147
97
  Num.Type = NumericColumn;
148
98
 
@@ -152,9 +102,6 @@ var ForeignColumn = class extends Field {
152
102
  super(...arguments);
153
103
  this.nullable = false;
154
104
  }
155
- get column() {
156
- return underscore(this.property) + "_id";
157
- }
158
105
  set(value) {
159
106
  if (this.query?.tables.has(value))
160
107
  return value[this.reference.column];
@@ -166,12 +113,11 @@ var ForeignColumn = class extends Field {
166
113
  return table;
167
114
  }
168
115
  };
169
- function One(entity, arg2) {
170
- if (typeof arg2 === "boolean")
171
- arg2 = { nullable: arg2 };
172
- const opts = Object.assign({}, arg2);
173
- const reference = entity.fields.get("id");
174
- return One.Type.new({ entity, reference, ...opts });
116
+ function One(entity, ...options) {
117
+ const field = "id";
118
+ const column = underscore(entity.name) + "_" + field;
119
+ const reference = entity.fields.get(field);
120
+ return One.Type.new({ column, reference }, ...options, { entity });
175
121
  }
176
122
  One.Type = ForeignColumn;
177
123
 
@@ -185,8 +131,8 @@ var StringColumn = class extends Field {
185
131
  return value;
186
132
  }
187
133
  };
188
- function Str(opts) {
189
- return Str.Type.new(opts);
134
+ function Str(...opts) {
135
+ return Str.Type.new(...opts);
190
136
  }
191
137
  Str.Type = StringColumn;
192
138
 
@@ -208,8 +154,8 @@ var TimeColumn = class extends Field {
208
154
  throw "Value must be a Date, string, or 'NOW'.";
209
155
  }
210
156
  };
211
- function Time(opts) {
212
- return Time.Type.new(opts);
157
+ function Time(...opts) {
158
+ return Time.Type.new(...opts);
213
159
  }
214
160
  Time.Type = TimeColumn;
215
161
 
@@ -292,9 +238,19 @@ var Builder = class {
292
238
  }
293
239
  };
294
240
  }
241
+ compare(field) {
242
+ const use = (op2) => (right, orEqual) => this.where(field, orEqual ? op2 + "=" : op2, right);
243
+ return {
244
+ equal: use("="),
245
+ in: use("IN"),
246
+ not: use("<>"),
247
+ over: use(">"),
248
+ under: use("<")
249
+ };
250
+ }
295
251
  field(field) {
296
252
  return {
297
- ...field.where(),
253
+ ...this.compare(field),
298
254
  asc: () => {
299
255
  this.order.set(field, "asc");
300
256
  },
@@ -317,7 +273,7 @@ var Builder = class {
317
273
  return local;
318
274
  }
319
275
  use(type, arg2, ...rest) {
320
- const { fields: fields2, schema } = type;
276
+ const { fields, schema } = type;
321
277
  const { tables } = this;
322
278
  const proxy = {};
323
279
  const table = {
@@ -337,7 +293,7 @@ var Builder = class {
337
293
  table.name = schema + "." + table.name;
338
294
  }
339
295
  tables.set(proxy, table);
340
- fields2.forEach((field, key) => {
296
+ fields.forEach((field, key) => {
341
297
  field = create(field);
342
298
  field.query = this;
343
299
  field.table = table;
@@ -422,7 +378,9 @@ var Builder = class {
422
378
  for (const step of path)
423
379
  target = target[step] || (target[step] = {});
424
380
  const value2 = raw[column];
425
- target[property] = field instanceof Field ? field.get(value2) : selects instanceof Parameter ? selects.digest(value2) : value2;
381
+ if (value2 === void 0)
382
+ return;
383
+ target[property] = value2 === null && field instanceof Field && field.nullable ? null : field instanceof Field ? field.get(value2) : selects instanceof Parameter ? selects.digest(value2) : value2;
426
384
  });
427
385
  return values2;
428
386
  }
@@ -676,7 +634,7 @@ var Generator = class {
676
634
  }
677
635
  });
678
636
  const mode = optional ? "LEFT" : "INNER";
679
- const as = name + (alias ? ` ${alias}` : "");
637
+ const as = this.escape(name) + (alias ? ` ${this.escape(alias)}` : "");
680
638
  const conds = joins.map((x) => this.filter(x.left, x.op, x.right));
681
639
  output.push(`${mode} JOIN ${as} ON ${conds.join(" AND ")}`);
682
640
  }
@@ -697,7 +655,7 @@ var Generator = class {
697
655
  else
698
656
  throw new Error(`Column ${field} is not nullable.`);
699
657
  } else
700
- value = field.raw(value);
658
+ value = escape(field.set(value));
701
659
  sets.push(`${this.escape(field.column)} = ${value}`);
702
660
  }
703
661
  if (!sets.length)
@@ -749,7 +707,9 @@ var Generator = class {
749
707
  const [main] = tables.values();
750
708
  const selection = returns instanceof Map ? (
751
709
  // TODO: simplify this
752
- Array.from(returns).map(([alias, field]) => this.value(field) + ` AS "${alias}"`).join(", ")
710
+ Array.from(returns).filter(([_alias, field]) => {
711
+ return field instanceof Field ? !field.absent : true;
712
+ }).map(([alias, field]) => this.value(field) + ` AS "${alias}"`).join(", ")
753
713
  ) : returns ? this.reference(returns) : "COUNT(*)";
754
714
  return [
755
715
  "SELECT",
@@ -767,6 +727,7 @@ var Generator = class {
767
727
  return "?";
768
728
  }
769
729
  filter(left, op2, right) {
730
+ const raw = (value) => escape(left.set(value));
770
731
  if (right === null) {
771
732
  right === "NULL";
772
733
  if (op2 == "=")
@@ -776,11 +737,11 @@ var Generator = class {
776
737
  else
777
738
  throw new Error("Cannot compare NULL with " + op2);
778
739
  } else if (right instanceof Array)
779
- right = `(${right.map(left.raw, left)})`;
740
+ right = `(${right.map(raw)})`;
780
741
  else if (right instanceof Field || right instanceof Value)
781
742
  right = this.reference(right);
782
743
  else
783
- right = left.raw(right);
744
+ right = raw(right);
784
745
  return `${this.reference(left)} ${op2} ${right}`;
785
746
  }
786
747
  where() {
@@ -873,17 +834,67 @@ function pretty(sql) {
873
834
  }
874
835
  Connection.None = new NoConnection();
875
836
 
876
- // src/type/Type.ts
877
- var _Type = class _Type {
837
+ // src/type/Primary.ts
838
+ var PrimaryColumn = class extends Field {
839
+ constructor() {
840
+ super(...arguments);
841
+ this.type = "integer";
842
+ this.nullable = false;
843
+ this.optional = true;
844
+ this.primary = true;
845
+ this.unique = true;
846
+ this.increment = true;
847
+ }
848
+ init(property, parent) {
849
+ const { tableName, tableSchema, columnName } = this;
850
+ if (tableName)
851
+ parent.table = typeof tableName == "function" ? tableName(parent) : tableName;
852
+ if (tableSchema)
853
+ parent.schema = typeof tableSchema == "function" ? tableSchema(parent) : tableSchema;
854
+ if (columnName)
855
+ parent.fields.forEach((field, property2) => {
856
+ field.column = columnName(property2, field, parent);
857
+ });
858
+ }
859
+ };
860
+ function Primary(...opts) {
861
+ return PrimaryColumn.new(...opts);
862
+ }
863
+
864
+ // src/type/Table.ts
865
+ var REGISTER = /* @__PURE__ */ new Map();
866
+ var _Table = class _Table {
878
867
  constructor() {
879
868
  /**
880
869
  * Primary key of this entity.
881
870
  * May be any name in the actual database, however requred to be `id` as property of this type.
882
871
  */
883
- this.id = new Primary();
872
+ this.id = Primary();
884
873
  }
885
874
  static get fields() {
886
- return fields(this);
875
+ let fields = REGISTER.get(this);
876
+ if (!fields) {
877
+ fields = /* @__PURE__ */ new Map();
878
+ defineProperty(this, "fields", { value: fields });
879
+ const reference = new this();
880
+ for (const key in reference) {
881
+ const { value } = getOwnPropertyDescriptor(reference, key);
882
+ if (value instanceof Field) {
883
+ fields.set(key, value);
884
+ if (!value.column)
885
+ value.column = underscore(key);
886
+ } else throw new Error(
887
+ `Entities do not support normal values, only fields. Did you forget to import \`${capitalize(typeof value)}\`?`
888
+ );
889
+ }
890
+ fields.forEach((field, key) => {
891
+ field.parent = this;
892
+ field.property = key;
893
+ if (field.init)
894
+ field.init(key, this);
895
+ });
896
+ }
897
+ return fields;
887
898
  }
888
899
  static get table() {
889
900
  return this.table = underscore(this.name.replace(/\d+$/, ""));
@@ -895,7 +906,7 @@ var _Type = class _Type {
895
906
  return this.name;
896
907
  }
897
908
  static is(obj) {
898
- return typeof obj === "function" && obj.prototype instanceof _Type;
909
+ return typeof obj === "function" && obj.prototype instanceof _Table;
899
910
  }
900
911
  static insert(arg1, arg2) {
901
912
  let data;
@@ -932,32 +943,21 @@ var _Type = class _Type {
932
943
  if (typeof query == "function")
933
944
  return query(self, where) || self;
934
945
  if (typeof query == "number")
935
- where(self.id).is(query);
946
+ where(self.id).equal(query);
936
947
  else
937
948
  where(self.id).desc();
938
949
  return self;
939
950
  }).one(true);
940
951
  }
941
952
  };
942
- _Type.schema = "";
943
- var Type = _Type;
944
- var Primary = class extends Field {
945
- constructor() {
946
- super(...arguments);
947
- this.type = "integer";
948
- this.increment = true;
949
- this.optional = true;
950
- this.nullable = false;
951
- this.primary = true;
952
- this.unique = true;
953
- }
954
- };
953
+ _Table.schema = "";
954
+ var Table = _Table;
955
955
 
956
956
  // src/query/Query.ts
957
957
  function Query(factory) {
958
958
  let connection = void 0;
959
959
  function where(arg1) {
960
- if (Type.is(arg1)) {
960
+ if (Table.is(arg1)) {
961
961
  if (!connection)
962
962
  connection = arg1.connection;
963
963
  else if (connection !== arg1.connection)
@@ -1036,17 +1036,6 @@ function Query(factory) {
1036
1036
  }
1037
1037
  Query.Builder = Builder;
1038
1038
  Query.fn = { ...MathOps, bit: BitWise };
1039
-
1040
- // src/type/Table.ts
1041
- function Table(arg1, arg2) {
1042
- return Field.does((parent) => {
1043
- if (typeof arg1 == "string") {
1044
- const [table, schema] = arg1.split(".").reverse();
1045
- arg1 = { schema, ...arg2, table };
1046
- }
1047
- assign(parent, arg1);
1048
- });
1049
- }
1050
1039
  export {
1051
1040
  Bool,
1052
1041
  Builder,
@@ -1057,9 +1046,9 @@ export {
1057
1046
  Num,
1058
1047
  One,
1059
1048
  Parameter,
1049
+ Primary,
1060
1050
  Query,
1061
1051
  Str,
1062
1052
  Table,
1063
- Time,
1064
- Type
1053
+ Time
1065
1054
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressive/sql",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Query builder and ORM",
5
5
  "license": "ISC",
6
6
  "publishConfig": {
@@ -24,6 +24,7 @@
24
24
  },
25
25
  "scripts": {
26
26
  "build": "tsup src/index.ts --dts --format esm,cjs",
27
+ "lint": "tsc --noEmit",
27
28
  "test": "vitest run"
28
29
  }
29
30
  }