db_sqlite.nim 11 KB

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