-
Notifications
You must be signed in to change notification settings - Fork 1
/
KiZooNa.js
333 lines (298 loc) · 9.86 KB
/
KiZooNa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class RawString extends String { }
class DB {
constructor(config) {
this.config = config;
}
raw(string) {
return new RawString(string)
}
select(select) {
this.select_list = this.select_list ? [...this.select_list, select] : [select]
return this
}
distinct() {
this._distinct = true
return this
}
table(table) {
this.table_name = table
return this
}
from(table) {
return this.table(table)
}
where(column, operator, value) {
if (value === undefined) {
value = operator
operator = '='
}
this.where_list = this.where_list ? [...this.where_list, { column, operator, value }] : [{ column, operator, value }]
return this
}
groupBy(column) {
this.group_by_list = this.group_by_list ? [...this.group_by_list, { column }] : [{ column }]
return this
}
orderBy(column) {
this.order_by_list = this.order_by_list ? [...this.order_by_list, { column }] : [{ column }]
return this
}
orderByDesc(column) {
this.order_by_list = this.order_by_list ? [...this.order_by_list, { column, direction: 'DESC' }] : [{ column, direction: 'DESC' }]
return this
}
async oldest() {
this.orderBy('created_at')
return this
}
async latest() {
this.orderByDesc('created_at')
return this
}
limit(limit) {
this._limit = limit
return this
}
offset(offset) {
this._offset = offset
return this
}
async get() {
let sql = 'SELECT'
if (this._distinct) {
sql += ' DISTINCT'
}
sql += ` ${this.select_list ? this.select_list.join(', ') : '*'}`
if (this.table_name) {
sql += ` FROM ${this.table_name}`
}
if (this.where_list) {
sql += ` WHERE ` + this.where_list.map(({ column, operator, value }) => `${column} ${operator} ${JSON.stringify(value).replaceAll("\"", "'")}`).join(' AND ')
}
if (this.group_by_list) {
sql += ` GROUP BY ` + this.group_by_list.map(({ column }) => column).join(', ')
}
if (this.order_by_list) {
sql += ` ORDER BY ` + this.order_by_list.map(({ column, direction }) => column + (direction ? ` ${direction}` : '')).join(', ')
}
if (this._limit) {
sql += ` LIMIT ${this._limit}`
}
if (this._offset) {
sql += ` OFFSET ${this._offset}`
}
return this.query(sql)
}
first() {
this.fetch = true
return this.get()
}
value(column) {
this.fetchColumn = true
if (column && this.select_list) {
this.fetchColumn_column = this.select_list.indexOf(column)
}
return this.get()
}
find(id) {
this.where('id', id)
return this.first()
}
pluck(value_column, key_column) {
if (key_column) {
this.select_list = [key_column, value_column]
this.fetchAll_mode = 'PDO::FETCH_KEY_PAIR'
} else {
this.select_list = [value_column]
this.fetchAll_mode = 'PDO::FETCH_COLUMN'
}
return this.get()
}
count() {
this.select_list = ['COUNT(*)']
return this.value()
}
max(column) {
this.select_list = [`MAX(${column})`]
return this.value()
}
min(column) {
this.select_list = [`MIN(${column})`]
return this.value()
}
avg(column) {
this.select_list = [`AVG(${column})`]
return this.value().then(Number)
}
sum(column) {
this.select_list = [`SUM(${column})`]
return this.value().then(Number)
}
insert(rows) {
this.rowCount = true
if (!Array.isArray(rows)) rows = [rows]
const placeholder = rows.map(row => `(${Object.values(row).map(value => value instanceof RawString ? value : '?').join(', ')})`).join(', ')
const values = rows.flatMap(row => Object.values(row).filter(value => !(value instanceof RawString)))
return this.query(`INSERT INTO ${this.table_name} (${Object.keys(rows[0]).join(', ')}) VALUES ${placeholder}`, values)
}
insertGetId(rows) {
this.lastInsertId = true
if (!Array.isArray(rows)) rows = [rows]
const placeholder = rows.map(row => `(${Object.values(row).map(value => value instanceof RawString ? value : '?').join(', ')})`).join(', ')
const values = rows.flatMap(row => Object.values(row).filter(value => !(value instanceof RawString)))
return this.query(`INSERT INTO ${this.table_name} (${Object.keys(rows[0]).join(', ')}) VALUES ${placeholder}`, values)
}
update($data) {
this.rowCount = true
const where_string = this.where_list ? ` WHERE ` + this.where_list.map(({ column, operator, value }) => `${column} ${operator} ${JSON.stringify(value).replaceAll("\"", "'")}`).join(' AND ') : ''
return this.query(`UPDATE ${this.table_name} SET ${Object.keys($data).map(column => column + ' = ?').join(', ')}${where_string}`, Object.values($data))
}
delete() {
this.rowCount = true
const where_string = this.where_list ? ` WHERE ` + this.where_list.map(({ column, operator, value }) => `${column} ${operator} ${JSON.stringify(value).replaceAll("\"", "'")}`).join(' AND ') : ''
return this.query(`DELETE FROM ${this.table_name}${where_string}`)
}
async query(query, params) {
if (this.config.debug) console.log('query:', query, 'params:', params)
const searchParams = new URLSearchParams()
searchParams.set('dsn', this.config.dsn)
searchParams.set('username', this.config.username)
searchParams.set('password', this.config.password)
searchParams.set('query', query)
if (params) {
searchParams.set('params', JSON.stringify(params))
}
if (this.lastInsertId) {
searchParams.set('lastInsertId', this.lastInsertId)
}
if (this.rowCount) {
searchParams.set('rowCount', this.rowCount)
}
if (this.fetch) {
searchParams.set('fetch', this.fetch)
}
if (this.fetchColumn) {
searchParams.set('fetchColumn', this.fetchColumn)
}
if (this.fetchColumn_column) {
searchParams.set('fetchColumn_column', this.fetchColumn_column)
}
if (this.fetchAll_mode) {
searchParams.set('fetchAll_mode', this.fetchAll_mode)
}
this.reset()
const response = await fetch(this.config.url + '?' + searchParams)
const result = await response.json()
if (!response.ok) {
console.error(query, params)
console.error(result)
}
return result
}
reset() {
delete this.select_list
delete this.table_name
delete this.where_list
delete this.group_by_list
delete this.order_by_list
delete this._limit
delete this._offset
delete this.lastInsertId
delete this.rowCount
delete this.fetch
delete this.fetchColumn
delete this.fetchColumn_column
delete this.fetchAll_mode
}
/**
* @param {string} name
* @param {function(Table): void} define_columns
* @returns {Promise<Table>}
*/
async createTable(name, define_columns) {
const table = new Table(name)
define_columns(table)
if (this.config.debug) console.debug({ table })
await this.query(table.toString())
return this
}
async dropTable(name) {
await this.query(`DROP TABLE IF EXISTS ${name}`)
return this
}
}
class Table {
columns = []
constructor(name) {
this.name = name;
}
increments(name) {
this.columns.push({ name, type: 'INT' })
this.autoIncrement()
return this
}
string(name, length = 255) {
this.columns.push({ name, type: `VARCHAR(${length})` })
return this
}
text(name) {
this.columns.push({ name, type: 'TEXT' })
return this
}
integer(name) {
this.columns.push({ name, type: 'INT' })
return this
}
timestamp(name) {
this.columns.push({ name, type: 'TIMESTAMP' })
return this
}
autoIncrement() {
this.columns.at(-1).autoIncrement = true
return this
}
nullable(nullable = true) {
this.columns.at(-1).nullable = nullable
return this
}
default(default_value) {
this.columns.at(-1).default = default_value
return this
}
useCurrent() {
this.columns.at(-1).default = 'CURRENT_TIMESTAMP'
return this
}
useCurrentOnUpdate() {
this.columns.at(-1).default_on_update = 'CURRENT_TIMESTAMP'
return this
}
softDeletes() {
return this
}
toString() {
const columns = []
for (const column of this.columns) {
let column_string = ` ${column.name} ${column.type}`
if (column.nullable === false) {
column_string += ' NOT NULL'
}
if (column.default) {
column_string += ` DEFAULT ${column.default}`
if (column.default_on_update) {
column_string += ` ON UPDATE ${column.default_on_update}`
}
}
if (column.autoIncrement) {
column_string += ' AUTO_INCREMENT'
}
columns.push(column_string)
}
for (const column of this.columns.filter(({ autoIncrement }) => autoIncrement)) {
columns.push(` PRIMARY KEY (${column.name})`)
}
return `CREATE TABLE IF NOT EXISTS ${this.name} (\n${columns.join(',\n')}\n)`
}
}
if (typeof global === 'object') global.DB = DB
if (typeof global === 'object') global.Table = Table