db_sqlite.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## A higher level `SQLite`:idx: database wrapper. This interface
  10. ## is implemented for other databases too.
  11. ##
  12. ## Basic usage
  13. ## ===========
  14. ##
  15. ## The basic flow of using this module is:
  16. ##
  17. ## 1. Open database connection
  18. ## 2. Execute SQL query
  19. ## 3. Close database connection
  20. ##
  21. ## Parameter substitution
  22. ## ----------------------
  23. ##
  24. ## All `db_*` modules support the same form of parameter substitution.
  25. ## That is, using the `?` (question mark) to signify the place where a
  26. ## value should be placed. For example:
  27. ##
  28. ## ```Nim
  29. ## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)"
  30. ## ```
  31. ##
  32. ## Opening a connection to a database
  33. ## ----------------------------------
  34. ##
  35. ## ```Nim
  36. ## import std/db_sqlite
  37. ##
  38. ## # user, password, database name can be empty.
  39. ## # These params are not used on db_sqlite module.
  40. ## let db = open("mytest.db", "", "", "")
  41. ## db.close()
  42. ## ```
  43. ##
  44. ## Creating a table
  45. ## ----------------
  46. ##
  47. ## ```Nim
  48. ## db.exec(sql"DROP TABLE IF EXISTS my_table")
  49. ## db.exec(sql"""CREATE TABLE my_table (
  50. ## id INTEGER,
  51. ## name VARCHAR(50) NOT NULL
  52. ## )""")
  53. ## ```
  54. ##
  55. ## Inserting data
  56. ## --------------
  57. ##
  58. ## ```Nim
  59. ## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)",
  60. ## "Jack")
  61. ## ```
  62. ##
  63. ## Larger example
  64. ## --------------
  65. ##
  66. ## ```Nim
  67. ## import std/[db_sqlite, math]
  68. ##
  69. ## let db = open("mytest.db", "", "", "")
  70. ##
  71. ## db.exec(sql"DROP TABLE IF EXISTS my_table")
  72. ## db.exec(sql"""CREATE TABLE my_table (
  73. ## id INTEGER PRIMARY KEY,
  74. ## name VARCHAR(50) NOT NULL,
  75. ## i INT(11),
  76. ## f DECIMAL(18, 10)
  77. ## )""")
  78. ##
  79. ## db.exec(sql"BEGIN")
  80. ## for i in 1..1000:
  81. ## db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)",
  82. ## "Item#" & $i, i, sqrt(i.float))
  83. ## db.exec(sql"COMMIT")
  84. ##
  85. ## for x in db.fastRows(sql"SELECT * FROM my_table"):
  86. ## echo x
  87. ##
  88. ## let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f)
  89. ## VALUES (?, ?, ?)""",
  90. ## "Item#1001", 1001, sqrt(1001.0))
  91. ## echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
  92. ##
  93. ## db.close()
  94. ## ```
  95. ##
  96. ## Storing binary data example
  97. ##----------------------------
  98. ##
  99. ## ```nim
  100. ## import std/random
  101. ##
  102. ## ## Generate random float datas
  103. ## var orig = newSeq[float64](150)
  104. ## randomize()
  105. ## for x in orig.mitems:
  106. ## x = rand(1.0)/10.0
  107. ##
  108. ## let db = open("mysqlite.db", "", "", "")
  109. ## block: ## Create database
  110. ## ## Binary datas needs to be of type BLOB in SQLite
  111. ## let createTableStr = sql"""CREATE TABLE test(
  112. ## id INTEGER NOT NULL PRIMARY KEY,
  113. ## data BLOB
  114. ## )
  115. ## """
  116. ## db.exec(createTableStr)
  117. ##
  118. ## block: ## Insert data
  119. ## var id = 1
  120. ## ## Data needs to be converted to seq[byte] to be interpreted as binary by bindParams
  121. ## var dbuf = newSeq[byte](orig.len*sizeof(float64))
  122. ## copyMem(unsafeAddr(dbuf[0]), unsafeAddr(orig[0]), dbuf.len)
  123. ##
  124. ## ## Use prepared statement to insert binary data into database
  125. ## var insertStmt = db.prepare("INSERT INTO test (id, data) VALUES (?, ?)")
  126. ## insertStmt.bindParams(id, dbuf)
  127. ## let bres = db.tryExec(insertStmt)
  128. ## ## Check insert
  129. ## doAssert(bres)
  130. ## # Destroy statement
  131. ## finalize(insertStmt)
  132. ##
  133. ## block: ## Use getValue to select data
  134. ## var dataTest = db.getValue(sql"SELECT data FROM test WHERE id = ?", 1)
  135. ## ## Calculate sequence size from buffer size
  136. ## let seqSize = int(dataTest.len*sizeof(byte)/sizeof(float64))
  137. ## ## Copy binary string data in dataTest into a seq
  138. ## var res: seq[float64] = newSeq[float64](seqSize)
  139. ## copyMem(unsafeAddr(res[0]), addr(dataTest[0]), dataTest.len)
  140. ##
  141. ## ## Check datas obtained is identical
  142. ## doAssert res == orig
  143. ##
  144. ## db.close()
  145. ## ```
  146. ##
  147. ##
  148. ## Note
  149. ## ====
  150. ## This module does not implement any ORM features such as mapping the types from the schema.
  151. ## Instead, a `seq[string]` is returned for each row.
  152. ##
  153. ## The reasoning is as follows:
  154. ## 1. it's close to what many DBs offer natively (`char**`:c:)
  155. ## 2. it hides the number of types that the DB supports
  156. ## (int? int64? decimal up to 10 places? geo coords?)
  157. ## 3. it's convenient when all you do is to forward the data to somewhere else (echo, log, put the data into a new query)
  158. ##
  159. ## See also
  160. ## ========
  161. ##
  162. ## * `db_odbc module <db_odbc.html>`_ for ODBC database wrapper
  163. ## * `db_mysql module <db_mysql.html>`_ for MySQL database wrapper
  164. ## * `db_postgres module <db_postgres.html>`_ for PostgreSQL database wrapper
  165. {.experimental: "codeReordering".}
  166. import sqlite3, macros
  167. import db_common
  168. export db_common
  169. import std/private/[since, dbutils]
  170. when defined(nimPreviewSlimSystem):
  171. import std/assertions
  172. type
  173. DbConn* = PSqlite3 ## Encapsulates a database connection.
  174. Row* = seq[string] ## A row of a dataset. `NULL` database values will be
  175. ## converted to an empty string.
  176. InstantRow* = PStmt ## A handle that can be used to get a row's column
  177. ## text on demand.
  178. SqlPrepared* = distinct PStmt ## a identifier for the prepared queries
  179. proc dbError*(db: DbConn) {.noreturn.} =
  180. ## Raises a `DbError` exception.
  181. ##
  182. ## **Examples:**
  183. ## ```Nim
  184. ## let db = open("mytest.db", "", "", "")
  185. ## if not db.tryExec(sql"SELECT * FROM not_exist_table"):
  186. ## dbError(db)
  187. ## db.close()
  188. ## ```
  189. var e: ref DbError
  190. new(e)
  191. e.msg = $sqlite3.errmsg(db)
  192. raise e
  193. proc dbQuote*(s: string): string =
  194. ## Escapes the `'` (single quote) char to `''`.
  195. ## Because single quote is used for defining `VARCHAR` in SQL.
  196. runnableExamples:
  197. doAssert dbQuote("'") == "''''"
  198. doAssert dbQuote("A Foobar's pen.") == "'A Foobar''s pen.'"
  199. result = "'"
  200. for c in items(s):
  201. if c == '\'': add(result, "''")
  202. else: add(result, c)
  203. add(result, '\'')
  204. proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
  205. dbFormatImpl(formatstr, dbQuote, args)
  206. proc prepare*(db: DbConn; q: string): SqlPrepared {.since: (1, 3).} =
  207. ## Creates a new `SqlPrepared` statement.
  208. if prepare_v2(db, q, q.len.cint,result.PStmt, nil) != SQLITE_OK:
  209. discard finalize(result.PStmt)
  210. dbError(db)
  211. proc tryExec*(db: DbConn, query: SqlQuery,
  212. args: varargs[string, `$`]): bool {.
  213. tags: [ReadDbEffect, WriteDbEffect].} =
  214. ## Tries to execute the query and returns `true` if successful, `false` otherwise.
  215. ##
  216. ## **Examples:**
  217. ## ```Nim
  218. ## let db = open("mytest.db", "", "", "")
  219. ## if not db.tryExec(sql"SELECT * FROM my_table"):
  220. ## dbError(db)
  221. ## db.close()
  222. ## ```
  223. assert(not db.isNil, "Database not connected.")
  224. var q = dbFormat(query, args)
  225. var stmt: sqlite3.PStmt
  226. if prepare_v2(db, q.cstring, q.len.cint, stmt, nil) == SQLITE_OK:
  227. let x = step(stmt)
  228. if x in {SQLITE_DONE, SQLITE_ROW}:
  229. result = finalize(stmt) == SQLITE_OK
  230. else:
  231. discard finalize(stmt)
  232. result = false
  233. proc tryExec*(db: DbConn, stmtName: SqlPrepared): bool {.
  234. tags: [ReadDbEffect, WriteDbEffect].} =
  235. let x = step(stmtName.PStmt)
  236. if x in {SQLITE_DONE, SQLITE_ROW}:
  237. result = true
  238. else:
  239. discard finalize(stmtName.PStmt)
  240. result = false
  241. proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  242. tags: [ReadDbEffect, WriteDbEffect].} =
  243. ## Executes the query and raises a `DbError` exception if not successful.
  244. ##
  245. ## **Examples:**
  246. ## ```Nim
  247. ## let db = open("mytest.db", "", "", "")
  248. ## try:
  249. ## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
  250. ## 1, "item#1")
  251. ## except:
  252. ## stderr.writeLine(getCurrentExceptionMsg())
  253. ## finally:
  254. ## db.close()
  255. ## ```
  256. if not tryExec(db, query, args): dbError(db)
  257. proc newRow(L: int): Row =
  258. newSeq(result, L)
  259. for i in 0..L-1: result[i] = ""
  260. proc setupQuery(db: DbConn, query: SqlQuery,
  261. args: varargs[string]): PStmt =
  262. assert(not db.isNil, "Database not connected.")
  263. var q = dbFormat(query, args)
  264. if prepare_v2(db, q.cstring, q.len.cint, result, nil) != SQLITE_OK: dbError(db)
  265. proc setupQuery(db: DbConn, stmtName: SqlPrepared): SqlPrepared {.since: (1, 3).} =
  266. assert(not db.isNil, "Database not connected.")
  267. result = stmtName
  268. proc setRow(stmt: PStmt, r: var Row, cols: cint) =
  269. for col in 0'i32..cols-1:
  270. let cb = column_bytes(stmt, col)
  271. setLen(r[col], cb) # set capacity
  272. if column_type(stmt, col) == SQLITE_BLOB:
  273. copyMem(addr(r[col][0]), column_blob(stmt, col), cb)
  274. else:
  275. setLen(r[col], 0)
  276. let x = column_text(stmt, col)
  277. if not isNil(x): add(r[col], x)
  278. iterator fastRows*(db: DbConn, query: SqlQuery,
  279. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  280. ## Executes the query and iterates over the result dataset.
  281. ##
  282. ## This is very fast, but potentially dangerous. Use this iterator only
  283. ## if you require **ALL** the rows.
  284. ##
  285. ## **Note:** Breaking the `fastRows()` iterator during a loop will cause the
  286. ## next database query to raise a `DbError` exception `unable to close due
  287. ## to ...`.
  288. ##
  289. ## **Examples:**
  290. ##
  291. ## ```Nim
  292. ## let db = open("mytest.db", "", "", "")
  293. ##
  294. ## # Records of my_table:
  295. ## # | id | name |
  296. ## # |----|----------|
  297. ## # | 1 | item#1 |
  298. ## # | 2 | item#2 |
  299. ##
  300. ## for row in db.fastRows(sql"SELECT id, name FROM my_table"):
  301. ## echo row
  302. ##
  303. ## # Output:
  304. ## # @["1", "item#1"]
  305. ## # @["2", "item#2"]
  306. ##
  307. ## db.close()
  308. ## ```
  309. var stmt = setupQuery(db, query, args)
  310. var L = (column_count(stmt))
  311. var result = newRow(L)
  312. try:
  313. while step(stmt) == SQLITE_ROW:
  314. setRow(stmt, result, L)
  315. yield result
  316. finally:
  317. if finalize(stmt) != SQLITE_OK: dbError(db)
  318. iterator fastRows*(db: DbConn, stmtName: SqlPrepared): Row
  319. {.tags: [ReadDbEffect,WriteDbEffect], since: (1, 3).} =
  320. discard setupQuery(db, stmtName)
  321. var L = (column_count(stmtName.PStmt))
  322. var result = newRow(L)
  323. try:
  324. while step(stmtName.PStmt) == SQLITE_ROW:
  325. setRow(stmtName.PStmt, result, L)
  326. yield result
  327. except:
  328. dbError(db)
  329. iterator instantRows*(db: DbConn, query: SqlQuery,
  330. args: varargs[string, `$`]): InstantRow
  331. {.tags: [ReadDbEffect].} =
  332. ## Similar to `fastRows iterator <#fastRows.i,DbConn,SqlQuery,varargs[string,]>`_
  333. ## but returns a handle that can be used to get column text
  334. ## on demand using `[]`. Returned handle is valid only within the iterator body.
  335. ##
  336. ## **Examples:**
  337. ##
  338. ## ```Nim
  339. ## let db = open("mytest.db", "", "", "")
  340. ##
  341. ## # Records of my_table:
  342. ## # | id | name |
  343. ## # |----|----------|
  344. ## # | 1 | item#1 |
  345. ## # | 2 | item#2 |
  346. ##
  347. ## for row in db.instantRows(sql"SELECT * FROM my_table"):
  348. ## echo "id:" & row[0]
  349. ## echo "name:" & row[1]
  350. ## echo "length:" & $len(row)
  351. ##
  352. ## # Output:
  353. ## # id:1
  354. ## # name:item#1
  355. ## # length:2
  356. ## # id:2
  357. ## # name:item#2
  358. ## # length:2
  359. ##
  360. ## db.close()
  361. ## ```
  362. var stmt = setupQuery(db, query, args)
  363. try:
  364. while step(stmt) == SQLITE_ROW:
  365. yield stmt
  366. finally:
  367. if finalize(stmt) != SQLITE_OK: dbError(db)
  368. iterator instantRows*(db: DbConn, stmtName: SqlPrepared): InstantRow
  369. {.tags: [ReadDbEffect,WriteDbEffect], since: (1, 3).} =
  370. var stmt = setupQuery(db, stmtName).PStmt
  371. try:
  372. while step(stmt) == SQLITE_ROW:
  373. yield stmt
  374. except:
  375. dbError(db)
  376. proc toTypeKind(t: var DbType; x: int32) =
  377. case x
  378. of SQLITE_INTEGER:
  379. t.kind = dbInt
  380. t.size = 8
  381. of SQLITE_FLOAT:
  382. t.kind = dbFloat
  383. t.size = 8
  384. of SQLITE_BLOB: t.kind = dbBlob
  385. of SQLITE_NULL: t.kind = dbNull
  386. of SQLITE_TEXT: t.kind = dbVarchar
  387. else: t.kind = dbUnknown
  388. proc setColumns(columns: var DbColumns; x: PStmt) =
  389. let L = column_count(x)
  390. setLen(columns, L)
  391. for i in 0'i32 ..< L:
  392. columns[i].name = $column_name(x, i)
  393. columns[i].typ.name = $column_decltype(x, i)
  394. toTypeKind(columns[i].typ, column_type(x, i))
  395. columns[i].tableName = $column_table_name(x, i)
  396. iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
  397. args: varargs[string, `$`]): InstantRow
  398. {.tags: [ReadDbEffect].} =
  399. ## Similar to `instantRows iterator <#instantRows.i,DbConn,SqlQuery,varargs[string,]>`_,
  400. ## but sets information about columns to `columns`.
  401. ##
  402. ## **Examples:**
  403. ##
  404. ## ```Nim
  405. ## let db = open("mytest.db", "", "", "")
  406. ##
  407. ## # Records of my_table:
  408. ## # | id | name |
  409. ## # |----|----------|
  410. ## # | 1 | item#1 |
  411. ## # | 2 | item#2 |
  412. ##
  413. ## var columns: DbColumns
  414. ## for row in db.instantRows(columns, sql"SELECT * FROM my_table"):
  415. ## discard
  416. ## echo columns[0]
  417. ##
  418. ## # Output:
  419. ## # (name: "id", tableName: "my_table", typ: (kind: dbNull,
  420. ## # notNull: false, name: "INTEGER", size: 0, maxReprLen: 0, precision: 0,
  421. ## # scale: 0, min: 0, max: 0, validValues: @[]), primaryKey: false,
  422. ## # foreignKey: false)
  423. ##
  424. ## db.close()
  425. ## ```
  426. var stmt = setupQuery(db, query, args)
  427. setColumns(columns, stmt)
  428. try:
  429. while step(stmt) == SQLITE_ROW:
  430. yield stmt
  431. finally:
  432. if finalize(stmt) != SQLITE_OK: dbError(db)
  433. proc `[]`*(row: InstantRow, col: int32): string {.inline.} =
  434. ## Returns text for given column of the row.
  435. ##
  436. ## See also:
  437. ## * `instantRows iterator <#instantRows.i,DbConn,SqlQuery,varargs[string,]>`_
  438. ## example code
  439. $column_text(row, col)
  440. proc unsafeColumnAt*(row: InstantRow, index: int32): cstring {.inline.} =
  441. ## Returns cstring for given column of the row.
  442. ##
  443. ## See also:
  444. ## * `instantRows iterator <#instantRows.i,DbConn,SqlQuery,varargs[string,]>`_
  445. ## example code
  446. column_text(row, index)
  447. proc len*(row: InstantRow): int32 {.inline.} =
  448. ## Returns number of columns in a row.
  449. ##
  450. ## See also:
  451. ## * `instantRows iterator <#instantRows.i,DbConn,SqlQuery,varargs[string,]>`_
  452. ## example code
  453. column_count(row)
  454. proc getRow*(db: DbConn, query: SqlQuery,
  455. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  456. ## Retrieves a single row. If the query doesn't return any rows, this proc
  457. ## will return a `Row` with empty strings for each column.
  458. ##
  459. ## **Examples:**
  460. ##
  461. ## ```Nim
  462. ## let db = open("mytest.db", "", "", "")
  463. ##
  464. ## # Records of my_table:
  465. ## # | id | name |
  466. ## # |----|----------|
  467. ## # | 1 | item#1 |
  468. ## # | 2 | item#2 |
  469. ##
  470. ## doAssert db.getRow(sql"SELECT id, name FROM my_table"
  471. ## ) == Row(@["1", "item#1"])
  472. ## doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?",
  473. ## 2) == Row(@["2", "item#2"])
  474. ##
  475. ## # Returns empty.
  476. ## doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
  477. ## 3, "item#3") == @[]
  478. ## doAssert db.getRow(sql"DELETE FROM my_table WHERE id = ?", 3) == @[]
  479. ## doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?",
  480. ## 1) == @[]
  481. ## db.close()
  482. ## ```
  483. var stmt = setupQuery(db, query, args)
  484. var L = (column_count(stmt))
  485. result = newRow(L)
  486. if step(stmt) == SQLITE_ROW:
  487. setRow(stmt, result, L)
  488. if finalize(stmt) != SQLITE_OK: dbError(db)
  489. proc getAllRows*(db: DbConn, query: SqlQuery,
  490. args: varargs[string, `$`]): seq[Row] {.tags: [ReadDbEffect].} =
  491. ## Executes the query and returns the whole result dataset.
  492. ##
  493. ## **Examples:**
  494. ##
  495. ## ```Nim
  496. ## let db = open("mytest.db", "", "", "")
  497. ##
  498. ## # Records of my_table:
  499. ## # | id | name |
  500. ## # |----|----------|
  501. ## # | 1 | item#1 |
  502. ## # | 2 | item#2 |
  503. ##
  504. ## doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])]
  505. ## db.close()
  506. ## ```
  507. result = @[]
  508. for r in fastRows(db, query, args):
  509. result.add(r)
  510. proc getAllRows*(db: DbConn, stmtName: SqlPrepared): seq[Row]
  511. {.tags: [ReadDbEffect,WriteDbEffect], since: (1, 3).} =
  512. result = @[]
  513. for r in fastRows(db, stmtName):
  514. result.add(r)
  515. iterator rows*(db: DbConn, query: SqlQuery,
  516. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  517. ## Similar to `fastRows iterator <#fastRows.i,DbConn,SqlQuery,varargs[string,]>`_,
  518. ## but slower and safe.
  519. ##
  520. ## **Examples:**
  521. ##
  522. ## ```Nim
  523. ## let db = open("mytest.db", "", "", "")
  524. ##
  525. ## # Records of my_table:
  526. ## # | id | name |
  527. ## # |----|----------|
  528. ## # | 1 | item#1 |
  529. ## # | 2 | item#2 |
  530. ##
  531. ## for row in db.rows(sql"SELECT id, name FROM my_table"):
  532. ## echo row
  533. ##
  534. ## ## Output:
  535. ## ## @["1", "item#1"]
  536. ## ## @["2", "item#2"]
  537. ##
  538. ## db.close()
  539. ## ```
  540. for r in fastRows(db, query, args): yield r
  541. iterator rows*(db: DbConn, stmtName: SqlPrepared): Row
  542. {.tags: [ReadDbEffect,WriteDbEffect], since: (1, 3).} =
  543. for r in fastRows(db, stmtName): yield r
  544. proc getValue*(db: DbConn, query: SqlQuery,
  545. args: varargs[string, `$`]): string {.tags: [ReadDbEffect].} =
  546. ## Executes the query and returns the first column of the first row of the
  547. ## result dataset. Returns `""` if the dataset contains no rows or the database
  548. ## value is `NULL`.
  549. ##
  550. ## **Examples:**
  551. ##
  552. ## ```Nim
  553. ## let db = open("mytest.db", "", "", "")
  554. ##
  555. ## # Records of my_table:
  556. ## # | id | name |
  557. ## # |----|----------|
  558. ## # | 1 | item#1 |
  559. ## # | 2 | item#2 |
  560. ##
  561. ## doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?",
  562. ## 2) == "item#2"
  563. ## doAssert db.getValue(sql"SELECT id, name FROM my_table") == "1"
  564. ## doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1"
  565. ##
  566. ## db.close()
  567. ## ```
  568. var stmt = setupQuery(db, query, args)
  569. if step(stmt) == SQLITE_ROW:
  570. let cb = column_bytes(stmt, 0)
  571. if cb == 0:
  572. result = ""
  573. else:
  574. if column_type(stmt, 0) == SQLITE_BLOB:
  575. result.setLen(cb)
  576. copyMem(addr(result[0]), column_blob(stmt, 0), cb)
  577. else:
  578. result = newStringOfCap(cb)
  579. add(result, column_text(stmt, 0))
  580. else:
  581. result = ""
  582. if finalize(stmt) != SQLITE_OK: dbError(db)
  583. proc getValue*(db: DbConn, stmtName: SqlPrepared): string
  584. {.tags: [ReadDbEffect,WriteDbEffect], since: (1, 3).} =
  585. var stmt = setupQuery(db, stmtName).PStmt
  586. if step(stmt) == SQLITE_ROW:
  587. let cb = column_bytes(stmt, 0)
  588. if cb == 0:
  589. result = ""
  590. else:
  591. if column_type(stmt, 0) == SQLITE_BLOB:
  592. result.setLen(cb)
  593. copyMem(addr(result[0]), column_blob(stmt, 0), cb)
  594. else:
  595. result = newStringOfCap(cb)
  596. add(result, column_text(stmt, 0))
  597. else:
  598. result = ""
  599. proc tryInsertID*(db: DbConn, query: SqlQuery,
  600. args: varargs[string, `$`]): int64
  601. {.tags: [WriteDbEffect], raises: [DbError].} =
  602. ## Executes the query (typically "INSERT") and returns the
  603. ## generated ID for the row or -1 in case of an error.
  604. ##
  605. ## **Examples:**
  606. ##
  607. ## ```Nim
  608. ## let db = open("mytest.db", "", "", "")
  609. ## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
  610. ##
  611. ## doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)",
  612. ## 1, "item#1") == -1
  613. ## db.close()
  614. ## ```
  615. assert(not db.isNil, "Database not connected.")
  616. var q = dbFormat(query, args)
  617. var stmt: sqlite3.PStmt
  618. result = -1
  619. if prepare_v2(db, q.cstring, q.len.cint, stmt, nil) == SQLITE_OK:
  620. if step(stmt) == SQLITE_DONE:
  621. result = last_insert_rowid(db)
  622. if finalize(stmt) != SQLITE_OK:
  623. result = -1
  624. else:
  625. discard finalize(stmt)
  626. proc insertID*(db: DbConn, query: SqlQuery,
  627. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  628. ## Executes the query (typically "INSERT") and returns the
  629. ## generated ID for the row.
  630. ##
  631. ## Raises a `DbError` exception when failed to insert row.
  632. ## For Postgre this adds `RETURNING id` to the query, so it only works
  633. ## if your primary key is named `id`.
  634. ##
  635. ## **Examples:**
  636. ##
  637. ## ```Nim
  638. ## let db = open("mytest.db", "", "", "")
  639. ## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
  640. ##
  641. ## for i in 0..2:
  642. ## let id = db.insertID(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", i, "item#" & $i)
  643. ## echo "LoopIndex = ", i, ", InsertID = ", id
  644. ##
  645. ## # Output:
  646. ## # LoopIndex = 0, InsertID = 1
  647. ## # LoopIndex = 1, InsertID = 2
  648. ## # LoopIndex = 2, InsertID = 3
  649. ##
  650. ## db.close()
  651. ## ```
  652. result = tryInsertID(db, query, args)
  653. if result < 0: dbError(db)
  654. proc tryInsert*(db: DbConn, query: SqlQuery, pkName: string,
  655. args: varargs[string, `$`]): int64
  656. {.tags: [WriteDbEffect], raises: [DbError], since: (1, 3).} =
  657. ## same as tryInsertID
  658. tryInsertID(db, query, args)
  659. proc insert*(db: DbConn, query: SqlQuery, pkName: string,
  660. args: varargs[string, `$`]): int64
  661. {.tags: [WriteDbEffect], since: (1, 3).} =
  662. ## same as insertId
  663. result = tryInsert(db, query, pkName, args)
  664. if result < 0: dbError(db)
  665. proc execAffectedRows*(db: DbConn, query: SqlQuery,
  666. args: varargs[string, `$`]): int64 {.
  667. tags: [ReadDbEffect, WriteDbEffect].} =
  668. ## Executes the query (typically "UPDATE") and returns the
  669. ## number of affected rows.
  670. ##
  671. ## **Examples:**
  672. ##
  673. ## ```Nim
  674. ## let db = open("mytest.db", "", "", "")
  675. ##
  676. ## # Records of my_table:
  677. ## # | id | name |
  678. ## # |----|----------|
  679. ## # | 1 | item#1 |
  680. ## # | 2 | item#2 |
  681. ##
  682. ## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2
  683. ##
  684. ## db.close()
  685. ## ```
  686. exec(db, query, args)
  687. result = changes(db)
  688. proc execAffectedRows*(db: DbConn, stmtName: SqlPrepared): int64
  689. {.tags: [ReadDbEffect, WriteDbEffect],since: (1, 3).} =
  690. exec(db, stmtName)
  691. result = changes(db)
  692. proc close*(db: DbConn) {.tags: [DbEffect].} =
  693. ## Closes the database connection.
  694. ##
  695. ## **Examples:**
  696. ## ```Nim
  697. ## let db = open("mytest.db", "", "", "")
  698. ## db.close()
  699. ## ```
  700. if sqlite3.close(db) != SQLITE_OK: dbError(db)
  701. proc open*(connection, user, password, database: string): DbConn {.
  702. tags: [DbEffect].} =
  703. ## Opens a database connection. Raises a `DbError` exception if the connection
  704. ## could not be established.
  705. ##
  706. ## **Note:** Only the `connection` parameter is used for `sqlite`.
  707. ##
  708. ## **Examples:**
  709. ## ```Nim
  710. ## try:
  711. ## let db = open("mytest.db", "", "", "")
  712. ## ## do something...
  713. ## ## db.getAllRows(sql"SELECT * FROM my_table")
  714. ## db.close()
  715. ## except:
  716. ## stderr.writeLine(getCurrentExceptionMsg())
  717. ## ```
  718. var db: DbConn
  719. if sqlite3.open(connection, db) == SQLITE_OK:
  720. result = db
  721. else:
  722. dbError(db)
  723. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  724. tags: [DbEffect].} =
  725. ## Sets the encoding of a database connection, returns `true` for
  726. ## success, `false` for failure.
  727. ##
  728. ## **Note:** The encoding cannot be changed once it's been set.
  729. ## According to SQLite3 documentation, any attempt to change
  730. ## the encoding after the database is created will be silently
  731. ## ignored.
  732. exec(connection, sql"PRAGMA encoding = ?", [encoding])
  733. result = connection.getValue(sql"PRAGMA encoding") == encoding
  734. proc finalize*(sqlPrepared:SqlPrepared) {.discardable, since: (1, 3).} =
  735. discard finalize(sqlPrepared.PStmt)
  736. template dbBindParamError*(paramIdx: int, val: varargs[untyped]) =
  737. ## Raises a `DbError` exception.
  738. var e: ref DbError
  739. new(e)
  740. e.msg = "error binding param in position " & $paramIdx
  741. raise e
  742. proc bindParam*(ps: SqlPrepared, paramIdx: int, val: int32) {.since: (1, 3).} =
  743. ## Binds a int32 to the specified paramIndex.
  744. if bind_int(ps.PStmt, paramIdx.int32, val) != SQLITE_OK:
  745. dbBindParamError(paramIdx, val)
  746. proc bindParam*(ps: SqlPrepared, paramIdx: int, val: int64) {.since: (1, 3).} =
  747. ## Binds a int64 to the specified paramIndex.
  748. if bind_int64(ps.PStmt, paramIdx.int32, val) != SQLITE_OK:
  749. dbBindParamError(paramIdx, val)
  750. proc bindParam*(ps: SqlPrepared, paramIdx: int, val: int) {.since: (1, 3).} =
  751. ## Binds a int to the specified paramIndex.
  752. when sizeof(int) == 8:
  753. bindParam(ps, paramIdx, val.int64)
  754. else:
  755. bindParam(ps, paramIdx, val.int32)
  756. proc bindParam*(ps: SqlPrepared, paramIdx: int, val: float64) {.since: (1, 3).} =
  757. ## Binds a 64bit float to the specified paramIndex.
  758. if bind_double(ps.PStmt, paramIdx.int32, val) != SQLITE_OK:
  759. dbBindParamError(paramIdx, val)
  760. proc bindNull*(ps: SqlPrepared, paramIdx: int) {.since: (1, 3).} =
  761. ## Sets the bindparam at the specified paramIndex to null
  762. ## (default behaviour by sqlite).
  763. if bind_null(ps.PStmt, paramIdx.int32) != SQLITE_OK:
  764. dbBindParamError(paramIdx)
  765. proc bindParam*(ps: SqlPrepared, paramIdx: int, val: string, copy = true) {.since: (1, 3).} =
  766. ## Binds a string to the specified paramIndex.
  767. ## if copy is true then SQLite makes its own private copy of the data immediately
  768. if bind_text(ps.PStmt, paramIdx.int32, val.cstring, val.len.int32, if copy: SQLITE_TRANSIENT else: SQLITE_STATIC) != SQLITE_OK:
  769. dbBindParamError(paramIdx, val)
  770. proc bindParam*(ps: SqlPrepared, paramIdx: int,val: openArray[byte], copy = true) {.since: (1, 3).} =
  771. ## binds a blob to the specified paramIndex.
  772. ## if copy is true then SQLite makes its own private copy of the data immediately
  773. let len = val.len
  774. if bind_blob(ps.PStmt, paramIdx.int32, val[0].unsafeAddr, len.int32, if copy: SQLITE_TRANSIENT else: SQLITE_STATIC) != SQLITE_OK:
  775. dbBindParamError(paramIdx, val)
  776. macro bindParams*(ps: SqlPrepared, params: varargs[untyped]): untyped {.since: (1, 3).} =
  777. let bindParam = bindSym("bindParam", brOpen)
  778. let bindNull = bindSym("bindNull")
  779. let preparedStatement = genSym()
  780. result = newStmtList()
  781. # Store `ps` in a temporary variable. This prevents `ps` from being evaluated every call.
  782. result.add newNimNode(nnkLetSection).add(newIdentDefs(preparedStatement, newEmptyNode(), ps))
  783. for idx, param in params:
  784. if param.kind != nnkNilLit:
  785. result.add newCall(bindParam, preparedStatement, newIntLitNode idx + 1, param)
  786. else:
  787. result.add newCall(bindNull, preparedStatement, newIntLitNode idx + 1)
  788. macro untypedLen(args: varargs[untyped]): int =
  789. newLit(args.len)
  790. template exec*(db: DbConn, stmtName: SqlPrepared,
  791. args: varargs[typed]): untyped =
  792. when untypedLen(args) > 0:
  793. if reset(stmtName.PStmt) != SQLITE_OK:
  794. dbError(db)
  795. if clear_bindings(stmtName.PStmt) != SQLITE_OK:
  796. dbError(db)
  797. stmtName.bindParams(args)
  798. if not tryExec(db, stmtName): dbError(db)
  799. when not defined(testing) and isMainModule:
  800. var db = open(":memory:", "", "", "")
  801. exec(db, sql"create table tbl1(one varchar(10), two smallint)", [])
  802. exec(db, sql"insert into tbl1 values('hello!',10)", [])
  803. exec(db, sql"insert into tbl1 values('goodbye', 20)", [])
  804. var p1 = db.prepare "create table tbl2(one varchar(10), two smallint)"
  805. exec(db, p1)
  806. finalize(p1)
  807. var p2 = db.prepare "insert into tbl2 values('hello!',10)"
  808. exec(db, p2)
  809. finalize(p2)
  810. var p3 = db.prepare "insert into tbl2 values('goodbye', 20)"
  811. exec(db, p3)
  812. finalize(p3)
  813. #db.query("create table tbl1(one varchar(10), two smallint)")
  814. #db.query("insert into tbl1 values('hello!',10)")
  815. #db.query("insert into tbl1 values('goodbye', 20)")
  816. for r in db.rows(sql"select * from tbl1", []):
  817. echo(r[0], r[1])
  818. for r in db.instantRows(sql"select * from tbl1", []):
  819. echo(r[0], r[1])
  820. var p4 = db.prepare "select * from tbl2"
  821. for r in db.rows(p4):
  822. echo(r[0], r[1])
  823. finalize(p4)
  824. var i5 = 0
  825. var p5 = db.prepare "select * from tbl2"
  826. for r in db.instantRows(p5):
  827. inc i5
  828. echo(r[0], r[1])
  829. assert i5 == 2
  830. finalize(p5)
  831. for r in db.rows(sql"select * from tbl2", []):
  832. echo(r[0], r[1])
  833. for r in db.instantRows(sql"select * from tbl2", []):
  834. echo(r[0], r[1])
  835. var p6 = db.prepare "select * from tbl2 where one = ? "
  836. p6.bindParams("goodbye")
  837. var rowsP3 = 0
  838. for r in db.rows(p6):
  839. rowsP3 = 1
  840. echo(r[0], r[1])
  841. assert rowsP3 == 1
  842. finalize(p6)
  843. var p7 = db.prepare "select * from tbl2 where two=?"
  844. p7.bindParams(20'i32)
  845. when sizeof(int) == 4:
  846. p7.bindParams(20)
  847. var rowsP = 0
  848. for r in db.rows(p7):
  849. rowsP = 1
  850. echo(r[0], r[1])
  851. assert rowsP == 1
  852. finalize(p7)
  853. exec(db, sql"CREATE TABLE photos(ID INTEGER PRIMARY KEY AUTOINCREMENT, photo BLOB)")
  854. var p8 = db.prepare "INSERT INTO photos (ID,PHOTO) VALUES (?,?)"
  855. var d = "abcdefghijklmnopqrstuvwxyz"
  856. p8.bindParams(1'i32, "abcdefghijklmnopqrstuvwxyz")
  857. exec(db, p8)
  858. finalize(p8)
  859. var p10 = db.prepare "INSERT INTO photos (ID,PHOTO) VALUES (?,?)"
  860. p10.bindParams(2'i32,nil)
  861. exec(db, p10)
  862. exec( db, p10, 3, nil)
  863. finalize(p10)
  864. for r in db.rows(sql"select * from photos where ID = 1", []):
  865. assert r[1].len == d.len
  866. assert r[1] == d
  867. var i6 = 0
  868. for r in db.rows(sql"select * from photos where ID = 3", []):
  869. i6 = 1
  870. assert i6 == 1
  871. var p9 = db.prepare("select * from photos where PHOTO is ?")
  872. p9.bindParams(nil)
  873. var rowsP2 = 0
  874. for r in db.rows(p9):
  875. rowsP2 = 1
  876. echo(r[0], repr r[1])
  877. assert rowsP2 == 1
  878. finalize(p9)
  879. db_sqlite.close(db)