db_mysql.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 `mySQL`:idx: database wrapper. The same interface is
  10. ## implemented for other databases too.
  11. ##
  12. ## See also: `db_odbc <db_odbc.html>`_, `db_sqlite <db_sqlite.html>`_,
  13. ## `db_postgres <db_postgres.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. ##
  26. ## Examples
  27. ## ========
  28. ##
  29. ## Opening a connection to a database
  30. ## ----------------------------------
  31. ##
  32. ## .. code-block:: Nim
  33. ## import db_mysql
  34. ## let db = open("localhost", "user", "password", "dbname")
  35. ## db.close()
  36. ##
  37. ## Creating a table
  38. ## ----------------
  39. ##
  40. ## .. code-block:: Nim
  41. ## db.exec(sql"DROP TABLE IF EXISTS myTable")
  42. ## db.exec(sql("""CREATE TABLE myTable (
  43. ## id integer,
  44. ## name varchar(50) not null)"""))
  45. ##
  46. ## Inserting data
  47. ## --------------
  48. ##
  49. ## .. code-block:: Nim
  50. ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
  51. ## "Dominik")
  52. ##
  53. ## Larger example
  54. ## --------------
  55. ##
  56. ## .. code-block:: Nim
  57. ##
  58. ## import db_mysql, math
  59. ##
  60. ## let theDb = open("localhost", "nim", "nim", "test")
  61. ##
  62. ## theDb.exec(sql"Drop table if exists myTestTbl")
  63. ## theDb.exec(sql("create table myTestTbl (" &
  64. ## " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
  65. ## " Name VARCHAR(50) NOT NULL, " &
  66. ## " i INT(11), " &
  67. ## " f DECIMAL(18,10))"))
  68. ##
  69. ## theDb.exec(sql"START TRANSACTION")
  70. ## for i in 1..1000:
  71. ## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  72. ## "Item#" & $i, i, sqrt(i.float))
  73. ## theDb.exec(sql"COMMIT")
  74. ##
  75. ## for x in theDb.fastRows(sql"select * from myTestTbl"):
  76. ## echo x
  77. ##
  78. ## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  79. ## "Item#1001", 1001, sqrt(1001.0))
  80. ## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
  81. ##
  82. ## theDb.close()
  83. import strutils, mysql
  84. import db_common
  85. export db_common
  86. import std/private/since
  87. type
  88. DbConn* = distinct PMySQL ## encapsulates a database connection
  89. Row* = seq[string] ## a row of a dataset. NULL database values will be
  90. ## converted to nil.
  91. InstantRow* = object ## a handle that can be used to get a row's
  92. ## column text on demand
  93. row: cstringArray
  94. len: int
  95. proc dbError*(db: DbConn) {.noreturn.} =
  96. ## raises a DbError exception.
  97. var e: ref DbError
  98. new(e)
  99. e.msg = $mysql.error(PMySQL db)
  100. raise e
  101. when false:
  102. proc dbQueryOpt*(db: DbConn, query: string, args: varargs[string, `$`]) =
  103. var stmt = mysql_stmt_init(db)
  104. if stmt == nil: dbError(db)
  105. if mysql_stmt_prepare(stmt, query, len(query)) != 0:
  106. dbError(db)
  107. var
  108. binding: seq[MYSQL_BIND]
  109. discard mysql_stmt_close(stmt)
  110. proc dbQuote*(s: string): string =
  111. ## DB quotes the string.
  112. result = newStringOfCap(s.len + 2)
  113. result.add "'"
  114. for c in items(s):
  115. # see https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html#mysql-escaping
  116. case c
  117. of '\0': result.add "\\0"
  118. of '\b': result.add "\\b"
  119. of '\t': result.add "\\t"
  120. of '\l': result.add "\\n"
  121. of '\r': result.add "\\r"
  122. of '\x1a': result.add "\\Z"
  123. of '"': result.add "\\\""
  124. of '%': result.add "\\%"
  125. of '\'': result.add "\\'"
  126. of '\\': result.add "\\\\"
  127. of '_': result.add "\\_"
  128. else: result.add c
  129. add(result, '\'')
  130. proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
  131. result = ""
  132. var a = 0
  133. for c in items(string(formatstr)):
  134. if c == '?':
  135. add(result, dbQuote(args[a]))
  136. inc(a)
  137. else:
  138. add(result, c)
  139. proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.
  140. tags: [ReadDbEffect, WriteDbEffect].} =
  141. ## tries to execute the query and returns true if successful, false otherwise.
  142. var q = dbFormat(query, args)
  143. return mysql.realQuery(PMySQL db, q, q.len) == 0'i32
  144. proc rawExec(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) =
  145. var q = dbFormat(query, args)
  146. if mysql.realQuery(PMySQL db, q, q.len) != 0'i32: dbError(db)
  147. proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  148. tags: [ReadDbEffect, WriteDbEffect].} =
  149. ## executes the query and raises EDB if not successful.
  150. var q = dbFormat(query, args)
  151. if mysql.realQuery(PMySQL db, q, q.len) != 0'i32: dbError(db)
  152. proc newRow(L: int): Row =
  153. newSeq(result, L)
  154. for i in 0..L-1: result[i] = ""
  155. proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) =
  156. if row != nil:
  157. while mysql.fetchRow(sqlres) != nil: discard
  158. mysql.freeResult(sqlres)
  159. iterator fastRows*(db: DbConn, query: SqlQuery,
  160. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  161. ## executes the query and iterates over the result dataset.
  162. ##
  163. ## This is very fast, but potentially dangerous. Use this iterator only
  164. ## if you require **ALL** the rows.
  165. ##
  166. ## Breaking the fastRows() iterator during a loop will cause the next
  167. ## database query to raise an [EDb] exception ``Commands out of sync``.
  168. rawExec(db, query, args)
  169. var sqlres = mysql.useResult(PMySQL db)
  170. if sqlres != nil:
  171. var
  172. L = int(mysql.numFields(sqlres))
  173. row: cstringArray
  174. result: Row
  175. backup: Row
  176. newSeq(result, L)
  177. while true:
  178. row = mysql.fetchRow(sqlres)
  179. if row == nil: break
  180. for i in 0..L-1:
  181. setLen(result[i], 0)
  182. result[i].add row[i]
  183. yield result
  184. properFreeResult(sqlres, row)
  185. iterator instantRows*(db: DbConn, query: SqlQuery,
  186. args: varargs[string, `$`]): InstantRow
  187. {.tags: [ReadDbEffect].} =
  188. ## Same as fastRows but returns a handle that can be used to get column text
  189. ## on demand using []. Returned handle is valid only within the iterator body.
  190. rawExec(db, query, args)
  191. var sqlres = mysql.useResult(PMySQL db)
  192. if sqlres != nil:
  193. let L = int(mysql.numFields(sqlres))
  194. var row: cstringArray
  195. while true:
  196. row = mysql.fetchRow(sqlres)
  197. if row == nil: break
  198. yield InstantRow(row: row, len: L)
  199. properFreeResult(sqlres, row)
  200. proc setTypeName(t: var DbType; f: PFIELD) =
  201. t.name = $f.name
  202. t.maxReprLen = Natural(f.max_length)
  203. if (NOT_NULL_FLAG and f.flags) != 0: t.notNull = true
  204. case f.ftype
  205. of TYPE_DECIMAL:
  206. t.kind = dbDecimal
  207. of TYPE_TINY:
  208. t.kind = dbInt
  209. t.size = 1
  210. of TYPE_SHORT:
  211. t.kind = dbInt
  212. t.size = 2
  213. of TYPE_LONG:
  214. t.kind = dbInt
  215. t.size = 4
  216. of TYPE_FLOAT:
  217. t.kind = dbFloat
  218. t.size = 4
  219. of TYPE_DOUBLE:
  220. t.kind = dbFloat
  221. t.size = 8
  222. of TYPE_NULL:
  223. t.kind = dbNull
  224. of TYPE_TIMESTAMP:
  225. t.kind = dbTimestamp
  226. of TYPE_LONGLONG:
  227. t.kind = dbInt
  228. t.size = 8
  229. of TYPE_INT24:
  230. t.kind = dbInt
  231. t.size = 3
  232. of TYPE_DATE:
  233. t.kind = dbDate
  234. of TYPE_TIME:
  235. t.kind = dbTime
  236. of TYPE_DATETIME:
  237. t.kind = dbDatetime
  238. of TYPE_YEAR:
  239. t.kind = dbDate
  240. of TYPE_NEWDATE:
  241. t.kind = dbDate
  242. of TYPE_VARCHAR, TYPE_VAR_STRING, TYPE_STRING:
  243. t.kind = dbVarchar
  244. of TYPE_BIT:
  245. t.kind = dbBit
  246. of TYPE_NEWDECIMAL:
  247. t.kind = dbDecimal
  248. of TYPE_ENUM: t.kind = dbEnum
  249. of TYPE_SET: t.kind = dbSet
  250. of TYPE_TINY_BLOB, TYPE_MEDIUM_BLOB, TYPE_LONG_BLOB,
  251. TYPE_BLOB: t.kind = dbBlob
  252. of TYPE_GEOMETRY:
  253. t.kind = dbGeometry
  254. proc setColumnInfo(columns: var DbColumns; res: PRES; L: int) =
  255. setLen(columns, L)
  256. for i in 0..<L:
  257. let fp = mysql.fetch_field_direct(res, cint(i))
  258. setTypeName(columns[i].typ, fp)
  259. columns[i].name = $fp.name
  260. columns[i].tableName = $fp.table
  261. columns[i].primaryKey = (fp.flags and PRI_KEY_FLAG) != 0
  262. #columns[i].foreignKey = there is no such thing in mysql
  263. iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery;
  264. args: varargs[string, `$`]): InstantRow =
  265. ## Same as fastRows but returns a handle that can be used to get column text
  266. ## on demand using []. Returned handle is valid only within the iterator body.
  267. rawExec(db, query, args)
  268. var sqlres = mysql.useResult(PMySQL db)
  269. if sqlres != nil:
  270. let L = int(mysql.numFields(sqlres))
  271. setColumnInfo(columns, sqlres, L)
  272. var row: cstringArray
  273. while true:
  274. row = mysql.fetchRow(sqlres)
  275. if row == nil: break
  276. yield InstantRow(row: row, len: L)
  277. properFreeResult(sqlres, row)
  278. proc `[]`*(row: InstantRow, col: int): string {.inline.} =
  279. ## Returns text for given column of the row.
  280. $row.row[col]
  281. proc unsafeColumnAt*(row: InstantRow, index: int): cstring {.inline.} =
  282. ## Return cstring of given column of the row
  283. row.row[index]
  284. proc len*(row: InstantRow): int {.inline.} =
  285. ## Returns number of columns in the row.
  286. row.len
  287. proc getRow*(db: DbConn, query: SqlQuery,
  288. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  289. ## Retrieves a single row. If the query doesn't return any rows, this proc
  290. ## will return a Row with empty strings for each column.
  291. rawExec(db, query, args)
  292. var sqlres = mysql.useResult(PMySQL db)
  293. if sqlres != nil:
  294. var L = int(mysql.numFields(sqlres))
  295. result = newRow(L)
  296. var row = mysql.fetchRow(sqlres)
  297. if row != nil:
  298. for i in 0..L-1:
  299. setLen(result[i], 0)
  300. add(result[i], row[i])
  301. properFreeResult(sqlres, row)
  302. proc getAllRows*(db: DbConn, query: SqlQuery,
  303. args: varargs[string, `$`]): seq[Row] {.tags: [ReadDbEffect].} =
  304. ## executes the query and returns the whole result dataset.
  305. result = @[]
  306. rawExec(db, query, args)
  307. var sqlres = mysql.useResult(PMySQL db)
  308. if sqlres != nil:
  309. var L = int(mysql.numFields(sqlres))
  310. var row: cstringArray
  311. var j = 0
  312. while true:
  313. row = mysql.fetchRow(sqlres)
  314. if row == nil: break
  315. setLen(result, j+1)
  316. newSeq(result[j], L)
  317. for i in 0..L-1:
  318. result[j][i] = $row[i]
  319. inc(j)
  320. mysql.freeResult(sqlres)
  321. iterator rows*(db: DbConn, query: SqlQuery,
  322. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  323. ## same as `fastRows`, but slower and safe.
  324. for r in items(getAllRows(db, query, args)): yield r
  325. proc getValue*(db: DbConn, query: SqlQuery,
  326. args: varargs[string, `$`]): string {.tags: [ReadDbEffect].} =
  327. ## executes the query and returns the first column of the first row of the
  328. ## result dataset. Returns "" if the dataset contains no rows or the database
  329. ## value is NULL.
  330. result = getRow(db, query, args)[0]
  331. proc tryInsertId*(db: DbConn, query: SqlQuery,
  332. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  333. ## executes the query (typically "INSERT") and returns the
  334. ## generated ID for the row or -1 in case of an error.
  335. var q = dbFormat(query, args)
  336. if mysql.realQuery(PMySQL db, q, q.len) != 0'i32:
  337. result = -1'i64
  338. else:
  339. result = mysql.insertId(PMySQL db)
  340. proc insertId*(db: DbConn, query: SqlQuery,
  341. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  342. ## executes the query (typically "INSERT") and returns the
  343. ## generated ID for the row.
  344. result = tryInsertID(db, query, args)
  345. if result < 0: dbError(db)
  346. proc tryInsert*(db: DbConn, query: SqlQuery, pkName: string,
  347. args: varargs[string, `$`]): int64
  348. {.tags: [WriteDbEffect], raises: [], since: (1, 3).} =
  349. ## same as tryInsertID
  350. tryInsertID(db, query, args)
  351. proc insert*(db: DbConn, query: SqlQuery, pkName: string,
  352. args: varargs[string, `$`]): int64
  353. {.tags: [WriteDbEffect], since: (1, 3).} =
  354. ## same as insertId
  355. result = tryInsert(db, query,pkName, args)
  356. if result < 0: dbError(db)
  357. proc execAffectedRows*(db: DbConn, query: SqlQuery,
  358. args: varargs[string, `$`]): int64 {.
  359. tags: [ReadDbEffect, WriteDbEffect].} =
  360. ## runs the query (typically "UPDATE") and returns the
  361. ## number of affected rows
  362. rawExec(db, query, args)
  363. result = mysql.affectedRows(PMySQL db)
  364. proc close*(db: DbConn) {.tags: [DbEffect].} =
  365. ## closes the database connection.
  366. if PMySQL(db) != nil: mysql.close(PMySQL db)
  367. proc open*(connection, user, password, database: string): DbConn {.
  368. tags: [DbEffect].} =
  369. ## opens a database connection. Raises `EDb` if the connection could not
  370. ## be established.
  371. var res = mysql.init(nil)
  372. if res == nil: dbError("could not open database connection")
  373. let
  374. colonPos = connection.find(':')
  375. host = if colonPos < 0: connection
  376. else: substr(connection, 0, colonPos-1)
  377. port: int32 = if colonPos < 0: 0'i32
  378. else: substr(connection, colonPos+1).parseInt.int32
  379. if mysql.realConnect(res, host, user, password, database,
  380. port, nil, 0) == nil:
  381. var errmsg = $mysql.error(res)
  382. mysql.close(res)
  383. dbError(errmsg)
  384. result = DbConn(res)
  385. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  386. tags: [DbEffect].} =
  387. ## sets the encoding of a database connection, returns true for
  388. ## success, false for failure.
  389. result = mysql.set_character_set(PMySQL connection, encoding) == 0