@asla/yoursql 0.3.1 → 0.5.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/mod.js CHANGED
@@ -34,6 +34,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
34
34
  };
35
35
 
36
36
  /**
37
+ * 获取对象数组中的 key 的集合
37
38
  * @public
38
39
  * @param keepUndefinedKey - 是否保留值为 undefined 的 key
39
40
  */
@@ -52,9 +53,146 @@ function getObjectListKeys(objectList, keepUndefinedKey) {
52
53
  keys.add(k);
53
54
  }
54
55
  }
55
- return Array.from(keys);
56
+ return keys;
57
+ }
58
+ /**
59
+ * 生成 WHERE 语句
60
+ * @public
61
+ * ```ts
62
+ *
63
+ * ```
64
+ */
65
+ function where(condition, type = "AND") {
66
+ if (!condition)
67
+ return "";
68
+ return genCondition(condition, "WHERE", type);
69
+ }
70
+ /**
71
+ *
72
+ * 生成 HAVING 语句
73
+ * @public
74
+ */
75
+ function having(condition, type = "AND") {
76
+ if (!condition)
77
+ return "";
78
+ return genCondition(condition, "HAVING", type);
79
+ }
80
+ function genCondition(condition, statement, type = "AND") {
81
+ if (typeof condition === "function")
82
+ condition = condition();
83
+ type = " " + type + " ";
84
+ let sql = "";
85
+ if (typeof condition === "string")
86
+ sql += "\n" + statement + " " + condition;
87
+ else {
88
+ if (condition.length)
89
+ sql += "\n" + statement + " " + condition[0];
90
+ for (let i = 1; i < condition.length; i++)
91
+ sql += type + condition[i];
92
+ }
93
+ return sql;
94
+ }
95
+ /**
96
+ * @public
97
+ * ```ts
98
+ * selectColumns({c1: true, c2: "count(*)", c3: "column"}) // "c1,count(*) AS c2,column as c3"
99
+ * selectColumns(["c1", "count(*) AS c2", "column as c3"]) // "c1,count(*) AS c2,column as c3"
100
+ * ```
101
+ */
102
+ function selectColumns(columns) {
103
+ let sql = "";
104
+ if (columns instanceof Array) {
105
+ if (columns.length)
106
+ sql += columns[0];
107
+ else
108
+ throw new Error("没有选择任何列");
109
+ for (let i = 1; i < columns.length; i++)
110
+ sql += "," + columns[i];
111
+ }
112
+ else {
113
+ const keys = Object.keys(columns);
114
+ if (keys.length === 0)
115
+ throw new Error("没有选择任何列");
116
+ let k = keys[0];
117
+ let v = columns[k];
118
+ if (typeof v === "string")
119
+ sql += v + " AS " + k;
120
+ else
121
+ sql += k;
122
+ for (let i = 1; i < keys.length; i++) {
123
+ k = keys[i];
124
+ v = columns[k];
125
+ sql += ",";
126
+ if (typeof v === "string")
127
+ sql += v + " AS " + k;
128
+ else
129
+ sql += k;
130
+ }
131
+ }
132
+ return sql;
133
+ }
134
+ /**
135
+ * 生成 ORDER BY 语句, d
136
+ * @public
137
+ * ```ts
138
+ * // 以下生成 "\nORDER BY age DESC NULLS FIRST,num ASC"
139
+ * orderBy("age DESC NULLS FIRST,num ASC");
140
+ * orderBy(["age DESC NULLS FIRST", "num ASC"]);
141
+ * orderBy([
142
+ * { key: "age", asc: false, nullLast: false },
143
+ * { key: "num", asc: true },
144
+ * ]);
145
+ * orderBy({ age: "DESC NULLS FIRST", num: true });
146
+ *
147
+ * orderBy([]) // ""
148
+ * orderBy({}) // ""
149
+ * ```
150
+ */
151
+ function orderBy(by) {
152
+ if (typeof by === "function")
153
+ by = by();
154
+ let sql = "";
155
+ if (typeof by === "string") {
156
+ if (!by)
157
+ return sql;
158
+ sql += "\nORDER BY " + by;
159
+ }
160
+ else if (by instanceof Array) {
161
+ if (by.length) {
162
+ sql += "\nORDER BY " + handlerOrderValue(by[0]);
163
+ for (let i = 1; i < by.length; i++)
164
+ sql += "," + handlerOrderValue(by[i]);
165
+ }
166
+ }
167
+ else {
168
+ let keys = Object.keys(by);
169
+ if (keys.length) {
170
+ let key = keys[0];
171
+ sql += "\nORDER BY " + key + " " + by[key];
172
+ for (let i = 1; i < keys.length; i++) {
173
+ key = keys[i];
174
+ sql += "," + key + " ";
175
+ if (typeof by[key] === "string")
176
+ sql += by[key];
177
+ else
178
+ sql += by[key] ? "ASC" : "DESC";
179
+ }
180
+ }
181
+ }
182
+ return sql;
183
+ }
184
+ function handlerOrderValue(value) {
185
+ if (typeof value === "string")
186
+ return value;
187
+ else {
188
+ let str = value.key + " " + (value.asc ? "ASC" : "DESC");
189
+ if (value.nullLast !== undefined)
190
+ str += value.nullLast ? " NULLS LAST" : " NULLS FIRST";
191
+ return str;
192
+ }
56
193
  }
