db_mysql.nim 13 KB

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