db_mysql.nim 12 KB

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