-
Notifications
You must be signed in to change notification settings - Fork 1
/
Updated helper with ts.txt
86 lines (71 loc) · 2.36 KB
/
Updated helper with ts.txt
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
import SQLite, { SQLiteDatabase, ResultSet } from 'react-native-sqlite-storage';
SQLite.DEBUG(true);
SQLite.enablePromise(true);
const databaseConfig = {
name: "MyDatabase.db",
location: "default",
};
interface Item {
id?: number;
name: string;
description: string;
new_column?: string;
}
class DatabaseService {
private async initDB(): Promise<SQLiteDatabase> {
return SQLite.openDatabase(databaseConfig);
}
private closeDatabase(db: SQLiteDatabase): void {
db.close().catch(error => console.error(error));
}
async createTable(): Promise<void> {
const db = await this.initDB();
await db.executeSql(`
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT
)
`);
this.closeDatabase(db);
}
async addItem(item: Item): Promise<ResultSet> {
const db = await this.initDB();
const result = await db.executeSql('INSERT INTO items (name, description) VALUES (?, ?)', [item.name, item.description]);
this.closeDatabase(db);
return result[0];
}
async updateItem(id: number, item: Item): Promise<ResultSet> {
const db = await this.initDB();
const result = await db.executeSql('UPDATE items SET name = ?, description = ? WHERE id = ?', [item.name, item.description, id]);
this.closeDatabase(db);
return result[0];
}
async deleteItem(id: number): Promise<ResultSet> {
const db = await this.initDB();
const result = await db.executeSql('DELETE FROM items WHERE id = ?', [id]);
this.closeDatabase(db);
return result[0];
}
async getItems(): Promise<Item[]> {
const db = await this.initDB();
const [result] = await db.executeSql('SELECT * FROM items', []);
this.closeDatabase(db);
const items: Item[] = [];
for (let i = 0; i < result.rows.length; i++) {
items.push(result.rows.item(i));
}
return items;
}
async updateDatabaseVersion(newVersion: number): Promise<void> {
const db = await this.initDB();
const [result] = await db.executeSql('PRAGMA user_version');
const currentVersion = result.rows.item(0).user_version;
if (currentVersion < newVersion) {
await db.executeSql('ALTER TABLE items ADD COLUMN new_column TEXT');
await db.executeSql(`PRAGMA user_version = ${newVersion}`);
}
this.closeDatabase(db);
}
}
export default new DatabaseService();