-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.ts
195 lines (170 loc) · 6.39 KB
/
database.ts
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
import * as SQLite from "expo-sqlite"
import {
AnyObjectSchema
} from "yup"
type Status = "success" | "failure"
/**
* Creates or connects the database of the given name with each schema representing a table.
*
* @param {string} dbName The name of the database.
*/
const initializeDatabase = (dbName = "main") => {
const sqlDB = SQLite.openDatabase(`${dbName}.db`)
function table(tableName: string, schema: AnyObjectSchema) {
let command = `CREATE TABLE IF NOT EXISTS ${tableName} (id INTEGER PRIMARY KEY NOT NULL`
type SchemaField = keyof typeof schema.fields
Object.keys(schema.fields).forEach((key) => {
if (key === "id") return
const field = schema.fields[key as SchemaField]
let type = field._type
switch (type) {
case "number":
let isInt = false
for (let test of field.describe().tests) {
if (test.name === "integer") {
isInt = true
break
}
}
if (isInt) type = "INTEGER"
else type = "REAL"
break
case "string":
type = "TEXT"
break
case "boolean":
type = "INTEGER"
break
}
command += `, ${key} ${type}`
})
command += ");"
sqlDB.transaction((tx) => {
tx.executeSql(command)
})
const insert = async <T extends {}>(value: T) => {
const valid = await schema.isValid(value)
if (!valid) throw Error(`${JSON.stringify(value)} is not of the correcttype`)
function checkForID(column: string) {
return column === "id"
}
const columns = Object.keys(value)
const idIndex = columns.findIndex(checkForID)
if (idIndex >= 0) columns.splice(idIndex, 1)
let columnNames = ""
let columnPlaceholders = ""
let columnValues: any[] = []
columns.forEach((column, index) => {
columnNames += index === 0 ? column : `, ${column}`
columnPlaceholders += index === 0 ? "?" : `, ?`
columnValues.push(value[column as keyof T])
})
let command = `INSERT INTO ${tableName} (${columnNames}) VALUES (${columnPlaceholders})`
return new Promise<{ status: Status, data: T | null }>((resolve) => {
sqlDB.transaction((tx) => {
tx.executeSql(
command,
columnValues,
() => {
resolve({ status: "success", data: value })
},
() => {
resolve({ status: "failure", data: null })
return false
}
)
})
})
}
const select = async <T>() => {
const command = `SELECT * FROM ${tableName};`
return new Promise<{ status: Status, data: T[] | null }>((resolve) => {
sqlDB.transaction((tx) => {
tx.executeSql(
command,
[],
(_, { rows: { _array } }: { rows: { _array: T[] } }) => {
resolve({ status: "success", data: _array })
},
() => {
resolve({ status: "failure", data: null })
return false
}
)
})
})
}
const columns = async <T>(columns: (keyof T)[]) => {
let columnStr = ""
columns.forEach((column, index) => {
columnStr += index === 0 ? column.toString() : `, ${column.toString()}`
})
const command = `SELECT ${columnStr} FROM ${tableName};`
return new Promise<{ status: Status, data: T[] | null }>((resolve) => {
sqlDB.transaction((tx) => {
tx.executeSql(
command,
[],
(_, { rows: { _array } }: { rows: { _array: T[] } }) => {
resolve({ status: "success", data: _array })
},
() => {
resolve({ status: "failure", data: null })
return false
}
)
})
})
}
const update = async <T>(id: number, value: T) => {
const command = `UPDATE ${tableName} SET done = 1 WHERE id = ?;`
return new Promise<{ status: Status, data: T }>((resolve) => {
sqlDB.transaction((tx) => {
tx.executeSql(
command,
[id],
() => resolve({ status: "success", data: value }));
})
})
}
const remove = async (id: number) => {
const command = `DELETE FROM ${tableName} WHERE id = ?;`
return new Promise<{ status: Status, data: null }>((resolve) => {
sqlDB.transaction((tx) => {
tx.executeSql(command, [id],
() => {
resolve({ status: "success", data: null })
},
() => {
resolve({ status: "failure", data: null })
return false
})
})
})
}
return {
columns,
insert,
delete: remove,
select,
update,
}
}
return {
table,
}
}
export { initializeDatabase }
/**
*
* Usage
*
const Item = object({
id: number().integer().required(),
done: boolean().required(),
value: string().required(),
})
type Item = InferType<typeof Item>
type SubItem = Pick<Item, "done" | "id">
initializeDatabase("test").table("items", Item).columns<SubItem>(["done", "id"]).then(result => console.log(result))
**/