db_sqlite.nim 30 KB

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