db_mysql.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 std/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 std/[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. else: result.add c
  128. add(result, '\'')
  129. proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
  130. result = ""
  131. var a = 0
  132. for c in items(string(formatstr)):
  133. if c == '?':
  134. add(result, dbQuote(args[a]))
  135. inc(a)
  136. else:
  137. add(result, c)
  138. proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.
  139. tags: [ReadDbEffect, WriteDbEffect].} =
  140. ## tries to execute the query and returns true if successful, false otherwise.
  141. var q = dbFormat(query, args)
  142. return mysql.realQuery(PMySQL db, q, q.len) == 0'i32
  143. proc rawExec(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) =
  144. var q = dbFormat(query, args)
  145. if mysql.realQuery(PMySQL db, q, q.len) != 0'i32: dbError(db)
  146. proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  147. tags: [ReadDbEffect, WriteDbEffect].} =
  148. ## executes the query and raises EDB if not successful.
  149. var q = dbFormat(query, args)
  150. if mysql.realQuery(PMySQL db, q, q.len) != 0'i32: dbError(db)
  151. proc newRow(L: int): Row =
  152. newSeq(result, L)
  153. for i in 0..L-1: result[i] = ""
  154. proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) =
  155. if row != nil:
  156. while mysql.fetchRow(sqlres) != nil: discard
  157. mysql.freeResult(sqlres)
  158. iterator fastRows*(db: DbConn, query: SqlQuery,
  159. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  160. ## executes the query and iterates over the result dataset.
  161. ##
  162. ## This is very fast, but potentially dangerous. Use this iterator only
  163. ## if you require **ALL** the rows.
  164. ##
  165. ## Breaking the fastRows() iterator during a loop will cause the next
  166. ## database query to raise an [EDb] exception `Commands out of sync`.
  167. rawExec(db, query, args)
  168. var sqlres = mysql.useResult(PMySQL db)
  169. if sqlres != nil:
  170. var
  171. L = int(mysql.numFields(sqlres))
  172. row: cstringArray
  173. result: Row
  174. backup: Row
  175. newSeq(result, L)
  176. while true:
  177. row = mysql.fetchRow(sqlres)
  178. if row == nil: break
  179. for i in 0..L-1:
  180. setLen(result[i], 0)
  181. result[i].add row[i]
  182. yield result
  183. properFreeResult(sqlres, row)
  184. iterator instantRows*(db: DbConn, query: SqlQuery,
  185. args: varargs[string, `$`]): InstantRow
  186. {.tags: [ReadDbEffect].} =
  187. ## Same as fastRows but returns a handle that can be used to get column text
  188. ## on demand using []. Returned handle is valid only within the iterator body.
  189. rawExec(db, query, args)
  190. var sqlres = mysql.useResult(PMySQL db)
  191. if sqlres != nil:
  192. let L = int(mysql.numFields(sqlres))
  193. var row: cstringArray
  194. while true:
  195. row = mysql.fetchRow(sqlres)
  196. if row == nil: break
  197. yield InstantRow(row: row, len: L)
  198. properFreeResult(sqlres, row)
  199. proc setTypeName(t: var DbType; f: PFIELD) =
  200. t.name = $f.name
  201. t.maxReprLen = Natural(f.max_length)
  202. if (NOT_NULL_FLAG and f.flags) != 0: t.notNull = true
  203. case f.ftype
  204. of TYPE_DECIMAL:
  205. t.kind = dbDecimal
  206. of TYPE_TINY:
  207. t.kind = dbInt
  208. t.size = 1
  209. of TYPE_SHORT:
  210. t.kind = dbInt
  211. t.size = 2
  212. of TYPE_LONG:
  213. t.kind = dbInt
  214. t.size = 4
  215. of TYPE_FLOAT:
  216. t.kind = dbFloat
  217. t.size = 4
  218. of TYPE_DOUBLE:
  219. t.kind = dbFloat
  220. t.size = 8
  221. of TYPE_NULL:
  222. t.kind = dbNull
  223. of TYPE_TIMESTAMP:
  224. t.kind = dbTimestamp
  225. of TYPE_LONGLONG:
  226. t.kind = dbInt
  227. t.size = 8
  228. of TYPE_INT24:
  229. t.kind = dbInt
  230. t.size = 3
  231. of TYPE_DATE:
  232. t.kind = dbDate
  233. of TYPE_TIME:
  234. t.kind = dbTime
  235. of TYPE_DATETIME:
  236. t.kind = dbDatetime
  237. of TYPE_YEAR:
  238. t.kind = dbDate
  239. of TYPE_NEWDATE:
  240. t.kind = dbDate
  241. of TYPE_VARCHAR, TYPE_VAR_STRING, TYPE_STRING:
  242. t.kind = dbVarchar
  243. of TYPE_BIT:
  244. t.kind = dbBit
  245. of TYPE_NEWDECIMAL:
  246. t.kind = dbDecimal
  247. of TYPE_ENUM: t.kind = dbEnum
  248. of TYPE_SET: t.kind = dbSet
  249. of TYPE_TINY_BLOB, TYPE_MEDIUM_BLOB, TYPE_LONG_BLOB,
  250. TYPE_BLOB: t.kind = dbBlob
  251. of TYPE_GEOMETRY:
  252. t.kind = dbGeometry
  253. proc setColumnInfo(columns: var DbColumns; res: PRES; L: int) =
  254. setLen(columns, L)
  255. for i in 0..<L:
  256. let fp = mysql.fetch_field_direct(res, cint(i))
  257. setTypeName(columns[i].typ, fp)
  258. columns[i].name = $fp.name
  259. columns[i].tableName = $fp.table
  260. columns[i].primaryKey = (fp.flags and PRI_KEY_FLAG) != 0
  261. #columns[i].foreignKey = there is no such thing in mysql
  262. iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery;
  263. args: varargs[string, `$`]): InstantRow =
  264. ## Same as fastRows but returns a handle that can be used to get column text
  265. ## on demand using []. Returned handle is valid only within the iterator body.
  266. rawExec(db, query, args)
  267. var sqlres = mysql.useResult(PMySQL db)
  268. if sqlres != nil:
  269. let L = int(mysql.numFields(sqlres))
  270. setColumnInfo(columns, sqlres, L)
  271. var row: cstringArray
  272. while true:
  273. row = mysql.fetchRow(sqlres)
  274. if row == nil: break
  275. yield InstantRow(row: row, len: L)
  276. properFreeResult(sqlres, row)
  277. proc `[]`*(row: InstantRow, col: int): string {.inline.} =
  278. ## Returns text for given column of the row.
  279. $row.row[col]
  280. proc unsafeColumnAt*(row: InstantRow, index: int): cstring {.inline.} =
  281. ## Return cstring of given column of the row
  282. row.row[index]
  283. proc len*(row: InstantRow): int {.inline.} =
  284. ## Returns number of columns in the row.
  285. row.len
  286. proc getRow*(db: DbConn, query: SqlQuery,
  287. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  288. ## Retrieves a single row. If the query doesn't return any rows, this proc
  289. ## will return a Row with empty strings for each column.
  290. rawExec(db, query, args)
  291. var sqlres = mysql.useResult(PMySQL db)
  292. if sqlres != nil:
  293. var L = int(mysql.numFields(sqlres))
  294. result = newRow(L)
  295. var row = mysql.fetchRow(sqlres)
  296. if row != nil:
  297. for i in 0..L-1:
  298. setLen(result[i], 0)
  299. add(result[i], row[i])
  300. properFreeResult(sqlres, row)
  301. proc getAllRows*(db: DbConn, query: SqlQuery,
  302. args: varargs[string, `$`]): seq[Row] {.tags: [ReadDbEffect].} =
  303. ## executes the query and returns the whole result dataset.
  304. result = @[]
  305. rawExec(db, query, args)
  306. var sqlres = mysql.useResult(PMySQL db)
  307. if sqlres != nil:
  308. var L = int(mysql.numFields(sqlres))
  309. var row: cstringArray
  310. var j = 0
  311. while true:
  312. row = mysql.fetchRow(sqlres)
  313. if row == nil: break
  314. setLen(result, j+1)
  315. newSeq(result[j], L)
  316. for i in 0..L-1:
  317. result[j][i] = $row[i]
  318. inc(j)
  319. mysql.freeResult(sqlres)
  320. iterator rows*(db: DbConn, query: SqlQuery,
  321. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  322. ## same as `fastRows`, but slower and safe.
  323. for r in items(getAllRows(db, query, args)): yield r
  324. proc getValue*(db: DbConn, query: SqlQuery,
  325. args: varargs[string, `$`]): string {.tags: [ReadDbEffect].} =
  326. ## executes the query and returns the first column of the first row of the
  327. ## result dataset. Returns "" if the dataset contains no rows or the database
  328. ## value is NULL.
  329. result = getRow(db, query, args)[0]
  330. proc tryInsertId*(db: DbConn, query: SqlQuery,
  331. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  332. ## executes the query (typically "INSERT") and returns the
  333. ## generated ID for the row or -1 in case of an error.
  334. var q = dbFormat(query, args)
  335. if mysql.realQuery(PMySQL db, q, q.len) != 0'i32:
  336. result = -1'i64
  337. else:
  338. result = mysql.insertId(PMySQL db)
  339. proc insertId*(db: DbConn, query: SqlQuery,
  340. args: varargs[string, `$`]): int64 {.tags: [WriteDbEffect].} =
  341. ## executes the query (typically "INSERT") and returns the
  342. ## generated ID for the row.
  343. result = tryInsertID(db, query, args)
  344. if result < 0: dbError(db)
  345. proc tryInsert*(db: DbConn, query: SqlQuery, pkName: string,
  346. args: varargs[string, `$`]): int64
  347. {.tags: [WriteDbEffect], raises: [], since: (1, 3).} =
  348. ## same as tryInsertID
  349. tryInsertID(db, query, args)
  350. proc insert*(db: DbConn, query: SqlQuery, pkName: string,
  351. args: varargs[string, `$`]): int64
  352. {.tags: [WriteDbEffect], since: (1, 3).} =
  353. ## same as insertId
  354. result = tryInsert(db, query,pkName, args)
  355. if result < 0: dbError(db)
  356. proc execAffectedRows*(db: DbConn, query: SqlQuery,
  357. args: varargs[string, `$`]): int64 {.
  358. tags: [ReadDbEffect, WriteDbEffect].} =
  359. ## runs the query (typically "UPDATE") and returns the
  360. ## number of affected rows
  361. rawExec(db, query, args)
  362. result = mysql.affectedRows(PMySQL db)
  363. proc close*(db: DbConn) {.tags: [DbEffect].} =
  364. ## closes the database connection.
  365. if PMySQL(db) != nil: mysql.close(PMySQL db)
  366. proc open*(connection, user, password, database: string): DbConn {.
  367. tags: [DbEffect].} =
  368. ## opens a database connection. Raises `EDb` if the connection could not
  369. ## be established.
  370. var res = mysql.init(nil)
  371. if res == nil: dbError("could not open database connection")
  372. let
  373. colonPos = connection.find(':')
  374. host = if colonPos < 0: connection
  375. else: substr(connection, 0, colonPos-1)
  376. port: int32 = if colonPos < 0: 0'i32
  377. else: substr(connection, colonPos+1).parseInt.int32
  378. if mysql.realConnect(res, host, user, password, database,
  379. port, nil, 0) == nil:
  380. var errmsg = $mysql.error(res)
  381. mysql.close(res)
  382. dbError(errmsg)
  383. result = DbConn(res)
  384. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  385. tags: [DbEffect].} =
  386. ## sets the encoding of a database connection, returns true for
  387. ## success, false for failure.
  388. result = mysql.set_character_set(PMySQL connection, encoding) == 0