Mercurial > games > semicongine
comparison semiconginev2/old/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/old/storage.nim@a3eb305bcac2 |
| children |
comparison
equal
deleted
inserted
replaced
| 1217:f819a874058f | 1218:56781cc0fc7c |
|---|---|
| 1 import std/marshal | |
| 2 import std/tables | |
| 3 import std/strformat | |
| 4 import std/paths | |
| 5 import std/os | |
| 6 | |
| 7 import ./thirdparty/db_connector/db_sqlite | |
| 8 | |
| 9 import ./core | |
| 10 | |
| 11 const STORAGE_NAME = Path("storage.db") | |
| 12 const DEFAULT_KEY_VALUE_TABLE_NAME = "shelf" | |
| 13 | |
| 14 type | |
| 15 StorageType* = enum | |
| 16 SystemStorage | |
| 17 UserStorage | |
| 18 # ? level storage type ? | |
| 19 | |
| 20 var db: Table[StorageType, DbConn] | |
| 21 | |
| 22 proc path(storageType: StorageType): Path = | |
| 23 case storageType: | |
| 24 of SystemStorage: | |
| 25 Path(getAppDir()) / STORAGE_NAME | |
| 26 of UserStorage: | |
| 27 string(Path(getDataDir()) / Path(AppName())).createDir() | |
| 28 Path(getDataDir()) / Path(AppName()) / STORAGE_NAME | |
| 29 | |
| 30 proc ensureExists(storageType: StorageType) = | |
| 31 if storageType in db: | |
| 32 return | |
| 33 db[storageType] = open(string(storageType.path), "", "", "") | |
| 34 | |
| 35 proc ensureExists(storageType: StorageType, table: string) = | |
| 36 storageType.ensureExists() | |
| 37 db[storageType].exec(sql(&"""CREATE TABLE IF NOT EXISTS {table} ( | |
| 38 key TEXT NOT NULL UNIQUE, | |
| 39 value TEXT NOT NULL | |
| 40 )""")) | |
| 41 | |
| 42 proc Store*[T](storageType: StorageType, key: string, value: T, table = DEFAULT_KEY_VALUE_TABLE_NAME) = | |
| 43 storageType.ensureExists(table) | |
| 44 db[storageType].exec(sql(&"""INSERT INTO {table} VALUES(?, ?) | |
| 45 ON CONFLICT(key) DO UPDATE SET value=excluded.value | |
| 46 """), key, $$value) | |
| 47 | |
| 48 proc Load*[T](storageType: StorageType, key: string, default: T, table = DEFAULT_KEY_VALUE_TABLE_NAME): T = | |
| 49 storageType.ensureExists(table) | |
| 50 let dbResult = db[storageType].getValue(sql(&"""SELECT value FROM {table} WHERE key = ? """), key) | |
| 51 if dbResult == "": | |
| 52 return default | |
| 53 return to[T](dbResult) | |
| 54 | |
| 55 proc List*[T](storageType: StorageType, table = DEFAULT_KEY_VALUE_TABLE_NAME): seq[string] = | |
| 56 storageType.ensureExists(table) | |
| 57 for row in db[storageType].fastRows(sql(&"""SELECT key FROM {table}""")): | |
| 58 result.add row[0] | |
| 59 | |
| 60 proc Purge*(storageType: StorageType) = | |
| 61 storageType.path().string.removeFile() |