57
194
 
195
+ var _SqlQueryStatement_sql;
58
196
  /**
59
197
  * 可选择项。可以是 table、查询结果等,它能被 select 语句选择
60
198
  * @example
@@ -116,16 +254,22 @@ class DbTable extends SqlSelectable {
116
254
  */
117
255
  class SqlQueryStatement extends SqlSelectable {
118
256
  constructor(sql, columns) {
257
+ if (sql instanceof SqlQueryStatement) {
258
+ columns = sql.columns;
259
+ sql = __classPrivateFieldGet(sql, _SqlQueryStatement_sql, "f");
260
+ }
119
261
  super(columns);
120
- this.sql = sql;
262
+ _SqlQueryStatement_sql.set(this, void 0);
263
+ __classPrivateFieldSet(this, _SqlQueryStatement_sql, sql, "f");
121
264
  }
122
265
  toString() {
123
- return this.sql;
266
+ return __classPrivateFieldGet(this, _SqlQueryStatement_sql, "f");
124
267
  }
125
268
  toSelect() {
126
269
  return "(" + this.toString() + ")";
127
270
  }
128
271
  }
272
+ _SqlQueryStatement_sql = new WeakMap();
129
273
 
130
274
  var _SqlRaw_value, _YourValuesAs_asName, _YourValuesAs_valuesStr, _YourValuesAs_sql;
