@asla/yoursql 0.5.1 → 0.6.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
@@ -33,6 +33,53 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
33
33
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
34
34
  };
35
35
 
36
+ function selectColumnsOrTable(columns) {
37
+ let sqlSelect;
38
+ let select;
39
+ if (columns instanceof Array) {
40
+ sqlSelect = columns;
41
+ select = columns;
42
+ }
43
+ else {
44
+ sqlSelect = [];
45
+ select = [];
46
+ let c;
47
+ for (const key of Object.keys(columns)) {
48
+ c = columns[key];
49
+ if (typeof c === "string" && c !== key) {
50
+ sqlSelect.push(key + " AS " + c);
51
+ select.push(c);
52
+ }
53
+ else if (c) {
54
+ sqlSelect.push(key);
55
+ select.push(key);
56
+ }
57
+ }
58
+ }
59
+ if (select.length === 0)
60
+ throw new Error("选择列为空");
61
+ return { columns: select, sqlColumns: sqlSelect.join(", ") };
62
+ }
63
+ function condition(conditions, type = "AND") {
64
+ if (typeof conditions === "function")
65
+ conditions = conditions();
66
+ if (!conditions)
67
+ return;
68
+ if (typeof conditions === "string")
69
+ return conditions;
70
+ else {
71
+ if (conditions.length) {
72
+ let sql = "";
73
+ type = " " + type + " ";
74
+ sql += conditions[0];
75
+ for (let i = 1; i < conditions.length; i++)
76
+ sql += type + conditions[i];
77
+ return sql;
78
+ }
79
+ return;
80
+ }
81
+ }
82
+
36
83
  /**
37
84
  * 获取对象数组中的 key 的集合
38
85
  * @public
@@ -58,8 +105,14 @@ function getObjectListKeys(objectList, keepUndefinedKey) {
58
105
  /**
59
106
  * 生成 WHERE 语句
60
107
  * @public
108
+ * @example
61
109
  * ```ts
62
- *
110
+ * where(['a=1','b=2']) // "\nWHERE a=1 AND b=2"
111
+ * where(['a=1','b=2'],"OR") // "\nWHERE a=1 OR b=2"
112
+ * where("a=1 OR b=2") // "\nWHERE a=1 OR b=2"
113
+ * where(()=>"a=1 OR b=2") // "\nWHERE a=1 AND b=2"
114
+ * where([]) // ""
115
+ * where(undefined) // ""
63
116
  * ```
64
117
  */
