forked from devforth/adminforth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite.ts
More file actions
273 lines (245 loc) · 10.8 KB
/
Copy pathsqlite.ts
File metadata and controls
273 lines (245 loc) · 10.8 KB
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
import betterSqlite3 from 'better-sqlite3';
import { IAdminForthDataSourceConnector, AdminForthResource, AdminForthResourceColumn } from '../types/Back.js';
import AdminForthBaseConnector from './baseConnector.js';
import dayjs from 'dayjs';
import { AdminForthDataTypes, AdminForthFilterOperators, AdminForthSortDirections } from '../types/Common.js';
class SQLiteConnector extends AdminForthBaseConnector implements IAdminForthDataSourceConnector {
db: any;
constructor({ url }: { url: string }) {
super();
// create connection here
this.db = betterSqlite3(url.replace('sqlite://', ''));
}
async discoverFields(resource: AdminForthResource): Promise<{[key: string]: AdminForthResourceColumn}> {
const tableName = resource.table;
const stmt = this.db.prepare(`PRAGMA table_info(${tableName})`);
const rows = await stmt.all();
const fieldTypes = {};
rows.forEach((row) => {
const field: any = {};
const baseType = row.type.toLowerCase();
if (baseType == 'int') {
field.type = AdminForthDataTypes.INTEGER;
field._underlineType = 'int';
} else if (baseType.includes('varchar(')) {
field.type = AdminForthDataTypes.STRING;
field._underlineType = 'varchar';
const length = baseType.match(/\d+/);
field.maxLength = length ? parseInt(length[0]) : null;
} else if (baseType == 'text') {
field.type = AdminForthDataTypes.TEXT;
field._underlineType = 'text';
} else if (baseType.includes('decimal(')) {
field.type = AdminForthDataTypes.DECIMAL;
field._underlineType = 'decimal';
const [precision, scale] = baseType.match(/\d+/g);
field.precision = parseInt(precision);
field.scale = parseInt(scale);
} else if (baseType == 'real') {
field.type = AdminForthDataTypes.FLOAT; //8-byte IEEE floating point number. It
field._underlineType = 'real';
} else if (baseType == 'timestamp') {
field.type = AdminForthDataTypes.DATETIME;
field._underlineType = 'timestamp';
} else if (baseType == 'boolean') {
field.type = AdminForthDataTypes.BOOLEAN;
field._underlineType = 'boolean';
} else if (baseType == 'datetime') {
field.type = AdminForthDataTypes.DATETIME;
field._underlineType = 'datetime';
} else {
field.type = 'unknown'
}
field._baseTypeDebug = baseType;
field.required = row.notnull == 1;
field.primaryKey = row.pk == 1;
field.default = row.dflt_value;
fieldTypes[row.name] = field
});
return fieldTypes;
}
getFieldValue(field: AdminForthResourceColumn, value: any): any {
if (field.type == AdminForthDataTypes.DATETIME) {
if (!value) {
return null;
}
if (field._underlineType == 'timestamp' || field._underlineType == 'int') {
return dayjs.unix(+value).toISOString();
} else if (field._underlineType == 'varchar') {
return dayjs(value).toISOString();
} else if (field._underlineType == 'datetime') {
return dayjs(value).toISOString();
} else {
throw new Error(`AdminForth does not support row type: ${field._underlineType} for timestamps, use VARCHAR (with iso strings) or TIMESTAMP/INT (with unix timestamps). Issue in field "${field.name}"`);
}
} else if (field.type == AdminForthDataTypes.DATE) {
if (!value) {
return null;
}
return dayjs(value).toISOString().split('T')[0];
} else if (field.type == AdminForthDataTypes.BOOLEAN) {
return !!value;
} else if (field.type == AdminForthDataTypes.JSON) {
if (field._underlineType == 'text' || field._underlineType == 'varchar') {
try {
return JSON.parse(value);
} catch (e) {
return {'error': `Failed to parse JSON: ${e.message}`}
}
} else {
console.error(`AdminForth: JSON field is not a string/text but ${field._underlineType}, this is not supported yet`);
}
}
return value;
}
setFieldValue(field: AdminForthResourceColumn, value: any): any {
if (field.type == AdminForthDataTypes.DATETIME) {
if (!value) {
return null;
}
if (field._underlineType == 'timestamp' || field._underlineType == 'int') {
// value is iso string now, convert to unix timestamp
return dayjs(value).unix();
} else if (field._underlineType == 'varchar') {
// value is iso string now, convert to unix timestamp
return dayjs(value).toISOString();
} else {
return value;
}
} else if (field.type == AdminForthDataTypes.BOOLEAN) {
return value ? 1 : 0;
} else if (field.type == AdminForthDataTypes.JSON) {
// check underline type is text or string
if (field._underlineType == 'text' || field._underlineType == 'varchar') {
return JSON.stringify(value);
} else {
console.error(`AdminForth: JSON field is not a string/text but ${field._underlineType}, this is not supported yet`);
}
}
return value;
}
OperatorsMap = {
[AdminForthFilterOperators.EQ]: '=',
[AdminForthFilterOperators.NE]: '!=',
[AdminForthFilterOperators.GT]: '>',
[AdminForthFilterOperators.LT]: '<',
[AdminForthFilterOperators.GTE]: '>=',
[AdminForthFilterOperators.LTE]: '<=',
[AdminForthFilterOperators.LIKE]: 'LIKE',
[AdminForthFilterOperators.ILIKE]: 'ILIKE',
[AdminForthFilterOperators.IN]: 'IN',
[AdminForthFilterOperators.NIN]: 'NOT IN',
};
SortDirectionsMap = {
[AdminForthSortDirections.asc]: 'ASC',
[AdminForthSortDirections.desc]: 'DESC',
};
whereClause(filters) {
return filters.length ? `WHERE ${filters.map((f, i) => {
let placeholder = '?';
let field = f.field;
let operator = this.OperatorsMap[f.operator];
if (f.operator == AdminForthFilterOperators.IN || f.operator == AdminForthFilterOperators.NIN) {
placeholder = `(${f.value.map(() => '?').join(', ')})`;
} else if (f.operator == AdminForthFilterOperators.ILIKE) {
placeholder = `LOWER(?)`;
field = `LOWER(${f.field})`;
operator = 'LIKE';
} else if (f.operator == AdminForthFilterOperators.NE) {
if (f.value === null) {
operator = 'IS NOT';
placeholder = 'NULL';
} else {
// for not equal, we need to add a null check
// because nullish field will not match != value
placeholder = `${placeholder} OR ${field} IS NULL)`;
field = `(${field}`;
}
}
return `${field} ${operator} ${placeholder}`
}).join(' AND ')}` : '';
}
whereParams(filters) {
return filters.reduce((acc, f) => {
if (f.operator == AdminForthFilterOperators.LIKE || f.operator == AdminForthFilterOperators.ILIKE) {
acc.push(`%${f.value}%`);
} else if (f.operator == AdminForthFilterOperators.IN || f.operator == AdminForthFilterOperators.NIN) {
acc.push(...f.value);
} else {
acc.push(f.value);
}
return acc;
}, []);
}
async getDataWithOriginalTypes({ resource, limit, offset, sort, filters }): Promise<any[]> {
const columns = resource.dataSourceColumns.map((col) => col.name).join(', ');
const tableName = resource.table;
const where = this.whereClause(filters);
const filterValues = this.whereParams(filters);
const orderBy = sort.length ? `ORDER BY ${sort.map((s) => `${s.field} ${this.SortDirectionsMap[s.direction]}`).join(', ')}` : '';
const q = `SELECT ${columns} FROM ${tableName} ${where} ${orderBy} LIMIT ? OFFSET ?`;
const stmt = this.db.prepare(q);
const d = [...filterValues, limit, offset];
if (process.env.HEAVY_DEBUG_QUERY) {
console.log('🪲📜 SQLITE Q', q, 'params:', d);
}
const rows = await stmt.all(d);
return rows.map((row) => {
const newRow = {};
for (const [key, value] of Object.entries(row)) {
newRow[key] = value;
}
return newRow;
})
}
async getCount({ resource, filters }) {
const tableName = resource.table;
const where = this.whereClause(filters);
const filterValues = this.whereParams(filters);
const q = `SELECT COUNT(*) FROM ${tableName} ${where}`;
if (process.env.HEAVY_DEBUG_QUERY) {
console.log('🪲📜 SQLITE Q', q, 'params:', filterValues);
}
const totalStmt = this.db.prepare(q);
return totalStmt.get([...filterValues])['COUNT(*)'];
}
async getMinMaxForColumnsWithOriginalTypes({ resource, columns }: { resource: AdminForthResource, columns: AdminForthResourceColumn[] }): Promise<{ [key: string]: { min: any, max: any } }> {
const tableName = resource.table;
const result = {};
await Promise.all(columns.map(async (col) => {
const stmt = await this.db.prepare(`SELECT MIN(${col.name}) as min, MAX(${col.name}) as max FROM ${tableName}`);
const { min, max } = stmt.get();
result[col.name] = {
min, max,
};
}))
return result;
}
async createRecordOriginalValues({ resource, record }: { resource: AdminForthResource, record: any }) {
const tableName = resource.table;
const columns = Object.keys(record);
const placeholders = columns.map(() => '?').join(', ');
const values = columns.map((colName) => record[colName]);
const q = this.db.prepare(`INSERT INTO ${tableName} (${columns.join(', ')}) VALUES (${placeholders})`)
await q.run(values);
}
async updateRecordOriginalValues({ resource, recordId, newValues }: { resource: AdminForthResource, recordId: any, newValues: any }) {
const columnsWithPlaceholders = Object.keys(newValues).map((col) => `${col} = ?`);
const values = [...Object.values(newValues), recordId];
const q = `UPDATE ${resource.table} SET ${columnsWithPlaceholders} WHERE ${this.getPrimaryKey(resource)} = ?`;
if (process.env.HEAVY_DEBUG_QUERY) {
console.log('🪲📜 SQLITE Q', q, 'params:', values);
}
const query = this.db.prepare(q);
await query.run(values);
}
async deleteRecord({ resource, recordId }: { resource: AdminForthResource, recordId: any }): Promise<boolean> {
const q = this.db.prepare(`DELETE FROM ${resource.table} WHERE ${this.getPrimaryKey(resource)} = ?`);
const res = await q.run(recordId);
return res.changes > 0;
}
close() {
this.db.close();
}
}
export default SQLiteConnector;