comparison semiconginev2/storage.nim @ 1218:56781cc0fc7c compiletime-tests

did: renamge main package
author sam <sam@basx.dev>
date Wed, 17 Jul 2024 21:01:37 +0700
parents semicongine/storage.nim@ba1af13233ee
children
comparison
equal deleted inserted replaced
1217:f819a874058f 1218:56781cc0fc7c
1 import ./thirdparty/db_connector/db_sqlite
2
3 const STORAGE_NAME = Path("storage.db")
4 const DEFAULT_KEY_VALUE_TABLE_NAME = "shelf"
5
6 type
7 StorageType* = enum
8 SystemStorage
9 UserStorage
10 # ? level storage type ?
11
12 var db: Table[StorageType, DbConn]
13
14 proc path(storageType: StorageType): Path =
15 case storageType:
16 of SystemStorage:
17 Path(getAppDir()) / STORAGE_NAME
18 of UserStorage:
19 string(Path(getDataDir()) / Path(AppName())).createDir()
20 Path(getDataDir()) / Path(AppName()) / STORAGE_NAME
21
22 proc ensureExists(storageType: StorageType) =
23 if storageType in db:
24 return
25 db[storageType] = open(string(storageType.path), "", "", "")
26
27 proc ensureExists(storageType: StorageType, table: string) =
28 storageType.ensureExists()
29 db[storageType].exec(sql(&"""CREATE TABLE IF NOT EXISTS {table} (
30 key TEXT NOT NULL UNIQUE,
31 value TEXT NOT NULL
32 )"""))
33
34 proc Store*[T](storageType: StorageType, key: string, value: T, table = DEFAULT_KEY_VALUE_TABLE_NAME) =
35 storageType.ensureExists(table)
36 db[storageType].exec(sql(&"""INSERT INTO {table} VALUES(?, ?)
37 ON CONFLICT(key) DO UPDATE SET value=excluded.value
38 """), key, $$value)
39
40 proc Load*[T](storageType: StorageType, key: string, default: T, table = DEFAULT_KEY_VALUE_TABLE_NAME): T =
41 storageType.ensureExists(table)
42 let dbResult = db[storageType].getValue(sql(&"""SELECT value FROM {table} WHERE key = ? """), key)
43 if dbResult == "":
44 return default
45 return to[T](dbResult)
46
47 proc List*[T](storageType: StorageType, table = DEFAULT_KEY_VALUE_TABLE_NAME): seq[string] =
48 storageType.ensureExists(table)
49 for row in db[storageType].fastRows(sql(&"""SELECT key FROM {table}""")):
50 result.add row[0]
51
52 proc Purge*(storageType: StorageType) =
53 storageType.path().string.removeFile()