131
275
  /**
@@ -229,7 +373,7 @@ class SqlValuesCreator {
229
373
  throw new Error("objectList 不能是空数组");
230
374
  let keys;
231
375
  if (!keys_types) {
232
- keys = getObjectListKeys(objectList, keepUndefinedKey);
376
+ keys = Array.from(getObjectListKeys(objectList, keepUndefinedKey));
233
377
  }
234
378
  else if (keys_types instanceof Array) {
235
379
  keys = keys_types;
@@ -394,35 +538,99 @@ const pgSqlTransformer = new Map([
394
538
  [Date, (value) => SqlValuesCreator.string(value.toISOString())],
395
539
  ]);
396
540
 
397
- function genOderBy(orderBy, orderNullRule) {
398
- let select = [];
399
- let v;
400
- for (const key of Object.keys(orderBy)) {
401
- v = orderBy[key];
402
- switch (v) {
403
- case "ASC":
404
- break;
405
- case "DESC":
406
- break;
407
- default:
408
- throw new Error("orderBy 只能是 ASE 或 DESC. 当前值:" + String(v));
409
- }
410
- select.push(key + " " + v);
541
+ var _Selection_instances, _a, _Selection_sql, _Selection_join;
542
+ class AfterSelectImpl extends SqlQueryStatement {
543
+ constructor(sql, columns) {
544
+ super(sql, columns);
411
545
  }
412
- let sql = "\nORDER BY " + select.join(", ");
413
- if (orderNullRule) {
414
- switch (orderNullRule) {
415
- case "FIRST":
416
- break;
417
- case "LAST":
418
- break;
419
- default:
420
- throw new Error("orderNullRule 只能是 FIRST 或 LAST. 当前值:" + String(orderNullRule));
421
- }
422
- sql += "NULLS " + orderNullRule;
546
+ where(param) {
547
+ return new AfterSelectImpl(this.toString() + where(param), this.columns);
548
+ }
549
+ groupBy(columns) {
550
+ let sql = this.toString();
551
+ if (typeof columns === "string")
552
+ sql += " GROUP BY " + columns;
553
+ else
554
+ sql += " GROUP BY " + columns.join(",");
555
+ return new AfterSelectImpl(sql, this.columns);
556
+ }
557
+ having(param) {
558
+ return new AfterSelectImpl(this.toString() + having(param), this.columns);
423
559
  }
560
+ orderBy(param) {
561
+ return new AfterSelectImpl(this.toString() + orderBy(param), this.columns);
562
+ }
563
+ limit(limit, offset) {
564
+ let sql = this.toString();
565
+ if (limit)
566
+ sql += "\nLIMIT " + limit;
567
+ if (offset)
568
+ sql += "\nOFFSET " + offset;
569
+ return new SqlQueryStatement(sql, Array.from(this.columns));
570
+ }
571
+ }
572
+ function fromAs(selectable, as) {
573
+ let sql = typeof selectable === "string" ? selectable : selectable.toSelect();
574
+ if (as)
575
+ sql += " AS " + as;
424
576
  return sql;
425
577
  }
578
+ /** @public */
579
+ class Selection {
580
+ static from(selectable, as) {
581
+ return new this(selectable, as);
582
+ }
583
+ constructor(selectable, as) {
584
+ _Selection_instances.add(this);
585
+ _Selection_sql.set(this, void 0);
586
+ __classPrivateFieldSet(this, _Selection_sql, fromAs(selectable, as), "f");
587
+ }
588
+ toString() {
589
+ return "FROM " + __classPrivateFieldGet(this, _Selection_sql, "f");
590
+ }
591
+ fullJoin(selectable, as, on) {
592
+ return __classPrivateFieldGet(this, _Selection_instances, "m", _Selection_join).call(this, "FULL JOIN", selectable, as, on);
593
+ }
594
+ innerJoin(selectable, as, on) {
595
+ return __classPrivateFieldGet(this, _Selection_instances, "m", _Selection_join).call(this, "INNER JOIN", selectable, as, on);
596
+ }
597
+ leftJoin(selectable, as, on) {
598
+ return __classPrivateFieldGet(this, _Selection_instances, "m", _Selection_join).call(this, "LEFT JOIN", selectable, as, on);
599
+ }
600
+ rightJoin(selectable, as, on) {
601
+ return __classPrivateFieldGet(this, _Selection_instances, "m", _Selection_join).call(this, "RIGHT JOIN", selectable, as, on);
602
+ }
603
+ naturalJoin(selectable, as) {
604
+ return __classPrivateFieldGet(this, _Selection_instances, "m", _Selection_join).call(this, "NATURAL JOIN", selectable, as);
605
+ }
606
+ crossJoin(selectable, as) {
607
+ return __classPrivateFieldGet(this, _Selection_instances, "m", _Selection_join).call(this, "CROSS JOIN", selectable, as);
608
+ }
609
+ from(selectable, as) {
610
+ return new _a(__classPrivateFieldGet(this, _Selection_sql, "f") + "," + fromAs(selectable, as));
611
+ }
612
+ select(columnsIn) {
613
+ let sql = "SELECT ";
614
+ let columns = [];
615
+ if (typeof columnsIn === "string")
616
+ sql += columnsIn;
617
+ else {
618
+ sql += selectColumns(columnsIn);
619
+ if (columnsIn instanceof Array) ;
620
+ else
621
+ columns = Object.keys(columnsIn);
622
+ }
623
+ sql += "\n" + this.toString();
624
+ return new AfterSelectImpl(sql, columns);
625
+ }
626
+ }
627
+ _a = Selection, _Selection_sql = new WeakMap(), _Selection_instances = new WeakSet(), _Selection_join = function _Selection_join(type, selectable, as, on) {
628
+ let sql = __classPrivateFieldGet(this, _Selection_sql, "f") + "\n" + type + " " + fromAs(selectable, as);
629
+ if (on)
630
+ sql += " ON " + on;
631
+ return new _a(sql);
632
+ };
633
+
426
634
  function selectColumnsOrTable(columns) {
427
635
  let sqlSelect;
428
636
  let select;
@@ -450,226 +658,6 @@ function selectColumnsOrTable(columns) {
450
658
  throw new Error("选择列为空");
451
659
  return { columns: select, sqlColumns: sqlSelect.join(", ") };
452
660
  }
453
- /**
454
- * @param select 选择的行
455
- * @param tableColumns 全部行
456
- * @param push 要讲选择的行加入到集合中。
457
- */
458
- function genNewColumns(select, tableColumns,
459
- /** newName -> oldName */
460
- push = new Map()) {
461
- if (select === "*") {
462
- for (const key of tableColumns) {
463
- if (push.has(key))
464
- throw new ColumnRepeatError(key);
465
- push.set(key, null);
466
- }
467
- }
468
- else {
469
- genSelectAsColumns(select, push);
470
- }
471
- return push;
472
- }
473
- function genSelectAsColumns(select,
474
- /** newName -> oldName */
475
- push = new Map()) {
476
- if (select instanceof Array) {
477
- for (const key of select) {
478
- if (push.has(key))
479
- throw new ColumnRepeatError(key);
480
- push.set(key, null);
481
- }
482
- }
483
- else {
484
- let finalName;
485
- for (const oldName of Object.keys(select)) {
486
- if (typeof select[oldName] === "string")
487
- finalName = select[oldName];
488
- else if (select[oldName])
489
- finalName = oldName;
490
- else
491
- continue;
492
- if (push.has(finalName))
493
- throw new ColumnRepeatError(finalName);
494
- push.set(finalName, oldName);
495
- }
496
- }
497
- return push;
498
- }
499
- class ColumnRepeatError extends Error {
500
- constructor(columnName) {
501
- super("Column name '" + columnName + "' repeated");
502
- }
503
- }
504
-
505
- var _SelectImpl_instances, _a, _SelectImpl_joinOn, _SelectImpl_join;
506
- /** @public */
507
- const createSelect = function createSelect(tb, columns, option) {
508
- let select = createSelectMap(tb, columns, option).selects;
509
- return new SelectImpl(select);
510
- };
511
- function* mergeColumns(a, b) {
512
- for (const { columns } of a)
513
- yield* columns.keys();
514
- yield* b;
515
- }
516
- class SelectImpl extends SqlSelectable {
517
- constructor(tableList, addedColumns) {
518
- super(addedColumns ? mergeColumns(tableList.values(), addedColumns.keys()) : tableList.keys());
519
- _SelectImpl_instances.add(this);
520
- this.tableList = tableList;
521
- this.addedColumns = addedColumns;
522
- }
523
- toSelect() {
524
- return "(" + this.toString() + ")";
525
- }
526
- toString() {
527
- let tables = [];
528
- let join = "";
529
- let selectColumns = [];
530
- const size = this.tableList.size;
531
- for (const [tableAs, { columns, from, on, type }] of this.tableList) {
532
- let tableStr = tableAs === from ? from : from + " AS " + tableAs;
533
- if (type) {
534
- join += "\n" + type + " " + tableStr;
535
- if (on)
536
- join += " ON " + on;
537
- }
538
- else {
539
- tables.push(tableStr);
540
- }
541
- if (size === 1 && tableAs === from) {
542
- for (const [column, oldName] of columns) {
543
- if (!oldName || oldName == column)
544
- selectColumns.push(column);
545
- else
546
- selectColumns.push(oldName + " AS " + column);
547
- }
548
- }
549
- else {
550
- for (const [column, oldName] of columns) {
551
- if (!oldName || oldName === column)
552
- selectColumns.push(tableAs + "." + column);
553
- else
554
- selectColumns.push(tableAs + "." + oldName + " AS " + column);
555
- }
556
- }
557
- }
558
- if (this.addedColumns) {
559
- for (const [asName, columnStr] of this.addedColumns) {
560
- if (asName === columnStr)
561
- selectColumns.push(asName);
562
- else
563
- selectColumns.push(columnStr + " AS " + asName);
564
- }
565
- }
566
- if (selectColumns.length === 0)
567
- throw new Error("Columns 为空");
568
- let sql = `SELECT ${selectColumns.join(", ")}\nFROM ${tables.join(", ")}` + join;
569
- return sql;
570
- }
571
- fullJoin(tb, columns, option) {
572
- return __classPrivateFieldGet(this, _SelectImpl_instances, "m", _SelectImpl_joinOn).call(this, "FULL JOIN", tb, columns, option);
573
- }
574
- innerJoin(tb, columns, option) {
575
- return __classPrivateFieldGet(this, _SelectImpl_instances, "m", _SelectImpl_joinOn).call(this, "INNER JOIN", tb, columns, option);
576
- }
577
- leftJoin(tb, columns, option) {
578
- return __classPrivateFieldGet(this, _SelectImpl_instances, "m", _SelectImpl_joinOn).call(this, "LEFT JOIN", tb, columns, option);
579
- }
580
- rightJoin(tb, columns, option) {
581
- return __classPrivateFieldGet(this, _SelectImpl_instances, "m", _SelectImpl_joinOn).call(this, "RIGHT JOIN", tb, columns, option);
582
- }
583
- naturalJoin(tb, columns, option) {
584
- return __classPrivateFieldGet(this, _SelectImpl_instances, "m", _SelectImpl_join).call(this, "NATURAL JOIN", tb, columns, option);
585
- }
586
- crossJoin(tb, columns, option) {
587
- return __classPrivateFieldGet(this, _SelectImpl_instances, "m", _SelectImpl_join).call(this, "CROSS JOIN", tb, columns, option);
588
- }
589
- select(tb, columns, option) {
590
- let select = createSelectMap(tb, columns, option, this.tableList).selects;
591
- const obj = new _a(select, new Map(this.addedColumns));
592
- return obj;
593
- }
594
- addColumns(add) {
595
- let addedColumns = this.addedColumns ? new Map(this.addedColumns) : new Map();
596
- for (const [asNewName, columnStr] of Object.entries(add)) {
597
- if (addedColumns.has(asNewName))
598
- throw new Error(`The column ${asNewName} already exists`);
599
- addedColumns.set(asNewName, columnStr);
600
- }
601
- return new _a(this.tableList, addedColumns);
602
- }
603
- toQuery(option = {}) {
604
- const { where, orderNullRule } = option;
605
- let sql = this.toString();
606
- if (where)
607
- sql += "\nWHERE " + where;
608
- const orderBy = option.orderBy;
609
- if (orderBy)
610
- sql += genOderBy(orderBy, orderNullRule);
611
- if (option.limit)
612
- sql += "\nLIMIT " + option.limit;
613
- if (option.offset)
614
- sql += "\nOFFSET " + option.offset;
615
- return new SqlQueryStatement(sql, Array.from(this.columns));
616
- }
617
- }
618
- _a = SelectImpl, _SelectImpl_instances = new WeakSet(), _SelectImpl_joinOn = function _SelectImpl_joinOn(type, tb, columns, option) {
619
- let { selects, tbInfo } = createSelectMap(tb, columns, option, this.tableList);
620
- tbInfo.type = type;
621
- tbInfo.on = option.on;
622
- const next = new _a(selects, new Map(this.addedColumns));
623
- Object.defineProperty(next, "select", { value: undefined, configurable: false, enumerable: false });
624
- return next;
625
- }, _SelectImpl_join = function _SelectImpl_join(type, tb, columns, option) {
626
- let { selects, tbInfo } = createSelectMap(tb, columns, option, this.tableList);
627
- tbInfo.type = type;
628
- const next = new _a(selects, new Map(this.addedColumns));
629
- Object.defineProperty(next, "select", { value: undefined, configurable: false, enumerable: false });
630
- return next;
631
- };
632
- function createSelectMap(tb, columns, option = {}, selects) {
633
- let select = new Map(selects);
634
- let tableAs;
635
- let tbInfo;
636
- if (typeof tb === "string") {
637
- throw new Error("tb 应是 SqlSelectable 类型");
638
- // if (typeof columns !== "object") throw new Error("缺少 option.columns");
639
- // const newColumns = genSelectAsColumns(columns);
640
- // tableAs = option.tableAs ?? tb;
641
- // tbInfo = { table: tb, columns: newColumns };
642
- }
643
- else {
644
- const from = tb.toSelect();
645
- if (tb instanceof DbTable) {
646
- tableAs = option.tableAs ?? from;
647
- }
648
- else {
649
- tableAs = option.tableAs ?? "t" + select.size;
650
- }
651
- if (columns) {
652
- const newColumns = genNewColumns(columns, tb.columns);
653
- tbInfo = { from, columns: newColumns };
654
- }
655
- else
656
- tbInfo = { from, columns: new Map() };
657
- }
658
- if (select.has(tableAs))
659
- throw new TableRepeatError(tableAs);
660
- select.set(tableAs, tbInfo);
661
- return { selects: select, tbInfo: tbInfo };
662
- }
663
- class TableRepeatError extends Error {
664
- constructor(tableName) {
665
- super("Table name '" + tableName + "' repeated");
666
- }
667
- }
668
- // interface SqlFrom<T extends object> {
669
- // from<A extends object>(table: SqlSelectable<A>): SqlFrom<T & A>;
670
- // }
671
- // declare function from<T extends SqlSelectable<any>[]>(...table: T): Select<MergeSelectable<T>>;
672
- // type MergeSelectable<T extends any[]> = T extends [SqlSelectable<infer P>, ...infer Q] ? P & MergeSelectable<Q> : {};
673
661
 
674
662
  /** @public */
675
663
  class DbTableQuery extends DbTable {
@@ -677,8 +665,8 @@ class DbTableQuery extends DbTable {
677
665
  super(name, columns);
678
666
  this.statement = statement;
679
667
  }
680
- select(columns, option) {
681
- return createSelect(this, columns, option);
668
+ fromAs(as) {
669
+ return new Selection(this, as);
682
670
  }
683
671
  insert(values, option) {
684
672
  let insertCol;
@@ -686,7 +674,7 @@ class DbTableQuery extends DbTable {
686
674
  if (values instanceof Array) {
687
675
  if (values.length === 0)
688
676
  throw new Error("值不能为空");
689
- insertCol = getObjectListKeys(values);
677
+ insertCol = Array.from(getObjectListKeys(values));
690
678
  valuesStr = `VALUES\n${this.statement.objectListToValuesList(values, insertCol)}`;
691
679
  }
692
680
  else if (values instanceof SqlQueryStatement) {
@@ -720,7 +708,6 @@ class DbTableQuery extends DbTable {
720
708
  return genRetuningSql(sql, returns, values instanceof SqlQueryStatement ? values.columns : this.columns);
721
709
  }
722
710
  update(values, option = {}) {
723
- const { where } = option;
724
711
  const updateKey = Object.entries(values);
725
712
  if (updateKey.length === 0)
726
713
  throw new Error("值不能为空");
@@ -731,8 +718,8 @@ class DbTableQuery extends DbTable {
731
718
  setList.push(k + " = " + this.statement.toSqlStr(v));
732
719
  }
733
720
  let sql = `UPDATE ${this.name}\nSET ${setList.join(",\n")}`;
734
- if (where)
735
- sql += genWhere(where);
721
+ if (option.where)
722
+ sql += where(option.where);
736
723
  return sql;
737
724
  }
738
725
  updateWithResult(values, returns, option) {
@@ -742,7 +729,7 @@ class DbTableQuery extends DbTable {
742
729
  delete(option = {}) {
743
730
  let sql = "DELETE FROM " + this.name;
744
731
  if (option.where)
745
- sql += genWhere(option.where);
732
+ sql += where(option.where);
746
733
  return sql;
747
734
  }
748
735
  deleteWithResult(returns = "*", option) {
@@ -765,9 +752,6 @@ function genRetuningSql(sql, returns, tableColumns) {
765
752
  sql += "\nRETURNING " + columnsStr;
766
753
  return new SqlQueryStatement(sql, columns);
767
754
  }
768
- function genWhere(where) {
769
- return "\nWHERE " + where;
770
- }
771
755
 
772
756
  /**
773
757
  * 表格列的信息
@@ -940,4 +924,4 @@ class YourTable extends DbTableQuery {
940
924
  }
941
925
  }
942
926
 
943
- export { ColumnMeta, CustomDbType, DbTable, DbTableQuery, SqlQueryStatement, SqlRaw, SqlSelectable, SqlValuesCreator, TypeChecker, YourTable, YourTypeMap, createSelect, getObjectListKeys, pgSqlTransformer };
927
+ export { ColumnMeta, CustomDbType, DbTable, DbTableQuery, Selection, SqlQueryStatement, SqlRaw, SqlSelectable, SqlValuesCreator, TypeChecker, YourTable, YourTypeMap, getObjectListKeys, having, orderBy, pgSqlTransformer, selectColumns, where };
@@ -1,17 +1,13 @@
1
1
  import { SqlValuesCreator, SqlRaw } from "../sql_value/sql_value.ts";
2
- import { ColumnsSelected, ColumnsSelectAs, SelectColumns, UpdateRowValue, TableType } from "./type.ts";
3
- import { Select, SelectTableOption } from "./select.ts";
2
+ import { ColumnsSelected, SelectColumns, UpdateRowValue, TableType } from "./type.ts";
3
+ import { Selection } from "./select.ts";
4
4
  import { DbTable, SqlQueryStatement } from "./selectable.ts";
5
+ import { WhereParam } from "../util.ts";
5
6
  /** @public */
6
7
  export declare class DbTableQuery<T extends TableType = Record<string, any>, C extends TableType = Partial<T>> extends DbTable<T> {
7
8
  private statement;
8
9
  constructor(name: string, columns: readonly string[], statement: SqlValuesCreator);
9
- /** 选择全部列 */
10
- select(columns?: undefined, option?: SelectTableOption): Select<{}>;
11
- /** 选择全部列 */
12
- select(columns: "*", option?: SelectTableOption): Select<T>;
13
- /** 选择表中的列并重命名 */
14
- select<R extends ColumnsSelectAs<T>>(columns: R, option?: SelectTableOption): Select<SelectColumns<T, R>>;
10
+ fromAs(as?: string): Selection;
15
11
  insert(values: C[] | SqlQueryStatement<C>, option?: InsertOption<T>): string;
16
12
  insertWithResult<R extends ColumnsSelected<T>>(values: C[] | SqlQueryStatement<C>, returns: R, option?: InsertOption<T>): SqlQueryStatement<SelectColumns<T, R>>;
17
13
  update(values: UpdateRowValue<T>, option?: UpdateOption): string;
@@ -25,14 +21,14 @@ export interface InsertOption<T extends object> {
25
21
  updateValues?: {
26
22
  [key in keyof T]?: undefined | SqlRaw | T[key];
27
23
  };
28
- where?: string;
24
+ where?: WhereParam;
29
25
  }
30
26
  /** @public */
31
27
  export interface UpdateOption {
32
- where?: string;
28
+ where?: WhereParam;
33
29
  }
34
30
  /** @public */
35
31
  export interface DeleteOption {
36
- where?: string;
32
+ where?: WhereParam;
37
33
  }
38
34
  //# sourceMappingURL=TableQuery.d.ts.map
@@ -1,15 +1,6 @@
1
- import { ColumnsSelectAs, ColumnsSelected, RowsOrder } from "./type.ts";
2
- export declare function genOderBy(orderBy: RowsOrder<any>, orderNullRule?: "FIRST" | "LAST"): string;
1
+ import { ColumnsSelectAs } from "./type.ts";
3
2
  export declare function selectColumnsOrTable(columns: ColumnsSelectAs<any> | string[]): {
4
3
  columns: string[];
5
4
  sqlColumns: string;
6
5
  };
7
- /**
8
- * @param select 选择的行
9
- * @param tableColumns 全部行
10
- * @param push 要讲选择的行加入到集合中。
11
- */
12
- export declare function genNewColumns(select: ColumnsSelected<any>, tableColumns: Iterable<string | number | symbol>,
13
- /** newName -> oldName */
14
- push?: Map<string, string | null>): Map<string, string | null>;
15
6
  //# sourceMappingURL=_statement.d.ts.map
@@ -1,57 +1,43 @@
1
- import { SqlSelectable, InferQueryResult, SqlQueryStatement } from "./selectable.ts";
2
- import type { ColumnsSelected, OrderValue, RowsOrder, SelectColumns, TableType } from "./type.ts";
3
- interface AddTableFn<T extends TableType> {
4
- <Q extends SqlSelectable<any>, A extends InferQueryResult<Q>>(tb: Q, columns?: undefined, option?: SelectTableOption): Select<T>;
5
- <Q extends SqlSelectable<any>, A extends InferQueryResult<Q>, C extends ColumnsSelected<A>>(tb: Q, columns: C, option?: SelectTableOption): Select<T & SelectColumns<A, C>>;
6
- }
7
- interface JoinTableFn<T extends TableType, ExtraOption extends object = {}> {
8
- <Q extends SqlSelectable<any>, A extends InferQueryResult<Q>>(tb: Q, columns: undefined, option: ExtraOption & SelectTableOption): JoinSelect<T>;
9
- <Q extends SqlSelectable<any>, A extends InferQueryResult<Q>, C extends ColumnsSelected<A>>(tb: Q, columns: C, option: ExtraOption & SelectTableOption): JoinSelect<T & SelectColumns<A, C>>;
10
- }
1
+ import { SqlSelectable, SqlQueryStatement } from "./selectable.ts";
2
+ import { OrderByParam, WhereParam } from "../util.ts";
3
+ import type { TableType } from "./type.ts";
11
4
  /** @public */
12
- export interface SelectFilterOption<T extends object> {
13
- orderBy?: RowsOrder<T>;
14
- orderNullRule?: "FIRST" | "LAST";
15
- where?: string;
16
- offset?: number;
17
- limit?: number;
5
+ export interface CurrentLimit<T extends TableType> extends SqlQueryStatement<T> {
6
+ limit(limit?: number, offset?: number): SqlQueryStatement<T>;
18
7
  }
19
8
  /** @public */
20
- export interface FinalSelect<T extends TableType> extends SqlSelectable<T> {
21
- toQuery(option?: SelectFilterOption<T & {
22
- [key: string]: OrderValue;
23
- }>): SqlQueryStatement<T>;
9
+ export interface CurrentOrderBy<T extends TableType> extends CurrentLimit<T> {
10
+ orderBy(param: OrderByParam): CurrentLimit<T>;
24
11
  }
25
12
  /** @public */
26
- export interface JoinSelect<T extends TableType> extends FinalSelect<T> {
27
- addColumns<A extends TableType>(add: {
28
- [key in keyof A]: string;
29
- }): FinalSelect<T & A>;
30
- crossJoin: JoinTableFn<T>;
31
- naturalJoin: JoinTableFn<T>;
32
- innerJoin: JoinTableFn<T, {
33
- on: string;
34
- }>;
35
- leftJoin: JoinTableFn<T, {
36
- on: string;
37
- }>;
38
- rightJoin: JoinTableFn<T, {
39
- on: string;
40
- }>;
41
- fullJoin: JoinTableFn<T, {
42
- on: string;
43
- }>;
13
+ export interface CurrentHaving<T extends TableType> extends CurrentOrderBy<T> {
14
+ having(param: WhereParam | (() => WhereParam)): CurrentLimit<T>;
44
15
  }
45
16
  /** @public */
46
- export interface Select<T extends TableType> extends JoinSelect<T> {
47
- /** 选择表 */
48
- select: AddTableFn<T>;
17
+ export interface CurrentGroupBy<T extends TableType> extends CurrentOrderBy<T> {
18
+ groupBy(columns: string | string[]): CurrentHaving<T>;
49
19
  }
50
20
  /** @public */
51
- export declare const createSelect: AddTableFn<{}>;
21
+ export interface CurrentWhere<T extends TableType> extends CurrentGroupBy<T> {
22
+ where(param: WhereParam | (() => WhereParam)): CurrentGroupBy<T>;
23
+ }
52
24
  /** @public */
53
- export interface SelectTableOption {
54
- tableAs?: string;
25
+ export declare class Selection {
26
+ #private;
27
+ static from(selectable: SqlSelectable<any> | string, as?: string): Selection;
28
+ constructor(selectable: SqlSelectable<any> | string, as?: string);
29
+ toString(): string;
30
+ fullJoin(selectable: SqlSelectable<any>, as: string | undefined, on: string): Selection;
31
+ innerJoin(selectable: SqlSelectable<any>, as: string | undefined, on: string): Selection;
32
+ leftJoin(selectable: SqlSelectable<any>, as: string | undefined, on: string): Selection;
33
+ rightJoin(selectable: SqlSelectable<any>, as: string | undefined, on: string): Selection;
34
+ naturalJoin(selectable: SqlSelectable<any>, as?: string | undefined): Selection;
35
+ crossJoin(selectable: SqlSelectable<any>, as?: string | undefined): Selection;
36
+ from(selectable: SqlSelectable<any> | string, as?: string): Selection;
37
+ select<T extends TableType = TableType>(columns: "*" | string[]): CurrentWhere<T>;
38
+ select<T extends TableType = TableType>(columns: {
39
+ [key in keyof T]: string | boolean;
40
+ }): CurrentWhere<T>;
41
+ select<T extends TableType = TableType>(columns: "*" | string[] | TableType): CurrentWhere<T>;
55
42
  }
56
- export {};
57
43
  //# sourceMappingURL=select.d.ts.map
@@ -23,7 +23,7 @@ export declare abstract class SqlSelectable<T extends TableType> {
23
23
  /** 获取 SQL 语句 */
24
24
  abstract toString(): string;
25
25
  /** 保留以推断类型 */
26
- private [SQL_SELECTABLE];
26
+ protected [SQL_SELECTABLE]: T;
27
27
  }
28
28
  /**
29
29
  * 数据库表
@@ -40,8 +40,9 @@ export declare class DbTable<T extends TableType> extends SqlSelectable<T> {
40
40
  * @public
41
41
  */
42
42
  export declare class SqlQueryStatement<T extends TableType = TableType> extends SqlSelectable<T> {
43
- private sql;
43
+ #private;
44
44
  constructor(sql: string, columns: readonly string[]);
45
+ constructor(sql: SqlQueryStatement);
45
46
  toString(): string;
46
47
  toSelect(): string;
47
48
  }
@@ -14,13 +14,6 @@ export type PickColumn<T extends {
14
14
  } & {
15
15
  [key in Pa]?: T[key];
16
16
  };
17
- /**
18
- * 定义行的排序
19
- * @public
20
- */
21
- export type RowsOrder<T extends object> = {
22
- [key in keyof T]?: OrderValue;
23
- };
24
17
  /** @public */
25
18
  export type UpdateRowValue<T extends object> = {
26
19
  [key in keyof T]?: T[key] | SqlRaw;
@@ -9,7 +9,7 @@ export declare class SqlRaw<T = any> {
9
9
  constructor(value: string);
10
10
  toString(): string;
11
11
  /** 保留以推断类型 */
12
- private [SQL_RAW];
12
+ protected [SQL_RAW]: T;
13
13
  }
14
14
  /** @public */
15
15
  export type JsObjectMapSql = Map<new (...args: any[]) => any, SqlValueEncoder>;
package/dist/util.d.ts CHANGED
@@ -1,6 +1,58 @@
1
+ import { OrderValue } from "./select/type.ts";
1
2
  /**
3
+ * 获取对象数组中的 key 的集合
2
4
  * @public
3
5
  * @param keepUndefinedKey - 是否保留值为 undefined 的 key
4
6
  */
5
- export declare function getObjectListKeys(objectList: any[], keepUndefinedKey?: boolean): string[];
7
+ export declare function getObjectListKeys(objectList: any[], keepUndefinedKey?: boolean): Set<string>;
8
+ /** @public */
9
+ export type WhereParam = string | string[];
10
+ /**
11
+ * 生成 WHERE 语句
12
+ * @public
13
+ * ```ts
14
+ *
15
+ * ```
16
+ */
17
+ export declare function where(condition?: WhereParam | (() => WhereParam), type?: "AND" | "OR"): string;
18
+ /**
19
+ *
20
+ * 生成 HAVING 语句
21
+ * @public
22
+ */
23
+ export declare function having(condition?: WhereParam | (() => WhereParam), type?: "AND" | "OR"): string;
24
+ /**
25
+ * @public
26
+ * ```ts
27
+ * selectColumns({c1: true, c2: "count(*)", c3: "column"}) // "c1,count(*) AS c2,column as c3"
28
+ * selectColumns(["c1", "count(*) AS c2", "column as c3"]) // "c1,count(*) AS c2,column as c3"
29
+ * ```
30
+ */
31
+ export declare function selectColumns(columns: string[] | Record<string, string | boolean>): string;
32
+ /** @public */
33
+ export type OrderBehavior = {
34
+ key: string;
35
+ asc: boolean;
36
+ nullLast?: boolean;
37
+ };
38
+ /** @public */
39
+ export type OrderByParam = string | (string | OrderBehavior)[] | Record<string, boolean | `${OrderValue} ${"NULLS FIRST" | "NULLS LAST"}`>;
40
+ /**
41
+ * 生成 ORDER BY 语句, d
42
+ * @public
43
+ * ```ts
44
+ * // 以下生成 "\nORDER BY age DESC NULLS FIRST,num ASC"
45
+ * orderBy("age DESC NULLS FIRST,num ASC");
46
+ * orderBy(["age DESC NULLS FIRST", "num ASC"]);
47
+ * orderBy([
48
+ * { key: "age", asc: false, nullLast: false },
49
+ * { key: "num", asc: true },
50
+ * ]);
51
+ * orderBy({ age: "DESC NULLS FIRST", num: true });
52
+ *
53
+ * orderBy([]) // ""
54
+ * orderBy({}) // ""
55
+ * ```
56
+ */
57
+ export declare function orderBy(by: OrderByParam | (() => OrderByParam)): string;
6
58
  //# sourceMappingURL=util.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asla/yoursql",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/mod.d.ts",