db_mysql.nim 12 KB

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