db_postgres_redone.nim 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #
  2. #
  3. # Nimrod's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## A higher level `PostgreSQL`:idx: database wrapper. This interface
  10. ## is implemented for other databases too.
  11. import strutils, postgres_redone
  12. type
  13. TDbConn* = PPGconn ## encapsulates a database connection
  14. TRow* = seq[string] ## a row of a dataset. NULL database values will be
  15. ## transformed always to the empty string.
  16. EDb* = object of EIO ## exception that is raised if a database error occurs
  17. TSqlQuery* = distinct string ## an SQL query string
  18. TPreparedId* = distinct string ## a identifier for the prepared queries
  19. FDb* = object of FIO ## effect that denotes a database operation
  20. FReadDb* = object of FDB ## effect that denotes a read operation
  21. FWriteDb* = object of FDB ## effect that denotes a write operation
  22. proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} =
  23. ## constructs a TSqlQuery from the string `query`. This is supposed to be
  24. ## used as a raw-string-literal modifier:
  25. ## ``sql"update user set counter = counter + 1"``
  26. ##
  27. ## If assertions are turned off, it does nothing. If assertions are turned
  28. ## on, later versions will check the string for valid syntax.
  29. result = TSqlQuery(query)
  30. proc dbError*(db: TDbConn) {.noreturn.} =
  31. ## raises an EDb exception.
  32. var e: ref EDb
  33. new(e)
  34. e.msg = $PQerrorMessage(db)
  35. raise e
  36. proc dbError*(msg: string) {.noreturn.} =
  37. ## raises an EDb exception with message `msg`.
  38. var e: ref EDb
  39. new(e)
  40. e.msg = msg
  41. raise e
  42. proc dbQuote(s: string): string =
  43. result = "'"
  44. for c in items(s):
  45. if c == '\'': add(result, "''")
  46. else: add(result, c)
  47. add(result, '\'')
  48. proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
  49. result = ""
  50. var a = 0
  51. for c in items(string(formatstr)):
  52. if c == '?':
  53. add(result, dbQuote(args[a]))
  54. inc(a)
  55. else:
  56. add(result, c)
  57. proc TryExec*(db: TDbConn, query: TSqlQuery,
  58. args: varargs[string, `$`]): bool {.tags: [FReadDB, FWriteDb].} =
  59. ## tries to execute the query and returns true if successful, false otherwise.
  60. var q = dbFormat(query, args)
  61. var res = PQExec(db, q)
  62. result = PQresultStatus(res) == PGRES_COMMAND_OK
  63. PQclear(res)
  64. proc ExecNo*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {.
  65. tags: [FReadDB, FWriteDb].} =
  66. ## executes the query and raises EDB if not successful.
  67. var q = dbFormat(query, args)
  68. var res = PQExec(db, q)
  69. if PQresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  70. PQclear(res)
  71. var nullPOid: POid
  72. var nowhere: ptr int32
  73. proc Exec*(db: TDbConn, stmtName: TPreparedId,
  74. args: varargs[string]) {.tags: [FReadDB, FWriteDb].} =
  75. var arr = allocCStringArray(args)
  76. var res = PQexecPrepared(db, stmtName.string, int32(args.len), arr,
  77. nowhere, nowhere, 0)
  78. deallocCStringArray(arr)
  79. if PQResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  80. PQclear(res)
  81. proc newRow(L: int): TRow =
  82. newSeq(result, L)
  83. for i in 0..L-1: result[i] = ""
  84. proc setupQueryNo(db: TDbConn, query: TSqlQuery,
  85. args: varargs[string]): PPGresult =
  86. var q = dbFormat(query, args)
  87. result = PQExec(db, q)
  88. if PQresultStatus(result) != PGRES_TUPLES_OK: dbError(db)
  89. proc setupQuery(db: TDbConn, query: string,
  90. args: varargs[string]): PPGresult =
  91. # read this for details:
  92. # http://www.postgresql.org/docs/9.3/interactive/libpq-exec.html
  93. var arr = allocCStringArray(args)
  94. result = PQexecParams(db, query, int32(args.len), nullPOid, arr, nowhere, nowhere, 0)
  95. deallocCStringArray(arr)
  96. if PQResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
  97. proc setupPQuery(db: TDbConn, stmtName: TPreparedId,
  98. args: varargs[string]): PPGresult =
  99. var arr = allocCStringArray(args)
  100. result = PQexecPrepared(db, stmtName.string, int32(args.len), arr,
  101. nowhere, nowhere, 0)
  102. deallocCStringArray(arr)
  103. if PQResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
  104. proc prepare*(db: TDbConn; stmtName, query: string; nParams: int): TPreparedId =
  105. var res = PQprepare(db, stmtName, query, int32(nParams), nullPOid)
  106. if PQResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  107. return TPreparedId(stmtName)
  108. proc setRow(res: PPGresult, r: var TRow, line, cols: int32) =
  109. for col in 0..cols-1:
  110. setLen(r[col], 0)
  111. var x = PQgetvalue(res, line, col)
  112. add(r[col], x)
  113. iterator FastPRows*(db: TDbConn, stmtName: TPreparedId,
  114. args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
  115. ## executes the query and iterates over the result dataset. This is very
  116. ## fast, but potenially dangerous: If the for-loop-body executes another
  117. ## query, the results can be undefined. For Postgres it is safe though.
  118. var res = setupPQuery(db, stmtName, args)
  119. var L = PQnfields(res)
  120. var result = newRow(L)
  121. for i in 0..PQntuples(res)-1:
  122. setRow(res, result, i, L)
  123. yield result
  124. PQclear(res)
  125. iterator FastRows*(db: TDbConn, query: string,
  126. args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
  127. ## executes the query and iterates over the result dataset. This is very
  128. ## fast, but potenially dangerous: If the for-loop-body executes another
  129. ## query, the results can be undefined. For Postgres it is safe though.
  130. var res = setupQuery(db, query, args)
  131. var L = PQnfields(res)
  132. var result = newRow(L)
  133. for i in 0..PQntuples(res)-1:
  134. setRow(res, result, i, L)
  135. yield result
  136. PQclear(res)
  137. proc getPRow*(db: TDbConn, stmtName: TPreparedId,
  138. args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
  139. var res = setupPQuery(db, stmtName, args)
  140. var L = PQnfields(res)
  141. result = newRow(L)
  142. setRow(res, result, 0, L)
  143. PQclear(res)
  144. proc getRow*(db: TDbConn, query: string,
  145. args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
  146. ## retrieves a single row. If the query doesn't return any rows, this proc
  147. ## will return a TRow with empty strings for each column.
  148. var res = setupQuery(db, query, args)
  149. var L = PQnfields(res)
  150. result = newRow(L)
  151. setRow(res, result, 0, L)
  152. PQclear(res)
  153. proc GetAllPRows*(db: TDbConn, stmtName: TPreparedId,
  154. args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} =
  155. ## executes the query and returns the whole result dataset.
  156. result = @[]
  157. for r in FastPRows(db, stmtName, args):
  158. result.add(r)
  159. proc GetAllRows*(db: TDbConn, query: string,
  160. args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} =
  161. ## executes the query and returns the whole result dataset.
  162. result = @[]
  163. for r in FastRows(db, query, args):
  164. result.add(r)
  165. iterator Rows*(db: TDbConn, query: string,
  166. args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
  167. ## same as `FastRows`, but slower and safe.
  168. for r in items(GetAllRows(db, query, args)): yield r
  169. proc GetValue*(db: TDbConn, query: string,
  170. args: varargs[string, `$`]): string {.tags: [FReadDB].} =
  171. ## executes the query and returns the first column of the first row of the
  172. ## result dataset. Returns "" if the dataset contains no rows or the database
  173. ## value is NULL.
  174. var x = PQgetvalue(setupQuery(db, query, args), 0, 0)
  175. result = if isNil(x): "" else: $x
  176. proc TryInsertID*(db: TDbConn, query: string,
  177. args: varargs[string, `$`]): int64 {.tags: [FWriteDb].}=
  178. ## executes the query (typically "INSERT") and returns the
  179. ## generated ID for the row or -1 in case of an error. For Postgre this adds
  180. ## ``RETURNING id`` to the query, so it only works if your primary key is
  181. ## named ``id``.
  182. var x = PQgetvalue(setupQuery(db, query & " RETURNING id",
  183. args), 0, 0)
  184. if not isNil(x):
  185. result = ParseBiggestInt($x)
  186. else:
  187. result = -1
  188. proc InsertID*(db: TDbConn, query: string,
  189. args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
  190. ## executes the query (typically "INSERT") and returns the
  191. ## generated ID for the row. For Postgre this adds
  192. ## ``RETURNING id`` to the query, so it only works if your primary key is
  193. ## named ``id``.
  194. result = TryInsertID(db, query, args)
  195. if result < 0: dbError(db)
  196. proc ExecAffectedRows*(db: TDbConn, query: TSqlQuery,
  197. args: varargs[string, `$`]): int64 {.tags: [
  198. FReadDB, FWriteDb].} =
  199. ## executes the query (typically "UPDATE") and returns the
  200. ## number of affected rows.
  201. var q = dbFormat(query, args)
  202. var res = PQExec(db, q)
  203. if PQresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  204. result = parseBiggestInt($PQcmdTuples(res))
  205. PQclear(res)
  206. proc Close*(db: TDbConn) {.tags: [FDb].} =
  207. ## closes the database connection.
  208. if db != nil: PQfinish(db)
  209. proc Open*(connection, user, password, database: string): TDbConn {.
  210. tags: [FDb].} =
  211. ## opens a database connection. Raises `EDb` if the connection could not
  212. ## be established.
  213. ##
  214. ## Clients can also use Postgres keyword/value connection strings to
  215. ## connect.
  216. ##
  217. ## Example:
  218. ##
  219. ## .. code-block:: nimrod
  220. ##
  221. ## con = Open("", "", "", "host=localhost port=5432 dbname=mydb")
  222. ##
  223. ## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  224. ## for more information.
  225. ##
  226. ## Note that the connection parameter is not used but exists to maintain
  227. ## the nimrod db api.
  228. result = PQsetdbLogin(nil, nil, nil, nil, database, user, password)
  229. if PQStatus(result) != CONNECTION_OK: dbError(result) # result = nil