|
| 1 | +# Yet another SQLite wrapper for Nim |
| 2 | + |
| 3 | +Features: |
| 4 | + |
| 5 | +1. Design for ARC/ORC, no need manually close connection |
| 6 | +2. Use `importdb` macro to create helper function (see examples) |
| 7 | + |
| 8 | +## Example |
| 9 | + |
| 10 | +Basic usage: |
| 11 | + |
| 12 | +```nim |
| 13 | +import std/tables |
| 14 | +import easy_sqlite3 |
| 15 | +
|
| 16 | +# Bind function argument to sql statment |
| 17 | +# The tuple return value indicate the query will got exactly 1 result |
| 18 | +proc select_1(arg: int): tuple[value: int] {.importdb: "SELECT $arg".} |
| 19 | +
|
| 20 | +var db = initDatabase(":memory:") |
| 21 | +# Use as a method (the statment will be cached, thats why `var` is required) |
| 22 | +echo db.select_1(1).value |
| 23 | +# Got 1 |
| 24 | +
|
| 25 | +# You can bind create statment as well |
| 26 | +proc create_table() {.importdb: """ |
| 27 | + CREATE TABLE mydata(name TEXT PRIMARY KEY NOT NULL, value INT NOT NULL); |
| 28 | +""".} |
| 29 | +
|
| 30 | +# Or insert |
| 31 | +proc insert_data(name: string, value: int) {.importdb: """ |
| 32 | + INSERT INTO mydata(name, value) VALUES ($name, $value); |
| 33 | +""".} |
| 34 | +
|
| 35 | +# And you can create iterator by the same way (the `= discard` is required, since iterator must have body in nim) |
| 36 | +iterator iterate_data(): tuple[name: string, value: int] {.importdb: """ |
| 37 | + SELECT name, value FROM mydata; |
| 38 | +""".} = discard |
| 39 | +
|
| 40 | +const dataset = { |
| 41 | + "A": 0, |
| 42 | + "B": 1, |
| 43 | + "C": 2, |
| 44 | + "D": 3, |
| 45 | +}.toTable |
| 46 | +db.create_table() |
| 47 | +for name, value in dataset: |
| 48 | + db.insert_data name, value |
| 49 | +
|
| 50 | +for name, value in db.iterate_data(): |
| 51 | + assert name in dataset |
| 52 | + assert dataset[name] == value |
| 53 | +``` |
0 commit comments