db_sqlite.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. ## See also: `db_odbc <db_odbc.html>`_, `db_postgres <db_postgres.html>`_,
  13. ## `db_mysql <db_mysql.html>`_.
  14. ##
  15. ## Parameter substitution
  16. ## ----------------------
  17. ##
  18. ## All ``db_*`` modules support the same form of parameter substitution.
  19. ## That is, using the ``?`` (question mark) to signify the place where a
  20. ## value should be placed. For example:
  21. ##
  22. ## .. code-block:: Nim
  23. ## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
  24. ##
  25. ## Examples
  26. ## --------
  27. ##
  28. ## Opening a connection to a database
  29. ## ==================================
  30. ##
  31. ## .. code-block:: Nim
  32. ## import db_sqlite
  33. ## let db = open("localhost", "user", "password", "dbname")
  34. ## db.close()
  35. ##
  36. ## Creating a table
  37. ## ================
  38. ##
  39. ## .. code-block:: Nim
  40. ## db.exec(sql"DROP TABLE IF EXISTS myTable")
  41. ## db.exec(sql("""CREATE TABLE myTable (
  42. ## id integer,
  43. ## name varchar(50) not null)"""))
  44. ##
  45. ## Inserting data
  46. ## ==============
  47. ##
  48. ## .. code-block:: Nim
  49. ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
  50. ## "Jack")
  51. ##
  52. ## Larger example
  53. ## ==============
  54. ##
  55. ## .. code-block:: nim
  56. ##
  57. ## import db_sqlite, math
  58. ##
  59. ## let theDb = open("mytest.db", nil, nil, nil)
  60. ##
  61. ## theDb.exec(sql"Drop table if exists myTestTbl")
  62. ## theDb.exec(sql("""create table myTestTbl (
  63. ## Id INTEGER PRIMARY KEY,
  64. ## Name VARCHAR(50) NOT NULL,
  65. ## i INT(11),
  66. ## f DECIMAL(18,10))"""))
  67. ##
  68. ## theDb.exec(sql"BEGIN")
  69. ## for i in 1..1000:
  70. ## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  71. ## "Item#" & $i, i, sqrt(i.float))
  72. ## theDb.exec(sql"COMMIT")
  73. ##
  74. ## for x in theDb.fastRows(sql"select * from myTestTbl"):
  75. ## echo x
  76. ##
  77. ## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  78. ## "Item#1001", 1001, sqrt(1001.0))
  79. ## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
  80. ##
  81. ## theDb.close()
  82. {.deadCodeElim:on.}
  83. import strutils, sqlite3
  84. import db_common
  85. export db_common
  86. type
  87. DbConn* = PSqlite3 ## encapsulates a database connection
  88. Row* = seq[string] ## a row of a dataset. NULL database values will be
  89. ## converted to nil.
  90. InstantRow* = Pstmt ## a handle that can be used to get a row's column
  91. ## text on demand
  92. {.deprecated: [TRow: Row, TDbConn: DbConn].}
  93. proc dbError*(db: DbConn) {.noreturn.} =
  94. ## raises a DbError exception.
  95. var e: ref DbError
  96. new(e)
  97. e.msg = $sqlite3.errmsg(db)
  98. raise e
  99. proc dbQuote*(s: string): string =
  100. ## DB quotes the string.
  101. if s.isNil: return "NULL"
  102. result = "'"
  103. for c in items(s):
  104. if c == '\'': add(result, "''")
  105. else: add(result, c)
  106. add(result, '\'')
  107. proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
  108. result = ""
  109. var a = 0
  110. for c in items(string(formatstr)):
  111. if c == '?':
  112. add(result, dbQuote(args[a]))
  113. inc(a)
  114. else:
  115. add(result, c)
  116. proc tryExec*(db: DbConn, query: SqlQuery,
  117. args: varargs[string, `$`]): bool {.
  118. tags: [ReadDbEffect, WriteDbEffect].} =
  119. ## tries to execute the query and returns true if successful, false otherwise.
  120. var q = dbFormat(query, args)
  121. var stmt: sqlite3.Pstmt
  122. if prepare_v2(db, q, q.len.cint, stmt, nil) == SQLITE_OK:
  123. let x = step(stmt)
  124. if x in {SQLITE_DONE, SQLITE_ROW}:
  125. result = finalize(stmt) == SQLITE_OK
  126. proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  127. tags: [ReadDbEffect, WriteDbEffect].} =
  128. ## executes the query and raises DbError if not successful.
  129. if not tryExec(db, query, args): dbError(db)
  130. proc newRow(L: int): Row =
  131. newSeq(result, L)
  132. for i in 0..L-1: result[i] = ""
  133. proc setupQuery(db: DbConn, query: SqlQuery,
  134. args: varargs[string]): Pstmt =
  135. var q = dbFormat(query, args)
  136. if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db)
  137. proc setRow(stmt: Pstmt, r: var Row, cols: cint) =
  138. for col in 0..cols-1:
  139. setLen(r[col], column_bytes(stmt, col)) # set capacity
  140. setLen(r[col], 0)
  141. let x = column_text(stmt, col)
  142. if not isNil(x): add(r[col], x)
  143. iterator fastRows*(db: DbConn, query: SqlQuery,
  144. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  145. ## Executes the query and iterates over the result dataset.
  146. ##
  147. ## This is very fast, but potentially dangerous. Use this iterator only
  148. ## if you require **ALL** the rows.
  149. ##
  150. ## Breaking the fastRows() iterator during a loop will cause the next
  151. ## database query to raise a DbError exception ``unable to close due to ...``.
  152. var stmt = setupQuery(db, query, args)
  153. var L = (column_count(stmt))
  154. var result = newRow(L)
  155. while step(stmt) == SQLITE_ROW:
  156. setRow(stmt, result, L)
  157. yield result
  158. if finalize(stmt) != SQLITE_OK: dbError(db)
  159. iterator instantRows*(db: DbConn, query: SqlQuery,
  160. args: varargs[string, `$`]): InstantRow
  161. {.tags: [ReadDbEffect].} =
  162. ## same as fastRows but returns a handle that can be used to get column text
  163. ## on demand using []. Returned handle is valid only within the iterator body.
  164. var stmt = setupQuery(db, query, args)
  165. while step(stmt) == SQLITE_ROW:
  166. yield stmt
  167. if finalize(stmt) != SQLITE_OK: dbError(db)
  168. proc toTypeKind(t: var DbType; x: int32) =
  169. case x
  170. of SQLITE_INTEGER:
  171. t.kind = dbInt
  172. t.size = 8
  173. of SQLITE_FLOAT:
  174. t.kind = dbFloat
  175. t.size = 8
  176. of SQLITE_BLOB: t.kind = dbBlob
  177. of SQLITE_NULL: t.kind = dbNull
  178. of SQLITE_TEXT: t.kind = dbVarchar
  179. else: t.kind = dbUnknown
  180. proc setColumns(columns: var DbColumns; x: PStmt) =
  181. let L = column_count(x)
  182. setLen(columns, L)
  183. for i in 0'i32 ..< L:
  184. columns[i].name = $column_name(x, i)
  185. columns[i].typ.name = $column_decltype(x, i)
  186. toTypeKind(columns[i].typ, column_type(x, i))
  187. columns[i].tableName = $column_table_name(x, i)
  188. iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
  189. args: varargs[string, `$`]): InstantRow
  190. {.tags: [ReadDbEffect].} =
  191. ## same as fastRows but returns a handle that can be used to get column text
  192. ## on demand using []. Returned handle is valid only within the iterator body.
  193. var stmt = setupQuery(db, query, args)
  194. setColumns(columns, stmt)
  195. while step(stmt) == SQLITE_ROW:
  196. yield stmt
  197. if finalize(stmt) != SQLITE_OK: dbError(db)
  198. proc `[]`*(row: InstantRow, col: int32): string {.inline.} =
  199. ## returns text for given column of the row
  200. $column_text(row, col)
  201. proc len*(row: InstantRow): int32 {.inline.} =
  202. ## returns number of columns in the row
  203. column_count(row)
  204. proc getRow*(db: DbConn, query: SqlQuery,
  205. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  206. ## retrieves a single row. If the query doesn't return any rows, this proc
  207. ## will return a Row with empty strings for each column.
  208. var stmt = setupQuery(db, query, args)
  209. var L = (column_count(stmt))
  210. result = newRow(L)
  211. if step(stmt) == SQLITE_ROW:
  212. setRow(stmt, result, L)
  213. if finalize(stmt) != SQLITE_OK: dbError(db)
  214. proc getAllRows*(db: DbConn, query: SqlQuery,
  215. args: varargs[string, `$`]): seq[Row] {.tags: [ReadDbEffect].} =
  216. ## executes the query and returns the whole result dataset.
  217. result = @[]
  218. for r in fastRows(db, query, args):
  219. result.add(r)
  220. iterator rows*(db: DbConn, query: SqlQuery,
  221. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  222. ## same as `FastRows`, but slower and safe.
  223. for r in fastRows(db, query, args): yield r
  224. proc getValue*(db: DbConn, query: SqlQuery,
  225. args: varargs[string, `$`]): string {.tags: [ReadDbEffect].} =
  226. ## executes the query and returns the first column of the first row of the
  227. ## result dataset. Returns "" if the dataset contains no rows or the database
  228. ## value is NULL.
  229. var stmt = setupQuery(db, query, args)
  230. if step(stmt) == SQLITE_ROW:
  231. let cb = column_bytes(stmt, 0)
  232. if cb == 0:
  233. result = ""
  234. else:
  235. result = newStringOfCap(cb)
  236. add(result, column_text(stmt, 0))
  237. else:
  238. result = ""
  239. if finalize(stmt) != SQLITE_OK: dbError(db)
  240. proc tryInsertID*(db: DbConn, query: SqlQuery,
  241. args: varargs[string, `$`]): int64
  242. {.tags: [WriteDbEffect], raises: [].} =
  243. ## executes the query (typically "INSERT") and returns the
  244. ## generated ID for the row or -1 in case of an error.
  245. var q = dbFormat(query, args)
  246. var stmt: sqlite3.Pstmt
  247. result = -1
  248. if prepare_v2(db, q, q.len.cint, stmt, nil) == SQLITE_OK:
  249. if step(stmt) == SQLITE_DONE:
  250. result = last_insert_rowid(db)
  251. if finalize(stmt) != SQLITE_OK:
  252. result = -1
  253. proc insertID*(db: DbConn, query: SqlQuery,
  254. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  255. ## executes the query (typically "INSERT") and returns the
  256. ## generated ID for the row. For Postgre this adds
  257. ## ``RETURNING id`` to the query, so it only works if your primary key is
  258. ## named ``id``.
  259. result = tryInsertID(db, query, args)
  260. if result < 0: dbError(db)
  261. proc execAffectedRows*(db: DbConn, query: SqlQuery,
  262. args: varargs[string, `$`]): int64 {.
  263. tags: [ReadDbEffect, WriteDbEffect].} =
  264. ## executes the query (typically "UPDATE") and returns the
  265. ## number of affected rows.
  266. exec(db, query, args)
  267. result = changes(db)
  268. proc close*(db: DbConn) {.tags: [DbEffect].} =
  269. ## closes the database connection.
  270. if sqlite3.close(db) != SQLITE_OK: dbError(db)
  271. proc open*(connection, user, password, database: string): DbConn {.
  272. tags: [DbEffect].} =
  273. ## opens a database connection. Raises `EDb` if the connection could not
  274. ## be established. Only the ``connection`` parameter is used for ``sqlite``.
  275. var db: DbConn
  276. if sqlite3.open(connection, db) == SQLITE_OK:
  277. result = db
  278. else:
  279. dbError(db)
  280. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  281. tags: [DbEffect].} =
  282. ## sets the encoding of a database connection, returns true for
  283. ## success, false for failure.
  284. ##
  285. ## Note that the encoding cannot be changed once it's been set.
  286. ## According to SQLite3 documentation, any attempt to change
  287. ## the encoding after the database is created will be silently
  288. ## ignored.
  289. exec(connection, sql"PRAGMA encoding = ?", [encoding])
  290. result = connection.getValue(sql"PRAGMA encoding") == encoding
  291. when not defined(testing) and isMainModule:
  292. var db = open("db.sql", "", "", "")
  293. exec(db, sql"create table tbl1(one varchar(10), two smallint)", [])
  294. exec(db, sql"insert into tbl1 values('hello!',10)", [])
  295. exec(db, sql"insert into tbl1 values('goodbye', 20)", [])
  296. #db.query("create table tbl1(one varchar(10), two smallint)")
  297. #db.query("insert into tbl1 values('hello!',10)")
  298. #db.query("insert into tbl1 values('goodbye', 20)")
  299. for r in db.rows(sql"select * from tbl1", []):
  300. echo(r[0], r[1])
  301. for r in db.instantRows(sql"select * from tbl1", []):
  302. echo(r[0], r[1])
  303. db_sqlite.close(db)