65
118
  function where(conditions, type) {
@@ -79,67 +132,50 @@ function having(conditions, type) {
79
132
  return "\nHAVING " + sql;
80
133
  return "";
81
134
  }
82
- function condition(conditions, type = "AND") {
83
- if (typeof conditions === "function")
84
- conditions = conditions();
85
- if (!conditions)
86
- return;
87
- if (typeof conditions === "string")
88
- return conditions;
89
- else {
90
- if (conditions.length) {
91
- let sql = "";
92
- type = " " + type + " ";
93
- sql += conditions[0];
94
- for (let i = 1; i < conditions.length; i++)
95
- sql += type + conditions[i];
96
- return sql;
97
- }
98
- return;
99
- }
100
- }
101
135
  /**
102
136
  * @public
137
+ * @example
103
138
  * ```ts
104
139
  * selectColumns({c1: true, c2: "count(*)", c3: "column"}) // "c1,count(*) AS c2,column as c3"
105
- * selectColumns(["c1", "count(*) AS c2", "column as c3"]) // "c1,count(*) AS c2,column as c3"
140
+ * selectColumns("c1,count(*) AS c2,column as c3") // "c1,count(*) AS c2,column as c3"
106
141
  * ```
107
142
  */
108
143
  function selectColumns(columns) {
109
- let sql = "";
110
- if (columns instanceof Array) {
111
- if (columns.length)
112
- sql += columns[0];
113
- else
114
- throw new Error("没有选择任何列");
115
- for (let i = 1; i < columns.length; i++)
116
- sql += "," + columns[i];
117
- }
118
- else {
119
- const keys = Object.keys(columns);
120
- if (keys.length === 0)
121
- throw new Error("没有选择任何列");
122
- let k = keys[0];
123
- let v = columns[k];
124
- if (typeof v === "string")
125
- sql += v + " AS " + k;
126
- else
127
- sql += k;
128
- for (let i = 1; i < keys.length; i++) {
129
- k = keys[i];
130
- v = columns[k];
131
- sql += ",";
144
+ if (typeof columns === "function")
145
+ columns = columns();
146
+ switch (typeof columns) {
147
+ case "string":
148
+ return columns;
149
+ case "object": {
150
+ let sql = "";
151
+ const keys = Object.keys(columns);
152
+ if (keys.length === 0)
153
+ throw new Error("没有选择任何列");
154
+ let k = keys[0];
155
+ let v = columns[k];
132
156
  if (typeof v === "string")
133
157
  sql += v + " AS " + k;
134
158
  else
135
159
  sql += k;
160
+ for (let i = 1; i < keys.length; i++) {
161
+ k = keys[i];
162
+ v = columns[k];
163
+ sql += ",";
164
+ if (typeof v === "string")
165
+ sql += v + " AS " + k;
166
+ else
167
+ sql += k;
168
+ }
169
+ return sql;
136
170
  }
171
+ default:
172
+ throw new TypeError("columns 应为 string 或 object 类型");
137
173
  }
138
- return sql;
139
174
  }
140
175
  /**
141
176
  * 生成 ORDER BY 语句, d
142
177
  * @public
178
+ * @example
143
179
  * ```ts
144
180
  * // 以下生成 "\nORDER BY age DESC NULLS FIRST,num ASC"
145
181
  * orderBy("age DESC NULLS FIRST,num ASC");
@@ -174,14 +210,16 @@ function orderBy(by) {
174
210
  let keys = Object.keys(by);
175
211
  if (keys.length) {
176
212
  let key = keys[0];
177
- sql += "\nORDER BY " + key + " " + by[key];
213
+ let value = by[key];
214
+ sql += "\nORDER BY " + key + " " + (typeof value === "string" ? value : value ? "ASC" : "DESC");
178
215
  for (let i = 1; i < keys.length; i++) {
179
216
  key = keys[i];
217
+ value = by[key];
180
218
  sql += "," + key + " ";
181
- if (typeof by[key] === "string")
182
- sql += by[key];
219
+ if (typeof value === "string")
220
+ sql += value;
183
221
  else
184
- sql += by[key] ? "ASC" : "DESC";
222
+ sql += value ? "ASC" : "DESC";
185
223
  }
186
224
  }
187
225
  }
@@ -210,41 +248,14 @@ var _SqlQueryStatement_sql;
210
248
  * @public
211
249
  */
212
250
  class SqlSelectable {
213
- constructor(columns) {
214
- // Reflect.set(this, SQL_SELECTABLE, undefined);
215
- let readonlyColumns;
216
- if (typeof columns[Symbol.iterator] === "function") {
217
- let iterable = columns;
218
- readonlyColumns = [];
219
- let iter = iterable[Symbol.iterator]();
220
- let i = 0;
221
- let item = iter.next();
222
- while (!item.done) {
223
- readonlyColumns[i++] = item.value;
224
- item = iter.next();
225
- }
226
- // readonlyColumns.length = i;
227
- }
228
- else {
229
- let arrayLike = columns;
230
- readonlyColumns = new Array(arrayLike.length);
231
- // readonlyColumns.length = arrayLike.length;
232
- for (let i = 0; i < arrayLike.length; i++) {
233
- readonlyColumns[i] = arrayLike[i];
234
- }
235
- }
236
- this.columns = readonlyColumns;
237
- }
238
251
  }
239
252
  /**
240
253
  * 数据库表
241
254
  * @public
242
255
  */
243
256
  class DbTable extends SqlSelectable {
244
- constructor(name, columns) {
245
- if (!(columns instanceof Array))
246
- columns = Object.keys(columns);
247
- super(columns);
257
+ constructor(name) {
258
+ super();
248
259
  this.name = name;
249
260
  }
250
261
  toSelect() {
@@ -259,14 +270,10 @@ class DbTable extends SqlSelectable {
259
270
  * @public
260
271
  */
261
272
  class SqlQueryStatement extends SqlSelectable {
262
- constructor(sql, columns) {
263
- if (sql instanceof SqlQueryStatement) {
264
- columns = sql.columns;
265
- sql = __classPrivateFieldGet(sql, _SqlQueryStatement_sql, "f");
266
- }
267
- super(columns);
273
+ constructor(sql) {
274
+ super();
268
275
  _SqlQueryStatement_sql.set(this, void 0);
269
- __classPrivateFieldSet(this, _SqlQueryStatement_sql, sql, "f");
276
+ __classPrivateFieldSet(this, _SqlQueryStatement_sql, sql.toString(), "f");
270
277
  }
271
278
  toString() {
272
279
  return __classPrivateFieldGet(this, _SqlQueryStatement_sql, "f");
@@ -487,13 +494,13 @@ class SqlValuesCreator {
487
494
  }
488
495
  class YourValuesAs extends SqlSelectable {
489
496
  constructor(columns, asName, valuesStr) {
490
- super(columns);
497
+ super();
491
498
  _YourValuesAs_asName.set(this, void 0);
492
499
  _YourValuesAs_valuesStr.set(this, void 0);
493
500
  _YourValuesAs_sql.set(this, void 0);
494
501
  __classPrivateFieldSet(this, _YourValuesAs_asName, asName, "f");
495
502
  __classPrivateFieldSet(this, _YourValuesAs_valuesStr, valuesStr, "f");
496
- __classPrivateFieldSet(this, _YourValuesAs_sql, `(VALUES\n${__classPrivateFieldGet(this, _YourValuesAs_valuesStr, "f")})\nAS ${__classPrivateFieldGet(this, _YourValuesAs_asName, "f")}(${this.columns.join(",")})`, "f");
503
+ __classPrivateFieldSet(this, _YourValuesAs_sql, `(VALUES\n${__classPrivateFieldGet(this, _YourValuesAs_valuesStr, "f")})\nAS ${__classPrivateFieldGet(this, _YourValuesAs_asName, "f")}(${columns.join(",")})`, "f");
497
504
  }
498
505
  toSelect() {
499
506
  return __classPrivateFieldGet(this, _YourValuesAs_sql, "f");
@@ -546,11 +553,11 @@ const pgSqlTransformer = new Map([
546
553
 
547
554
  var _Selection_instances, _a, _Selection_sql, _Selection_join;
548
555
  class AfterSelectImpl extends SqlQueryStatement {
549
- constructor(sql, columns) {
550
- super(sql, columns);
556
+ constructor(sql) {
557
+ super(sql);
551
558
  }
552
559
  where(param) {
553
- return new AfterSelectImpl(this.toString() + where(param), this.columns);
560
+ return new AfterSelectImpl(this.toString() + where(param));
554
561
  }
555
562
  groupBy(columns) {
556
563
  let sql = this.toString();
@@ -558,13 +565,13 @@ class AfterSelectImpl extends SqlQueryStatement {
558
565
  sql += " GROUP BY " + columns;
559
566
  else
560
567
  sql += " GROUP BY " + columns.join(",");
561
- return new AfterSelectImpl(sql, this.columns);
568
+ return new AfterSelectImpl(sql);
562
569
  }
563
570
  having(param) {
564
- return new AfterSelectImpl(this.toString() + having(param), this.columns);
571
+ return new AfterSelectImpl(this.toString() + having(param));
565
572
  }
566
573
  orderBy(param) {
567
- return new AfterSelectImpl(this.toString() + orderBy(param), this.columns);
574
+ return new AfterSelectImpl(this.toString() + orderBy(param));
568
575
  }
569
576
  limit(limit, offset) {
570
577
  let sql = this.toString();
@@ -572,10 +579,12 @@ class AfterSelectImpl extends SqlQueryStatement {
572
579
  sql += "\nLIMIT " + limit;
573
580
  if (offset)
574
581
  sql += "\nOFFSET " + offset;
575
- return new SqlQueryStatement(sql, Array.from(this.columns));
582
+ return new SqlQueryStatement(sql);
576
583
  }
577
584
  }
578
585
  function fromAs(selectable, as) {
586
+ if (typeof selectable === "function")
587
+ selectable = selectable();
579
588
  let sql = typeof selectable === "string" ? selectable : selectable.toSelect();
580
589
  if (as)
581
590
  sql += " AS " + as;
@@ -616,59 +625,25 @@ class Selection {
616
625
  return new _a(__classPrivateFieldGet(this, _Selection_sql, "f") + "," + fromAs(selectable, as));
617
626
  }
618
627
  select(columnsIn) {
619
- let sql = "SELECT ";
620
- let columns = [];
621
- if (typeof columnsIn === "string")
622
- sql += columnsIn;
623
- else {
624
- sql += selectColumns(columnsIn);
625
- if (columnsIn instanceof Array) ;
626
- else
627
- columns = Object.keys(columnsIn);
628
- }
628
+ if (typeof columnsIn === "function")
629
+ columnsIn = columnsIn();
630
+ let sql = "SELECT " + selectColumns(columnsIn);
629
631
  sql += "\n" + this.toString();
630
- return new AfterSelectImpl(sql, columns);
632
+ return new AfterSelectImpl(sql);
631
633
  }
632
634
  }
633
635
  _a = Selection, _Selection_sql = new WeakMap(), _Selection_instances = new WeakSet(), _Selection_join = function _Selection_join(type, selectable, as, on) {
634
636
  let sql = __classPrivateFieldGet(this, _Selection_sql, "f") + "\n" + type + " " + fromAs(selectable, as);
635
- if (on)
636
- sql += " ON " + on;
637
+ if (on) {
638
+ sql += " ON " + condition(on);
639
+ }
637
640
  return new _a(sql);
638
641
  };
639
642
 
640
- function selectColumnsOrTable(columns) {
641
- let sqlSelect;
642
- let select;
643
- if (columns instanceof Array) {
644
- sqlSelect = columns;
645
- select = columns;
646
- }
647
- else {
648
- sqlSelect = [];
649
- select = [];
650
- let c;
651
- for (const key of Object.keys(columns)) {
652
- c = columns[key];
653
- if (typeof c === "string" && c !== key) {
654
- sqlSelect.push(key + " AS " + c);
655
- select.push(c);
656
- }
657
- else if (c) {
658
- sqlSelect.push(key);
659
- select.push(key);
660
- }
661
- }
662
- }
663
- if (select.length === 0)
664
- throw new Error("选择列为空");
665
- return { columns: select, sqlColumns: sqlSelect.join(", ") };
666
- }
667
-
668
643
  /** @public */
669
644
  class DbTableQuery extends DbTable {
670
- constructor(name, columns, statement) {
671
- super(name, columns);
645
+ constructor(name, statement) {
646
+ super(name);
672
647
  this.statement = statement;
673
648
  }
674
649
  fromAs(as) {
@@ -677,89 +652,127 @@ class DbTableQuery extends DbTable {
677
652
  select(columns, as) {
678
653
  return this.fromAs(as).select(columns);
679
654
  }
680
- insert(values, option) {
681
- let insertCol;
655
+ insert(values, columns_option, option) {
656
+ if (typeof values === "function")
657
+ values = values();
658
+ let columnStr;
682
659
  let valuesStr;
683
- if (values instanceof Array) {
684
- if (values.length === 0)
685
- throw new Error("值不能为空");
686
- insertCol = Array.from(getObjectListKeys(values));
687
- valuesStr = `VALUES\n${this.statement.objectListToValuesList(values, insertCol)}`;
660
+ if (typeof values === "string") {
661
+ valuesStr = values;
662
+ if (typeof columns_option === "string")
663
+ columnStr = columns_option;
664
+ else if (columns_option instanceof Array) {
665
+ if (columns_option.length === 0)
666
+ throw new Error("插入列为空");
667
+ columnStr = columns_option.join(",");
668
+ }
669
+ else
670
+ throw new Error("当 values 为 string 类型时,必须指定 columns");
688
671
  }
689
- else if (values instanceof SqlQueryStatement) {
690
- // todo 验证 values.columns 和 this.columns 是否匹配
691
- valuesStr = values.toString();
692
- insertCol = values.columns;
672
+ else {
673
+ let insertCol;
674
+ option = columns_option;
675
+ if (typeof values === "object") {
676
+ if (values instanceof Array) {
677
+ if (values.length === 0)
678
+ throw new Error("值不能为空");
679
+ insertCol = Array.from(getObjectListKeys(values));
680
+ valuesStr = `VALUES\n${this.statement.objectListToValuesList(values, insertCol)}`;
681
+ }
682
+ else if (values instanceof SqlQueryStatement) {
683
+ // todo 验证 values.columns 和 this.columns 是否匹配
684
+ valuesStr = values.toString();
685
+ insertCol = values.columns;
686
+ }
687
+ else {
688
+ insertCol = Object.keys(values);
689
+ valuesStr = `VALUES\n(${this.statement.objectToValues(values, insertCol)})`;
690
+ }
691
+ }
692
+ else
693
+ throw new Error("values 应该是 Array 或 TableQuery 类型");
694
+ if (insertCol.length === 0)
695
+ throw new Error("插入列不能为空");
696
+ columnStr = insertCol.join(",");
693
697
  }
694
- else
695
- throw new Error("values 应该是 Array 或 TableQuery 类型");
696
- if (insertCol.length === 0)
697
- throw new Error("插入列不能为空");
698
- let sql = `INSERT INTO ${this.name} (${insertCol.join(",")})\n${valuesStr}`;
698
+ let sql = `INSERT INTO ${this.name} (${columnStr})\n${valuesStr}`;
699
699
  if (option) {
700
- const { updateValues, conflict, where } = option;
700
+ let { updateValues, conflict, where: inputWhere } = option;
701
701
  if (conflict) {
702
- sql += `\nON CONFLICT (${conflict.join(",")})`;
702
+ if (typeof conflict !== "string")
703
+ conflict = conflict.join(",");
704
+ sql += `\nON CONFLICT (${conflict})`;
705
+ if (typeof updateValues === "function")
706
+ updateValues = updateValues();
703
707
  if (updateValues) {
704
708
  const updateKey = Object.entries(updateValues);
705
709
  sql += `\nDO UPDATE SET\n${updateKey.map(([key, v = "EXCLUDED." + key]) => key + " = " + v).join(",\n")}`;
706
710
  }
707
711
  else
708
712
  sql += "DO NOTHING";
709
- if (where)
710
- sql += "\nWHERE " + where;
713
+ sql += where(inputWhere);
711
714
  }
712
715
  }
713
716
  return sql;
714
717
  }
715
- insertWithResult(values, returns, option) {
716
- let sql = this.insert(values, option);
717
- return genRetuningSql(sql, returns, values instanceof SqlQueryStatement ? values.columns : this.columns);
718
+ insertWithResult(values, returns, columns, option) {
719
+ let sql = this.insert(values, columns, option);
720
+ return genRetuningSql(sql, returns);
718
721
  }
722
+ /**
723
+ * @example
724
+ * ```ts
725
+ * table.update("age=3, name='hi'") // "UPDATE table SET age=3, name='hi'"
726
+ * table.update({age:3, name:"hi"}) // "UPDATE table SET age=3, name='hi'"
727
+ * ```
728
+ */
719
729
  update(values, option = {}) {
720
- const updateKey = Object.entries(values);
721
- if (updateKey.length === 0)
722
- throw new Error("值不能为空");
723
- let setList = [];
724
- for (const [k, v] of updateKey) {
725
- if (v === undefined)
726
- continue;
727
- setList.push(k + " = " + this.statement.toSqlStr(v));
730
+ if (typeof values === "function")
731
+ values = values();
732
+ let setStr;
733
+ if (typeof values === "string")
734
+ setStr = values;
735
+ else {
736
+ const updateKey = Object.entries(values);
737
+ let setList = [];
738
+ for (const [k, v] of updateKey) {
739
+ if (v === undefined)
740
+ continue;
741
+ setList.push(k + " = " + this.statement.toSqlStr(v));
742
+ }
743
+ setStr = setList.join(",\n");
728
744
  }
729
- let sql = `UPDATE ${this.name}\nSET ${setList.join(",\n")}`;
730
- if (option.where)
731
- sql += where(option.where);
745
+ if (!setStr)
746
+ throw new Error("值不能为空");
747
+ let sql = `UPDATE ${this.name}\nSET ${setStr}`;
748
+ sql += where(option.where);
732
749
  return sql;
733
750
  }
734
751
  updateWithResult(values, returns, option) {
735
752
  let sql = this.update(values, option);
736
- return genRetuningSql(sql, returns, values instanceof SqlQueryStatement ? values.columns : this.columns);
753
+ return genRetuningSql(sql, returns);
737
754
  }
738
755
  delete(option = {}) {
739
756
  let sql = "DELETE FROM " + this.name;
740
- if (option.where)
741
- sql += where(option.where);
757
+ sql += where(option.where);
742
758
  return sql;
743
759
  }
744
760
  deleteWithResult(returns = "*", option) {
745
761
  let sql = this.delete(option);
746
- return genRetuningSql(sql, returns, this.columns);
762
+ return genRetuningSql(sql, returns);
747
763
  }
748
764
  }
749
- function genRetuningSql(sql, returns, tableColumns) {
765
+ function genRetuningSql(sql, returns) {
750
766
  let columnsStr;
751
- let columns;
752
767
  if (returns === "*") {
753
- columns = tableColumns;
754
768
  columnsStr = "*";
755
769
  }
756
770
  else {
757
771
  const res = selectColumnsOrTable(returns);
758
772
  columnsStr = res.sqlColumns;
759
- columns = res.columns;
760
773
  }
761
774
  sql += "\nRETURNING " + columnsStr;
762
- return new SqlQueryStatement(sql, columns);
775
+ return new SqlQueryStatement(sql);
763
776
  }
764
777
 
765
778
  /**
@@ -913,8 +926,9 @@ function getErrStr(expect, actual) {
913
926
  */
914
927
  class YourTable extends DbTableQuery {
915
928
  constructor(name, define, sqlValue) {
916
- super(name, Object.keys(define), sqlValue);
929
+ super(name, sqlValue);
917
930
  this.define = define;
931
+ this.columns = Object.keys(define);
918
932
  }
919
933
  getColumnMeta(name) {
920
934
  return Reflect.get(this.define, name);
@@ -2,11 +2,11 @@ import { SqlValuesCreator, SqlRaw } from "../sql_value/sql_value.ts";
2
2
  import { ColumnsSelected, SelectColumns, UpdateRowValue, TableType } from "./type.ts";
3
3
  import { CurrentWhere, Selection } from "./select.ts";
4
4
  import { DbTable, SqlQueryStatement } from "./selectable.ts";
5
- import { ConditionParam } from "../util.ts";
5
+ import { ConditionParam, Constructable } from "../util.ts";
6
6
  /** @public */
7
7
  export declare class DbTableQuery<T extends TableType = Record<string, any>, C extends TableType = Partial<T>> extends DbTable<T> {
8
8
  private statement;
9
- constructor(name: string, columns: readonly string[], statement: SqlValuesCreator);
9
+ constructor(name: string, statement: SqlValuesCreator);
10
10
  fromAs(as?: string): Selection;
11
11
  /** 选择单表全部列 */
12
12
  select(columns: "*", as?: string): CurrentWhere<T>;
@@ -15,35 +15,57 @@ export declare class DbTableQuery<T extends TableType = Record<string, any>, C e
15
15
  * @param columns - 对象选择
16
16
  */
17
17
  select<R extends {
18
- [key in keyof T]?: string | boolean;
19
- } | Record<string, string>>(columns: R, as?: string): CurrentWhere<{
20
- [key in keyof R]: R[key] extends boolean ? key extends keyof T ? T[key] : unknown : R[key] extends keyof T ? T[R[key]] : unknown;
18
+ [key in keyof T]?: boolean;
19
+ }>(columns: Constructable<R>, as?: string): CurrentWhere<{
20
+ [key in keyof R]: key extends keyof T ? T[key] : unknown;
21
21
  }>;
22
22
  /** 选择单表- 所有类型 */
23
- select<R extends {}>(columns: "*" | string[] | {
23
+ select<R extends {}>(columns: Constructable<{
24
24
  [key in keyof R]?: key extends keyof T ? string | boolean : string;
25
- }, as?: string): CurrentWhere<R>;
26
- insert(values: C[] | SqlQueryStatement<C>, option?: InsertOption<T>): string;
27
- insertWithResult<R extends ColumnsSelected<T>>(values: C[] | SqlQueryStatement<C>, returns: R, option?: InsertOption<T>): SqlQueryStatement<SelectColumns<T, R>>;
28
- update(values: UpdateRowValue<T>, option?: UpdateOption): string;
29
- updateWithResult<R extends ColumnsSelected<T>>(values: UpdateRowValue<T>, returns: R, option?: UpdateOption): SqlQueryStatement<SelectColumns<T, R>>;
25
+ } | string>, as?: string): CurrentWhere<R>;
26
+ /**
27
+ * @example
28
+ * ```ts
29
+ * table.insert({age:18, name:"hi"}) // INSERT INTO table(age,name) VALUES (18, 'hi')
30
+ * table.insert([{age:18, name:"hi"}, {age:17, name:"hh"}]) // INSERT INTO table(age,name) VALUES(18, 'hi'), (17, 'hh')
31
+ * ```
32
+ */
33
+ insert(values: Constructable<C | C[]>, option?: InsertOption<T>): string;
34
+ /**
35
+ * @example
36
+ * ```ts
37
+ * table.insert("VALUES (18, 'hi'), (17, 'hh')", ["age","name"]) // INSERT INTO table(age,name) VALUES(18, 'hi'), (17, 'hh')
38
+ * ```
39
+ */
40
+ insert(values: Constructable<string>, columns: string[], option?: InsertOption<T>): string;
41
+ insertWithResult<R extends ColumnsSelected<T>>(values: Constructable<C | C[]>, returns: R, option?: InsertOption<T>): SqlQueryStatement<SelectColumns<T, R>>;
42
+ insertWithResult<R extends ColumnsSelected<T>>(values: Constructable<string>, returns: R, columns: string | string[], option?: InsertOption<T>): SqlQueryStatement<SelectColumns<T, R>>;
43
+ /**
44
+ * @example
45
+ * ```ts
46
+ * table.update("age=3, name='hi'") // "UPDATE table SET age=3, name='hi'"
47
+ * table.update({age:3, name:"hi"}) // "UPDATE table SET age=3, name='hi'"
48
+ * ```
49
+ */
50
+ update(values: Constructable<UpdateRowValue<T> | string>, option?: UpdateOption): string;
51
+ updateWithResult<R extends ColumnsSelected<T>>(values: Constructable<UpdateRowValue<T>>, returns: R, option?: UpdateOption): SqlQueryStatement<SelectColumns<T, R>>;
30
52
  delete(option?: DeleteOption): string;
31
53
  deleteWithResult<R extends ColumnsSelected<T>>(returns?: ColumnsSelected<T> | "*", option?: DeleteOption): SqlQueryStatement<SelectColumns<T, R>>;
32
54
  }
33
55
  /** @public */
34
56
  export interface InsertOption<T extends object> {
35
- conflict?: (keyof T)[];
36
- updateValues?: {
57
+ conflict?: (keyof T)[] | string;
58
+ updateValues?: Constructable<{
37
59
  [key in keyof T]?: undefined | SqlRaw | T[key];
38
- };
39
- where?: ConditionParam;
60
+ } | string | void>;
61
+ where?: Constructable<ConditionParam | void>;
40
62
  }
41
63
  /** @public */
42
64
  export interface UpdateOption {
43
- where?: ConditionParam;
65
+ where?: Constructable<ConditionParam | void>;
44
66
  }
45
67
  /** @public */
46
68
  export interface DeleteOption {
47
- where?: ConditionParam;
69
+ where?: Constructable<ConditionParam | void>;
48
70
  }
49
71
  //# sourceMappingURL=TableQuery.d.ts.map
@@ -1,6 +1,12 @@
1
- import { ColumnsSelectAs } from "./type.ts";
2
- export declare function selectColumnsOrTable(columns: ColumnsSelectAs<any> | string[]): {
1
+ import { Constructable } from "../util.ts";
2
+ export declare function selectColumnsOrTable(columns: Record<string, boolean | string> | string[]): {
3
3
  columns: string[];
4
4
  sqlColumns: string;
5
5
  };
6
+ type ConditionParam = string | string[];
7
+ /**
8
+ * 生成条件语句
9
+ */
10
+ export declare function condition(conditions?: Constructable<ConditionParam | void>, type?: "AND" | "OR"): string;
11
+ export {};
6
12
  //# sourceMappingURL=_statement.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { SqlSelectable, SqlQueryStatement } from "./selectable.ts";
2
- import { OrderByParam, ConditionParam } from "../util.ts";
2
+ import { OrderByParam, ConditionParam, SelectParam, Constructable } from "../util.ts";
3
3
  import type { TableType } from "./type.ts";
4
4
  /** @public */
5
5
  export interface CurrentLimit<T extends TableType> extends SqlQueryStatement<T> {
@@ -7,11 +7,11 @@ export interface CurrentLimit<T extends TableType> extends SqlQueryStatement<T>
7
7
  }
8
8
  /** @public */
9
9
  export interface CurrentOrderBy<T extends TableType> extends CurrentLimit<T> {
10
- orderBy(param: OrderByParam | (() => OrderByParam | void)): CurrentLimit<T>;
10
+ orderBy(param: Constructable<OrderByParam | void>): CurrentLimit<T>;
11
11
  }
12
12
  /** @public */
13
13
  export interface CurrentHaving<T extends TableType> extends CurrentOrderBy<T> {
14
- having(param: ConditionParam | (() => ConditionParam | void)): CurrentLimit<T>;
14
+ having(param: Constructable<ConditionParam | void>): CurrentLimit<T>;
15
15
  }
16
16
  /** @public */
17
17
  export interface CurrentGroupBy<T extends TableType> extends CurrentOrderBy<T> {
@@ -19,25 +19,41 @@ export interface CurrentGroupBy<T extends TableType> extends CurrentOrderBy<T> {
19
19
  }
20
20
  /** @public */
21
21
  export interface CurrentWhere<T extends TableType> extends CurrentGroupBy<T> {
22
- where(param: ConditionParam | (() => ConditionParam | void)): CurrentGroupBy<T>;
22
+ where(param: Constructable<ConditionParam | void>): CurrentGroupBy<T>;
23
23
  }
24
24
  /** @public */
25
25
  export declare class Selection {
26
26
  #private;
27
- static from(selectable: SqlSelectable<any> | string, as?: string): Selection;
28
- constructor(selectable: SqlSelectable<any> | string, as?: string);
27
+ static from(selectable: Constructable<SqlSelectable<any> | string>, as?: string): Selection;
28
+ constructor(selectable: Constructable<SqlSelectable<any> | string>, as?: string);
29
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>(columns: {
30
+ fullJoin(selectable: Constructable<SqlSelectable<any> | string>, as: string | undefined, on: Constructable<ConditionParam>): Selection;
31
+ innerJoin(selectable: Constructable<SqlSelectable<any> | string>, as: string | undefined, on: Constructable<ConditionParam>): Selection;
32
+ leftJoin(selectable: Constructable<SqlSelectable<any> | string>, as: string | undefined, on: Constructable<ConditionParam>): Selection;
33
+ rightJoin(selectable: Constructable<SqlSelectable<any> | string>, as: string | undefined, on: Constructable<ConditionParam>): Selection;
34
+ naturalJoin(selectable: Constructable<SqlSelectable<any> | string>, as?: string | undefined): Selection;
35
+ crossJoin(selectable: Constructable<SqlSelectable<any> | string>, as?: string | undefined): Selection;
36
+ from(selectable: Constructable<SqlSelectable<any> | string>, as?: string): Selection;
37
+ /** 选择全部列 */
38
+ select<T extends TableType = TableType>(columns: "*"): CurrentWhere<T>;
39
+ /**
40
+ * 自定义SQL选择语句
41
+ * @example
42
+ * ```ts
43
+ * selection.select("t.age, count(*) AS c") // SELECT t.age,count(*) AS c FROM ...
44
+ * ```
45
+ */
46
+ select<T extends TableType = TableType>(columns: Constructable<string>): CurrentWhere<T>;
47
+ /**
48
+ * 通过 object 选择 列
49
+ * @example
50
+ * ```ts
51
+ * selection.select({"age":true, c:"count(*)"}) // SELECT age,count(*) AS c FROM ...
52
+ * ```
53
+ */
54
+ select<T extends TableType>(columns: Constructable<{
39
55
  [key in keyof T]: string | boolean;
40
- }): CurrentWhere<T>;
41
- select(columns: "*" | string[] | Record<string, string | boolean>): CurrentWhere<TableType>;
56
+ }>): CurrentWhere<T>;
57
+ select(columns: Constructable<SelectParam>): CurrentWhere<TableType>;
42
58
  }
43
59
  //# sourceMappingURL=select.d.ts.map
@@ -11,9 +11,6 @@ declare const SQL_SELECTABLE: unique symbol;
11
11
  * @public
12
12
  */
13
13
  export declare abstract class SqlSelectable<T extends TableType> {
14
- constructor(columns: ArrayLike<string> | Iterable<string>);
15
- /** 结果列 */
16
- readonly columns: readonly string[];
17
14
  /**
18
15
  * 转成子选择语句, 你可以使用 select form xxx 选择
19
16
  * 如果是 table 则是 table name
@@ -31,7 +28,7 @@ export declare abstract class SqlSelectable<T extends TableType> {
31
28
  */
32
29
  export declare class DbTable<T extends TableType> extends SqlSelectable<T> {
33
30
  readonly name: string;
34
- constructor(name: string, columns: readonly (keyof T)[]);
31
+ constructor(name: string);
35
32
  toSelect(): string;
36
33
  toString(): string;
37
34
  }
@@ -41,8 +38,7 @@ export declare class DbTable<T extends TableType> extends SqlSelectable<T> {
41
38
  */
42
39
  export declare class SqlQueryStatement<T extends TableType = TableType> extends SqlSelectable<T> {
43
40
  #private;
44
- constructor(sql: string, columns: readonly string[]);
45
- constructor(sql: SqlQueryStatement);
41
+ constructor(sql: string | SqlQueryStatement);
46
42
  toString(): string;
47
43
  toSelect(): string;
48
44
  }
@@ -18,25 +18,22 @@ export type PickColumn<T extends {
18
18
  export type UpdateRowValue<T extends object> = {
19
19
  [key in keyof T]?: T[key] | SqlRaw;
20
20
  };
21
- /**
22
- * 选择列并重命名
23
- * @public
24
- */
25
- export type ColumnsSelectAs<T extends TableType> = {
26
- [key in keyof T]?: boolean | string;
27
- };
28
21
  /** @public */
29
22
  export type OrderValue = "ASC" | "DESC";
30
23
  /**
31
24
  * 表的选择参数
32
25
  * @public
33
26
  */
34
- export type ColumnsSelected<T extends TableType> = ColumnsSelectAs<T> | "*";
27
+ export type ColumnsSelected<T extends TableType> = {
28
+ [key in keyof T]?: boolean | string;
29
+ } | "*";
35
30
  /**
36
31
  * 从一个表格选择列,生成新的表格类型
37
32
  * @public
38
33
  */
39
- export type SelectColumns<T extends TableType, R extends ColumnsSelected<T>> = R extends "*" ? T : R extends ColumnsSelectAs<T> ? {
34
+ export type SelectColumns<T extends TableType, R extends ColumnsSelected<T>> = R extends "*" ? T : R extends {
35
+ [key in keyof T]?: boolean | string;
36
+ } ? {
40
37
  [key in keyof T as R[key] extends true ? key : StringOnly<R[key]>]: T[key];
41
38
  } : never;
42
39
  type StringOnly<T> = T extends string ? T : never;
package/dist/util.d.ts CHANGED
@@ -6,29 +6,40 @@ import { OrderValue } from "./select/type.ts";
6
6
  */
7
7
  export declare function getObjectListKeys(objectList: any[], keepUndefinedKey?: boolean): Set<string>;
8
8
  /** @public */
9
+ export type Constructable<T> = T | (() => T);
10
+ /** @public */
9
11
  export type ConditionParam = string | string[];
10
12
  /**
11
13
  * 生成 WHERE 语句
12
14
  * @public
15
+ * @example
13
16
  * ```ts
14
- *
17
+ * where(['a=1','b=2']) // "\nWHERE a=1 AND b=2"
18
+ * where(['a=1','b=2'],"OR") // "\nWHERE a=1 OR b=2"
19
+ * where("a=1 OR b=2") // "\nWHERE a=1 OR b=2"
20
+ * where(()=>"a=1 OR b=2") // "\nWHERE a=1 AND b=2"
21
+ * where([]) // ""
22
+ * where(undefined) // ""
15
23
  * ```
16
24
  */
17
- export declare function where(conditions?: ConditionParam | (() => ConditionParam | void), type?: "AND" | "OR"): string;
25
+ export declare function where(conditions?: Constructable<ConditionParam | void>, type?: "AND" | "OR"): string;
18
26
  /**
19
27
  *
20
28
  * 生成 HAVING 语句
21
29
  * @public
22
30
  */
23
- export declare function having(conditions?: ConditionParam | (() => ConditionParam | void), type?: "AND" | "OR"): string;
31
+ export declare function having(conditions?: Constructable<ConditionParam | void>, type?: "AND" | "OR"): string;
32
+ /** @public */
33
+ export type SelectParam = string | Record<string, string | boolean>;
24
34
  /**
25
35
  * @public
36
+ * @example
26
37
  * ```ts
27
38
  * 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"
39
+ * selectColumns("c1,count(*) AS c2,column as c3") // "c1,count(*) AS c2,column as c3"
29
40
  * ```
30
41
  */
31
- export declare function selectColumns(columns: string[] | Record<string, string | boolean>): string;
42
+ export declare function selectColumns(columns: Constructable<SelectParam>): string;
32
43
  /** @public */
33
44
  export type OrderBehavior = {
34
45
  key: string;
@@ -40,6 +51,7 @@ export type OrderByParam = string | (string | OrderBehavior)[] | Record<string,
40
51
  /**
41
52
  * 生成 ORDER BY 语句, d
42
53
  * @public
54
+ * @example
43
55
  * ```ts
44
56
  * // 以下生成 "\nORDER BY age DESC NULLS FIRST,num ASC"
45
57
  * orderBy("age DESC NULLS FIRST,num ASC");
@@ -54,5 +66,5 @@ export type OrderByParam = string | (string | OrderBehavior)[] | Record<string,
54
66
  * orderBy({}) // ""
55
67
  * ```
56
68
  */
57
- export declare function orderBy(by?: OrderByParam | void | (() => OrderByParam | void)): string;
69
+ export declare function orderBy(by?: Constructable<OrderByParam | void>): string;
58
70
  //# sourceMappingURL=util.d.ts.map
@@ -10,6 +10,7 @@ import { TypeChecker } from "./checker.ts";
10
10
  export declare class YourTable<T extends TableType = TableType, C extends TableType = T> extends DbTableQuery<T, C> {
11
11
  private define;
12
12
  constructor(name: string, define: TableDefined, sqlValue: SqlValuesCreator);
13
+ readonly columns: readonly string[];
13
14
  getColumnMeta(name: keyof T): ColumnMeta<unknown>;
14
15
  createTypeChecker<T>(keys: readonly string[]): TypeChecker<T>;
15
16
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asla/yoursql",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/mod.d.ts",