db_sqlite.nim 30 KB

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