Last active
August 13, 2025 08:10
-
-
Save vaguinerg/596e735b807ac0ecc3bad4032abd7da0 to your computer and use it in GitHub Desktop.
Tiny key value db in im. inspired by https://github.com/capocasa/limdb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import tables, strutils, os | |
| type | |
| TinyDB* = object | |
| filename: string | |
| data: Table[string, string] | |
| proc init*(filename: string): TinyDB = | |
| result.filename = filename | |
| result.data = initTable[string, string]() | |
| if fileExists(result.filename): | |
| for line in lines(result.filename): | |
| let parts = line.split('\t', 1) | |
| if parts.len == 2: | |
| result.data[parts[0]] = parts[1] | |
| proc save(db: TinyDB) = | |
| let file = open(db.filename, fmWrite) | |
| defer: file.close() | |
| for key, value in db.data: | |
| file.writeLine(key & "\t" & value) | |
| proc `[]=`*[T](db: var TinyDB, key: string, value: T) = | |
| db.data[key] = $value | |
| db.save() | |
| proc `[]`*(db: TinyDB, key: string): string = | |
| db.data.getOrDefault(key) | |
| when isMainModule: | |
| var db: TinyDB = init("my") | |
| db["foo"] = "bar" | |
| echo db["foo"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment