@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.js CHANGED
@@ -29,11 +29,11 @@ __export(index_exports, {
29
29
  Num: () => Num,
30
30
  One: () => One,
31
31
  Parameter: () => Parameter,
32
+ Primary: () => Primary,
32
33
  Query: () => Query,
33
34
  Str: () => Str,
34
35
  Table: () => Table,
35
- Time: () => Time,
36
- Type: () => Type
36
+ Time: () => Time
37
37
  });
38
38
  module.exports = __toCommonJS(index_exports);
39
39
 
@@ -50,8 +50,8 @@ function underscore(str) {
50
50
  function escape(value) {
51
51
  if (typeof value != "string")
52
52
  return value;
53
- 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"));
54
- return `'${value}'`;
53
+ 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"));
54
+ return `'${escaped}'`;
55
55
  }
56
56
  var {
57
57
  assign,
@@ -65,33 +65,21 @@ var {
65
65
  } = Object;
66
66
 
67
67
  // src/type/Field.ts
68
- var REGISTER = /* @__PURE__ */ new Map();
69
68
  var Field = class {
70
69
  constructor() {
71
70
  this.type = "";
72
71
  this.unique = false;
73
72
  this.nullable = false;
74
73
  this.optional = false;
74
+ this.absent = false;
75
75
  this.increment = false;
76
76
  }
77
77
  /** Real datatype of this field in database. */
78
78
  get datatype() {
79
79
  return this.type;
80
80
  }
81
- get column() {
82
- return underscore(this.property);
83
- }
84
- set column(value) {
85
- Object.defineProperty(this, "column", { value });
86
- }
87
- static new(options) {
88
- return Object.assign(new this(), options);
89
- }
90
- create(property, parent) {
91
- const field = create(this);
92
- field.parent = parent;
93
- field.property = property;
94
- return field;
81
+ static new(...options) {
82
+ return Object.assign(new this(), ...options.map((x) => typeof x === "string" ? { column: x } : x === null ? { nullable: true } : x));
95
83
  }
96
84
  /**
97
85
  * This method dictates behavior of this field when converted from a javascript context to SQL.
@@ -110,49 +98,10 @@ var Field = class {
110
98
  get(value) {
111
99
  return value;
112
100
  }
113
- raw(value) {
114
- return escape(this.set(value));
115
- }
116
- /**
117
- * This method is used to compare this field with another value in a query.
118
- *
119
- * @param acc Set of comparisons to be added to if not part of a group.
120
- */
121
- where() {
122
- const use = (op2) => (right, orEqual) => this.query.where(this, op2 + (orEqual ? "=" : ""), right);
123
- return {
124
- is: use("="),
125
- in: use("IN"),
126
- not: use("<>"),
127
- over: use(">"),
128
- under: use("<")
129
- };
130
- }
131
101
  };
132
102
  defineProperty(Field, "does", {
133
103
  value: (callback) => callback
134
104
  });
135
- function fields(from) {
136
- let fields2 = REGISTER.get(from);
137
- if (!fields2) {
138
- fields2 = /* @__PURE__ */ new Map();
139
- REGISTER.set(from, fields2);
140
- const reference = new from();
141
- for (const key in reference) {
142
- const { value } = getOwnPropertyDescriptor(reference, key);
143
- if (value instanceof Field) {
144
- const instance = value.create(key, from);
145
- from.fields.set(key, instance);
146
- freeze(instance);
147
- } else if (typeof value === "function") {
148
- value(from, key);
149
- } else throw new Error(
150
- `Entities do not support normal values, only fields. Did you forget to import \`${capitalize(typeof value)}\`?`
151
- );
152
- }
153
- }
154
- return fields2;
155
- }
156
105
 
157
106
  // src/columns/Bool.ts
158
107
  var BooleanColumn = class extends Field {
@@ -167,8 +116,9 @@ var BooleanColumn = class extends Field {
167
116
  return value ? TRUE : FALSE;
168
117
  }
169
118
  };
170
- function Bool(opts) {
171
- return Bool.Type.new(opts);
119
+ function Bool(...opts) {
120
+ return Bool.Type.new(...opts);
121
+ ;
172
122
  }
173
123
  Bool.Type = BooleanColumn;
174
124
 
@@ -180,8 +130,8 @@ var NumericColumn = class extends Field {
180
130
  return value;
181
131
  }
182
132
  };
183
- function Num(opts) {
184
- return Num.Type.new(opts);
133
+ function Num(...opts) {
134
+ return Num.Type.new(...opts);
185
135
  }
186
136
  Num.Type = NumericColumn;
187
137
 
@@ -191,9 +141,6 @@ var ForeignColumn = class extends Field {
191
141
  super(...arguments);
192
142
  this.nullable = false;
193
143
  }
194
- get column() {
195
- return underscore(this.property) + "_id";
196
- }
197
144
  set(value) {
198
145
  if (this.query?.tables.has(value))
199
146
  return value[this.reference.column];
@@ -205,12 +152,11 @@ var ForeignColumn = class extends Field {
205
152
  return table;
206
153
  }
207
154
  };
208
- function One(entity, arg2) {
209
- if (typeof arg2 === "boolean")
210
- arg2 = { nullable: arg2 };
211
- const opts = Object.assign({}, arg2);
212
- const reference = entity.fields.get("id");
213
- return One.Type.new({ entity, reference, ...opts });
155
+ function One(entity, ...options) {
156
+ const field = "id";
157
+ const column = underscore(entity.name) + "_" + field;
158
+ const reference = entity.fields.get(field);
159
+ return One.Type.new({ column, reference }, ...options, { entity });
214
160
  }
215
161
  One.Type = ForeignColumn;
216
162
 
@@ -224,8 +170,8 @@ var StringColumn = class extends Field {
224
170
  return value;
225
171
  }
226
172
  };
227
- function Str(opts) {
228
- return Str.Type.new(opts);
173
+ function Str(...opts) {
174
+ return Str.Type.new(...opts);
229
175
  }
230
176
  Str.Type = StringColumn;
231
177
 
@@ -247,8 +193,8 @@ var TimeColumn = class extends Field {
247
193
  throw "Value must be a Date, string, or 'NOW'.";
248
194
  }
249
195
  };
250
- function Time(opts) {
251
- return Time.Type.new(opts);
196
+ function Time(...opts) {
197
+ return Time.Type.new(...opts);
252
198
  }
253
199
  Time.Type = TimeColumn;
254
200
 
@@ -331,9 +277,19 @@ var Builder = class {
331
277
  }
332
278
  };
333
279
  }
280
+ compare(field) {
281
+ const use = (op2) => (right, orEqual) => this.where(field, orEqual ? op2 + "=" : op2, right);
282
+ return {
283
+ equal: use("="),
284
+ in: use("IN"),
285
+ not: use("<>"),
286
+ over: use(">"),
287
+ under: use("<")
288
+ };
289
+ }
334
290
  field(field) {
335
291
  return {
336
- ...field.where(),
292
+ ...this.compare(field),
337
293
  asc: () => {
338
294
  this.order.set(field, "asc");
339
295
  },
@@ -356,7 +312,7 @@ var Builder = class {
356
312
  return local;
357
313
  }
358
314
  use(type, arg2, ...rest) {
359
- const { fields: fields2, schema } = type;
315
+ const { fields, schema } = type;
360
316
  const { tables } = this;
361
317
  const proxy = {};
362
318
  const table = {
@@ -376,7 +332,7 @@ var Builder = class {
376
332
  table.name = schema + "." + table.name;
377
333
  }
378
334
  tables.set(proxy, table);
379
- fields2.forEach((field, key) => {
335
+ fields.forEach((field, key) => {
380
336
  field = create(field);
381
337
  field.query = this;
382
338
  field.table = table;
@@ -461,7 +417,9 @@ var Builder = class {
461
417
  for (const step of path)
462
418
  target = target[step] || (target[step] = {});
463
419
  const value2 = raw[column];
464
- target[property] = field instanceof Field ? field.get(value2) : selects instanceof Parameter ? selects.digest(value2) : value2;
420
+ if (value2 === void 0)
421
+ return;
422
+ target[property] = value2 === null && field instanceof Field && field.nullable ? null : field instanceof Field ? field.get(value2) : selects instanceof Parameter ? selects.digest(value2) : value2;
465
423
  });
466
424
  return values2;
467
425
  }
@@ -715,7 +673,7 @@ var Generator = class {
715
673
  }
716
674
  });
717
675
  const mode = optional ? "LEFT" : "INNER";
718
- const as = name + (alias ? ` ${alias}` : "");
676
+ const as = this.escape(name) + (alias ? ` ${this.escape(alias)}` : "");
719
677
  const conds = joins.map((x) => this.filter(x.left, x.op, x.right));
720
678
  output.push(`${mode} JOIN ${as} ON ${conds.join(" AND ")}`);
721
679
  }
@@ -736,7 +694,7 @@ var Generator = class {
736
694
  else
737
695
  throw new Error(`Column ${field} is not nullable.`);
738
696
  } else
739
- value = field.raw(value);
697
+ value = escape(field.set(value));
740
698
  sets.push(`${this.escape(field.column)} = ${value}`);
741
699
  }
742
700
  if (!sets.length)
@@ -788,7 +746,9 @@ var Generator = class {
788
746
  const [main] = tables.values();
789
747
  const selection = returns instanceof Map ? (
790
748
  // TODO: simplify this
791
- Array.from(returns).map(([alias, field]) => this.value(field) + ` AS "${alias}"`).join(", ")
749
+ Array.from(returns).filter(([_alias, field]) => {
750
+ return field instanceof Field ? !field.absent : true;
751
+ }).map(([alias, field]) => this.value(field) + ` AS "${alias}"`).join(", ")
792
752
  ) : returns ? this.reference(returns) : "COUNT(*)";
793
753
  return [
794
754
  "SELECT",
@@ -806,6 +766,7 @@ var Generator = class {
806
766
  return "?";
807
767
  }
808
768
  filter(left, op2, right) {
769
+ const raw = (value) => escape(left.set(value));
809
770
  if (right === null) {
810
771
  right === "NULL";
811
772
  if (op2 == "=")
@@ -815,11 +776,11 @@ var Generator = class {
815
776
  else
816
777
  throw new Error("Cannot compare NULL with " + op2);
817
778
  } else if (right instanceof Array)
818
- right = `(${right.map(left.raw, left)})`;
779
+ right = `(${right.map(raw)})`;
819
780
  else if (right instanceof Field || right instanceof Value)
820
781
  right = this.reference(right);
821
782
  else
822
- right = left.raw(right);
783
+ right = raw(right);
823
784
  return `${this.reference(left)} ${op2} ${right}`;
824
785
  }
825
786
  where() {
@@ -912,17 +873,67 @@ function pretty(sql) {
912
873
  }
913
874
  Connection.None = new NoConnection();
914
875
 
915
- // src/type/Type.ts
916
- var _Type = class _Type {
876
+ // src/type/Primary.ts
877
+ var PrimaryColumn = class extends Field {
878
+ constructor() {
879
+ super(...arguments);
880
+ this.type = "integer";
881
+ this.nullable = false;
882
+ this.optional = true;
883
+ this.primary = true;
884
+ this.unique = true;
885
+ this.increment = true;
886
+ }
887
+ init(property, parent) {
888
+ const { tableName, tableSchema, columnName } = this;
889
+ if (tableName)
890
+ parent.table = typeof tableName == "function" ? tableName(parent) : tableName;
891
+ if (tableSchema)
892
+ parent.schema = typeof tableSchema == "function" ? tableSchema(parent) : tableSchema;
893
+ if (columnName)
894
+ parent.fields.forEach((field, property2) => {
895
+ field.column = columnName(property2, field, parent);
896
+ });
897
+ }
898
+ };
899
+ function Primary(...opts) {
900
+ return PrimaryColumn.new(...opts);
901
+ }
902
+
903
+ // src/type/Table.ts
904
+ var REGISTER = /* @__PURE__ */ new Map();
905
+ var _Table = class _Table {
917
906
  constructor() {
918
907
  /**
919
908
  * Primary key of this entity.
920
909
  * May be any name in the actual database, however requred to be `id` as property of this type.
921
910
  */
922
- this.id = new Primary();
911
+ this.id = Primary();
923
912
  }
924
913
  static get fields() {
925
- return fields(this);
914
+ let fields = REGISTER.get(this);
915
+ if (!fields) {
916
+ fields = /* @__PURE__ */ new Map();
917
+ defineProperty(this, "fields", { value: fields });
918
+ const reference = new this();
919
+ for (const key in reference) {
920
+ const { value } = getOwnPropertyDescriptor(reference, key);
921
+ if (value instanceof Field) {
922
+ fields.set(key, value);
923
+ if (!value.column)
924
+ value.column = underscore(key);
925
+ } else throw new Error(
926
+ `Entities do not support normal values, only fields. Did you forget to import \`${capitalize(typeof value)}\`?`
927
+ );
928
+ }
929
+ fields.forEach((field, key) => {
930
+ field.parent = this;
931
+ field.property = key;
932
+ if (field.init)
933
+ field.init(key, this);
934
+ });
935
+ }
936
+ return fields;
926
937
  }
927
938
  static get table() {
928
939
  return this.table = underscore(this.name.replace(/\d+$/, ""));
@@ -934,7 +945,7 @@ var _Type = class _Type {
934
945
  return this.name;
935
946
  }
936
947
  static is(obj) {
937
- return typeof obj === "function" && obj.prototype instanceof _Type;
948
+ return typeof obj === "function" && obj.prototype instanceof _Table;
938
949
  }
939
950
  static insert(arg1, arg2) {
940
951
  let data;
@@ -971,32 +982,21 @@ var _Type = class _Type {
971
982
  if (typeof query == "function")
972
983
  return query(self, where) || self;
973
984
  if (typeof query == "number")
974
- where(self.id).is(query);
985
+ where(self.id).equal(query);
975
986
  else
976
987
  where(self.id).desc();
977
988
  return self;
978
989
  }).one(true);
979
990
  }
980
991
  };
981
- _Type.schema = "";
982
- var Type = _Type;
983
- var Primary = class extends Field {
984
- constructor() {
985
- super(...arguments);
986
- this.type = "integer";
987
- this.increment = true;
988
- this.optional = true;
989
- this.nullable = false;
990
- this.primary = true;
991
- this.unique = true;
992
- }
993
- };
992
+ _Table.schema = "";
993
+ var Table = _Table;
994
994
 
995
995
  // src/query/Query.ts
996
996
  function Query(factory) {
997
997
  let connection = void 0;
998
998
  function where(arg1) {
999
- if (Type.is(arg1)) {
999
+ if (Table.is(arg1)) {
1000
1000
  if (!connection)
1001
1001
  connection = arg1.connection;
1002
1002
  else if (connection !== arg1.connection)
@@ -1075,17 +1075,6 @@ function Query(factory) {
1075
1075
  }
1076
1076
  Query.Builder = Builder;
1077
1077
  Query.fn = { ...MathOps, bit: BitWise };
1078
-
1079
- // src/type/Table.ts
1080
- function Table(arg1, arg2) {
1081
- return Field.does((parent) => {
1082
- if (typeof arg1 == "string") {
1083
- const [table, schema] = arg1.split(".").reverse();
1084
- arg1 = { schema, ...arg2, table };
1085
- }
1086
- assign(parent, arg1);
1087
- });
1088
- }
1089
1078
  // Annotate the CommonJS export names for ESM import in node:
1090
1079
  0 && (module.exports = {
1091
1080
  Bool,
@@ -1097,9 +1086,9 @@ function Table(arg1, arg2) {
1097
1086
  Num,
1098
1087
  One,
1099
1088
  Parameter,
1089
+ Primary,
1100
1090
  Query,
1101
1091
  Str,
1102
1092
  Table,
1103
- Time,
1104
- Type
1093
+ Time
1105
1094
  });