db_sqlite.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. if step(stmt) == SQLITE_DONE:
  124. result = finalize(stmt) == SQLITE_OK
  125. proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  126. tags: [ReadDbEffect, WriteDbEffect].} =
  127. ## executes the query and raises DbError if not successful.
  128. if not tryExec(db, query, args): dbError(db)
  129. proc newRow(L: int): Row =
  130. newSeq(result, L)
  131. for i in 0..L-1: result[i] = ""
  132. proc setupQuery(db: DbConn, query: SqlQuery,
  133. args: varargs[string]): Pstmt =
  134. var q = dbFormat(query, args)
  135. if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db)
  136. proc setRow(stmt: Pstmt, r: var Row, cols: cint) =
  137. for col in 0..cols-1:
  138. setLen(r[col], column_bytes(stmt, col)) # set capacity
  139. setLen(r[col], 0)
  140. let x = column_text(stmt, col)
  141. if not isNil(x): add(r[col], x)
  142. iterator fastRows*(db: DbConn, query: SqlQuery,
  143. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  144. ## Executes the query and iterates over the result dataset.
  145. ##
  146. ## This is very fast, but potentially dangerous. Use this iterator only
  147. ## if you require **ALL** the rows.
  148. ##
  149. ## Breaking the fastRows() iterator during a loop will cause the next
  150. ## database query to raise a DbError exception ``unable to close due to ...``.
  151. var stmt = setupQuery(db, query, args)
  152. var L = (column_count(stmt))
  153. var result = newRow(L)
  154. while step(stmt) == SQLITE_ROW:
  155. setRow(stmt, result, L)
  156. yield result
  157. if finalize(stmt) != SQLITE_OK: dbError(db)
  158. iterator instantRows*(db: DbConn, query: SqlQuery,
  159. args: varargs[string, `$`]): InstantRow
  160. {.tags: [ReadDbEffect].} =
  161. ## same as fastRows but returns a handle that can be used to get column text
  162. ## on demand using []. Returned handle is valid only within the iterator body.
  163. var stmt = setupQuery(db, query, args)
  164. while step(stmt) == SQLITE_ROW:
  165. yield stmt
  166. if finalize(stmt) != SQLITE_OK: dbError(db)
  167. proc toTypeKind(t: var DbType; x: int32) =
  168. case x
  169. of SQLITE_INTEGER:
  170. t.kind = dbInt
  171. t.size = 8
  172. of SQLITE_FLOAT:
  173. t.kind = dbFloat
  174. t.size = 8
  175. of SQLITE_BLOB: t.kind = dbBlob
  176. of SQLITE_NULL: t.kind = dbNull
  177. of SQLITE_TEXT: t.kind = dbVarchar
  178. else: t.kind = dbUnknown
  179. proc setColumns(columns: var DbColumns; x: PStmt) =
  180. let L = column_count(x)
  181. setLen(columns, L)
  182. for i in 0'i32 ..< L:
  183. columns[i].name = $column_name(x, i)
  184. columns[i].typ.name = $column_decltype(x, i)
  185. toTypeKind(columns[i].typ, column_type(x, i))
  186. columns[i].tableName = $column_table_name(x, i)
  187. iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
  188. args: varargs[string, `$`]): InstantRow
  189. {.tags: [ReadDbEffect].} =
  190. ## same as fastRows but returns a handle that can be used to get column text
  191. ## on demand using []. Returned handle is valid only within the iterator body.
  192. var stmt = setupQuery(db, query, args)
  193. setColumns(columns, stmt)
  194. while step(stmt) == SQLITE_ROW:
  195. yield stmt
  196. if finalize(stmt) != SQLITE_OK: dbError(db)
  197. proc `[]`*(row: InstantRow, col: int32): string {.inline.} =
  198. ## returns text for given column of the row
  199. $column_text(row, col)
  200. proc len*(row: InstantRow): int32 {.inline.} =
  201. ## returns number of columns in the row
  202. column_count(row)
  203. proc getRow*(db: DbConn, query: SqlQuery,
  204. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  205. ## retrieves a single row. If the query doesn't return any rows, this proc
  206. ## will return a Row with empty strings for each column.
  207. var stmt = setupQuery(db, query, args)
  208. var L = (column_count(stmt))
  209. result = newRow(L)
  210. if step(stmt) == SQLITE_ROW:
  211. setRow(stmt, result, L)
  212. if finalize(stmt) != SQLITE_OK: dbError(db)
  213. proc getAllRows*(db: DbConn, query: SqlQuery,
  214. args: varargs[string, `$`]): seq[Row] {.tags: [ReadDbEffect].} =
  215. ## executes the query and returns the whole result dataset.
  216. result = @[]
  217. for r in fastRows(db, query, args):
  218. result.add(r)
  219. iterator rows*(db: DbConn, query: SqlQuery,
  220. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  221. ## same as `FastRows`, but slower and safe.
  222. for r in fastRows(db, query, args): yield r
  223. proc getValue*(db: DbConn, query: SqlQuery,
  224. args: varargs[string, `$`]): string {.tags: [ReadDbEffect].} =
  225. ## executes the query and returns the first column of the first row of the
  226. ## result dataset. Returns "" if the dataset contains no rows or the database
  227. ## value is NULL.
  228. var stmt = setupQuery(db, query, args)
  229. if step(stmt) == SQLITE_ROW:
  230. let cb = column_bytes(stmt, 0)
  231. if cb == 0:
  232. result = ""
  233. else:
  234. result = newStringOfCap(cb)
  235. add(result, column_text(stmt, 0))
  236. else:
  237. result = ""
  238. if finalize(stmt) != SQLITE_OK: dbError(db)
  239. proc tryInsertID*(db: DbConn, query: SqlQuery,
  240. args: varargs[string, `$`]): int64
  241. {.tags: [WriteDbEffect], raises: [].} =
  242. ## executes the query (typically "INSERT") and returns the
  243. ## generated ID for the row or -1 in case of an error.
  244. var q = dbFormat(query, args)
  245. var stmt: sqlite3.Pstmt
  246. result = -1
  247. if prepare_v2(db, q, q.len.cint, stmt, nil) == SQLITE_OK:
  248. if step(stmt) == SQLITE_DONE:
  249. result = last_insert_rowid(db)
  250. if finalize(stmt) != SQLITE_OK:
  251. result = -1
  252. proc insertID*(db: DbConn, query: SqlQuery,
  253. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  254. ## executes the query (typically "INSERT") and returns the
  255. ## generated ID for the row. For Postgre this adds
  256. ## ``RETURNING id`` to the query, so it only works if your primary key is
  257. ## named ``id``.
  258. result = tryInsertID(db, query, args)
  259. if result < 0: dbError(db)
  260. proc execAffectedRows*(db: DbConn, query: SqlQuery,
  261. args: varargs[string, `$`]): int64 {.
  262. tags: [ReadDbEffect, WriteDbEffect].} =
  263. ## executes the query (typically "UPDATE") and returns the
  264. ## number of affected rows.
  265. exec(db, query, args)
  266. result = changes(db)
  267. proc close*(db: DbConn) {.tags: [DbEffect].} =
  268. ## closes the database connection.
  269. if sqlite3.close(db) != SQLITE_OK: dbError(db)
  270. proc open*(connection, user, password, database: string): DbConn {.
  271. tags: [DbEffect].} =
  272. ## opens a database connection. Raises `EDb` if the connection could not
  273. ## be established. Only the ``connection`` parameter is used for ``sqlite``.
  274. var db: DbConn
  275. if sqlite3.open(connection, db) == SQLITE_OK:
  276. result = db
  277. else:
  278. dbError(db)
  279. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  280. tags: [DbEffect].} =
  281. ## sets the encoding of a database connection, returns true for
  282. ## success, false for failure.
  283. ##
  284. ## Note that the encoding cannot be changed once it's been set.
  285. ## According to SQLite3 documentation, any attempt to change
  286. ## the encoding after the database is created will be silently
  287. ## ignored.
  288. exec(connection, sql"PRAGMA encoding = ?", [encoding])
  289. result = connection.getValue(sql"PRAGMA encoding") == encoding
  290. when not defined(testing) and isMainModule:
  291. var db = open("db.sql", "", "", "")
  292. exec(db, sql"create table tbl1(one varchar(10), two smallint)", [])
  293. exec(db, sql"insert into tbl1 values('hello!',10)", [])
  294. exec(db, sql"insert into tbl1 values('goodbye', 20)", [])
  295. #db.query("create table tbl1(one varchar(10), two smallint)")
  296. #db.query("insert into tbl1 values('hello!',10)")
  297. #db.query("insert into tbl1 values('goodbye', 20)")
  298. for r in db.rows(sql"select * from tbl1", []):
  299. echo(r[0], r[1])
  300. for r in db.instantRows(sql"select * from tbl1", []):
  301. echo(r[0], r[1])
  302. db_sqlite.close(db)