db_mysql.nim 13 KB

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