db_postgres.nim 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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 `PostgreSQL`:idx: database wrapper. This interface
  10. ## is implemented for other databases also.
  11. ##
  12. ## See also: `db_odbc <db_odbc.html>`_, `db_sqlite <db_sqlite.html>`_,
  13. ## `db_mysql <db_mysql.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. ## **Note**: There are two approaches to parameter substitution support by
  26. ## this module.
  27. ##
  28. ## 1. `SqlQuery` using `?, ?, ?, ...` (same as all the `db_*` modules)
  29. ##
  30. ## 2. `SqlPrepared` using `$1, $2, $3, ...`
  31. ##
  32. ## .. code-block:: Nim
  33. ## prepare(db, "myExampleInsert",
  34. ## sql"""INSERT INTO myTable
  35. ## (colA, colB, colC)
  36. ## VALUES ($1, $2, $3)""",
  37. ## 3)
  38. ##
  39. ##
  40. ## Unix Socket
  41. ## ===========
  42. ##
  43. ## Using Unix sockets instead of TCP connection can
  44. ## `improve performance up to 30% ~ 175% for some operations <https://momjian.us/main/blogs/pgblog/2012.html#June_6_2012>`_.
  45. ##
  46. ## To use Unix sockets with `db_postgres`, change the server address to the socket file path:
  47. ##
  48. ## .. code-block:: Nim
  49. ## import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path
  50. ## let db = db_postgres.open("/run/postgresql", "user", "password", "database")
  51. ## echo db.getAllRows(sql"SELECT version();")
  52. ## db.close()
  53. ##
  54. ## The socket file path is operating system specific and distribution specific,
  55. ## additional configuration may or may not be needed on your `postgresql.conf`.
  56. ## The Postgres server must be on the same computer and only works for Unix-like operating systems.
  57. ##
  58. ##
  59. ## Examples
  60. ## ========
  61. ##
  62. ## Opening a connection to a database
  63. ## ----------------------------------
  64. ##
  65. ## .. code-block:: Nim
  66. ## import std/db_postgres
  67. ## let db = open("localhost", "user", "password", "dbname")
  68. ## db.close()
  69. ##
  70. ## Creating a table
  71. ## ----------------
  72. ##
  73. ## .. code-block:: Nim
  74. ## db.exec(sql"DROP TABLE IF EXISTS myTable")
  75. ## db.exec(sql("""CREATE TABLE myTable (
  76. ## id integer,
  77. ## name varchar(50) not null)"""))
  78. ##
  79. ## Inserting data
  80. ## --------------
  81. ##
  82. ## .. code-block:: Nim
  83. ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
  84. ## "Dominik")
  85. import strutils, postgres
  86. import db_common
  87. export db_common
  88. import std/private/since
  89. type
  90. DbConn* = PPGconn ## 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
  94. res: PPGresult ## used to get a row's
  95. SqlPrepared* = distinct string ## a identifier for the prepared queries
  96. proc dbError*(db: DbConn) {.noreturn.} =
  97. ## raises a DbError exception.
  98. var e: ref DbError
  99. new(e)
  100. e.msg = $pqErrorMessage(db)
  101. raise e
  102. proc dbQuote*(s: string): string =
  103. ## DB quotes the string.
  104. result = "'"
  105. for c in items(s):
  106. case c
  107. of '\'': add(result, "''")
  108. of '\0': add(result, "\\0")
  109. else: add(result, c)
  110. add(result, '\'')
  111. proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
  112. result = ""
  113. var a = 0
  114. if args.len > 0 and not string(formatstr).contains("?"):
  115. dbError("""parameter substitution expects "?" """)
  116. if args.len == 0:
  117. return string(formatstr)
  118. else:
  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,
  126. args: varargs[string, `$`]): bool {.tags: [ReadDbEffect, WriteDbEffect].} =
  127. ## tries to execute the query and returns true if successful, false otherwise.
  128. var res = pqexecParams(db, dbFormat(query, args), 0, nil, nil,
  129. nil, nil, 0)
  130. result = pqresultStatus(res) == PGRES_COMMAND_OK
  131. pqclear(res)
  132. proc tryExec*(db: DbConn, stmtName: SqlPrepared,
  133. args: varargs[string, `$`]): bool {.tags: [
  134. ReadDbEffect, WriteDbEffect].} =
  135. ## tries to execute the query and returns true if successful, false otherwise.
  136. var arr = allocCStringArray(args)
  137. var res = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
  138. nil, nil, 0)
  139. deallocCStringArray(arr)
  140. result = pqresultStatus(res) == PGRES_COMMAND_OK
  141. pqclear(res)
  142. proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  143. tags: [ReadDbEffect, WriteDbEffect].} =
  144. ## executes the query and raises EDB if not successful.
  145. var res = pqexecParams(db, dbFormat(query, args), 0, nil, nil,
  146. nil, nil, 0)
  147. if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  148. pqclear(res)
  149. proc exec*(db: DbConn, stmtName: SqlPrepared,
  150. args: varargs[string]) {.tags: [ReadDbEffect, WriteDbEffect].} =
  151. var arr = allocCStringArray(args)
  152. var res = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
  153. nil, nil, 0)
  154. deallocCStringArray(arr)
  155. if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  156. pqclear(res)
  157. proc newRow(L: int): Row =
  158. newSeq(result, L)
  159. for i in 0..L-1: result[i] = ""
  160. proc setupQuery(db: DbConn, query: SqlQuery,
  161. args: varargs[string]): PPGresult =
  162. result = pqexec(db, dbFormat(query, args))
  163. if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
  164. proc setupQuery(db: DbConn, stmtName: SqlPrepared,
  165. args: varargs[string]): PPGresult =
  166. var arr = allocCStringArray(args)
  167. result = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
  168. nil, nil, 0)
  169. deallocCStringArray(arr)
  170. if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
  171. proc setupSingeRowQuery(db: DbConn, query: SqlQuery,
  172. args: varargs[string]) =
  173. if pqsendquery(db, dbFormat(query, args)) != 1:
  174. dbError(db)
  175. if pqSetSingleRowMode(db) != 1:
  176. dbError(db)
  177. proc setupSingeRowQuery(db: DbConn, stmtName: SqlPrepared,
  178. args: varargs[string]) =
  179. var arr = allocCStringArray(args)
  180. if pqsendqueryprepared(db, stmtName.string, int32(args.len), arr, nil, nil, 0) != 1:
  181. dbError(db)
  182. if pqSetSingleRowMode(db) != 1:
  183. dbError(db)
  184. deallocCStringArray(arr)
  185. proc prepare*(db: DbConn; stmtName: string, query: SqlQuery;
  186. nParams: int): SqlPrepared =
  187. ## Creates a new `SqlPrepared` statement. Parameter substitution is done
  188. ## via `$1`, `$2`, `$3`, etc.
  189. if nParams > 0 and not string(query).contains("$1"):
  190. dbError("parameter substitution expects \"$1\"")
  191. var res = pqprepare(db, stmtName, query.string, int32(nParams), nil)
  192. if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  193. result = SqlPrepared(stmtName)
  194. pqclear(res)
  195. proc setRow(res: PPGresult, r: var Row, line, cols: int32) =
  196. for col in 0'i32..cols-1:
  197. setLen(r[col], 0)
  198. let x = pqgetvalue(res, line, col)
  199. if x.isNil:
  200. r[col] = ""
  201. else:
  202. add(r[col], x)
  203. template fetchRows(db: DbConn): untyped =
  204. var res: PPGresult = nil
  205. while true:
  206. res = pqgetresult(db)
  207. if res == nil:
  208. break
  209. let status = pqresultStatus(res)
  210. if status == PGRES_TUPLES_OK:
  211. discard
  212. elif status != PGRES_SINGLE_TUPLE:
  213. dbError(db)
  214. else:
  215. let L = pqNfields(res)
  216. var result = newRow(L)
  217. setRow(res, result, 0, L)
  218. yield result
  219. pqclear(res)
  220. iterator fastRows*(db: DbConn, query: SqlQuery,
  221. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  222. ## executes the query and iterates over the result dataset. This is very
  223. ## fast, but potentially dangerous: If the for-loop-body executes another
  224. ## query, the results can be undefined. For Postgres it is safe though.
  225. setupSingeRowQuery(db, query, args)
  226. fetchRows(db)
  227. iterator fastRows*(db: DbConn, stmtName: SqlPrepared,
  228. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  229. ## executes the query and iterates over the result dataset. This is very
  230. ## fast, but potentially dangerous: If the for-loop-body executes another
  231. ## query, the results can be undefined. For Postgres it is safe though.
  232. setupSingeRowQuery(db, stmtName, args)
  233. fetchRows(db)
  234. template fetchinstantRows(db: DbConn): untyped =
  235. var res: PPGresult = nil
  236. while true:
  237. res = pqgetresult(db)
  238. if res == nil:
  239. break
  240. let status = pqresultStatus(res)
  241. if status == PGRES_TUPLES_OK:
  242. discard
  243. elif status != PGRES_SINGLE_TUPLE:
  244. dbError(db)
  245. else:
  246. yield InstantRow(res: res)
  247. pqclear(res)
  248. iterator instantRows*(db: DbConn, query: SqlQuery,
  249. args: varargs[string, `$`]): InstantRow
  250. {.tags: [ReadDbEffect].} =
  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 iterator body.
  253. setupSingeRowQuery(db, query, args)
  254. fetchinstantRows(db)
  255. iterator instantRows*(db: DbConn, stmtName: SqlPrepared,
  256. args: varargs[string, `$`]): InstantRow
  257. {.tags: [ReadDbEffect].} =
  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 iterator body.
  260. setupSingeRowQuery(db, stmtName, args)
  261. fetchinstantRows(db)
  262. proc getColumnType(res: PPGresult, col: int) : DbType =
  263. ## returns DbType for given column in the row
  264. ## defined in pg_type.h file in the postgres source code
  265. ## Wire representation for types: http://www.npgsql.org/dev/types.html
  266. var oid = pqftype(res, int32(col))
  267. ## The integer returned is the internal OID number of the type
  268. case oid
  269. of 16: return DbType(kind: DbTypeKind.dbBool, name: "bool")
  270. of 17: return DbType(kind: DbTypeKind.dbBlob, name: "bytea")
  271. of 21: return DbType(kind: DbTypeKind.dbInt, name: "int2", size: 2)
  272. of 23: return DbType(kind: DbTypeKind.dbInt, name: "int4", size: 4)
  273. of 20: return DbType(kind: DbTypeKind.dbInt, name: "int8", size: 8)
  274. of 1560: return DbType(kind: DbTypeKind.dbBit, name: "bit")
  275. of 1562: return DbType(kind: DbTypeKind.dbInt, name: "varbit")
  276. of 18: return DbType(kind: DbTypeKind.dbFixedChar, name: "char")
  277. of 19: return DbType(kind: DbTypeKind.dbFixedChar, name: "name")
  278. of 1042: return DbType(kind: DbTypeKind.dbFixedChar, name: "bpchar")
  279. of 25: return DbType(kind: DbTypeKind.dbVarchar, name: "text")
  280. of 1043: return DbType(kind: DbTypeKind.dbVarChar, name: "varchar")
  281. of 2275: return DbType(kind: DbTypeKind.dbVarchar, name: "cstring")
  282. of 700: return DbType(kind: DbTypeKind.dbFloat, name: "float4")
  283. of 701: return DbType(kind: DbTypeKind.dbFloat, name: "float8")
  284. of 790: return DbType(kind: DbTypeKind.dbDecimal, name: "money")
  285. of 1700: return DbType(kind: DbTypeKind.dbDecimal, name: "numeric")
  286. of 704: return DbType(kind: DbTypeKind.dbTimeInterval, name: "tinterval")
  287. of 702: return DbType(kind: DbTypeKind.dbTimestamp, name: "abstime")
  288. of 703: return DbType(kind: DbTypeKind.dbTimeInterval, name: "reltime")
  289. of 1082: return DbType(kind: DbTypeKind.dbDate, name: "date")
  290. of 1083: return DbType(kind: DbTypeKind.dbTime, name: "time")
  291. of 1114: return DbType(kind: DbTypeKind.dbTimestamp, name: "timestamp")
  292. of 1184: return DbType(kind: DbTypeKind.dbTimestamp, name: "timestamptz")
  293. of 1186: return DbType(kind: DbTypeKind.dbTimeInterval, name: "interval")
  294. of 1266: return DbType(kind: DbTypeKind.dbTime, name: "timetz")
  295. of 114: return DbType(kind: DbTypeKind.dbJson, name: "json")
  296. of 142: return DbType(kind: DbTypeKind.dbXml, name: "xml")
  297. of 3802: return DbType(kind: DbTypeKind.dbJson, name: "jsonb")
  298. of 600: return DbType(kind: DbTypeKind.dbPoint, name: "point")
  299. of 601: return DbType(kind: DbTypeKind.dbLseg, name: "lseg")
  300. of 602: return DbType(kind: DbTypeKind.dbPath, name: "path")
  301. of 603: return DbType(kind: DbTypeKind.dbBox, name: "box")
  302. of 604: return DbType(kind: DbTypeKind.dbPolygon, name: "polygon")
  303. of 628: return DbType(kind: DbTypeKind.dbLine, name: "line")
  304. of 718: return DbType(kind: DbTypeKind.dbCircle, name: "circle")
  305. of 650: return DbType(kind: DbTypeKind.dbInet, name: "cidr")
  306. of 829: return DbType(kind: DbTypeKind.dbMacAddress, name: "macaddr")
  307. of 869: return DbType(kind: DbTypeKind.dbInet, name: "inet")
  308. of 2950: return DbType(kind: DbTypeKind.dbVarchar, name: "uuid")
  309. of 3614: return DbType(kind: DbTypeKind.dbVarchar, name: "tsvector")
  310. of 3615: return DbType(kind: DbTypeKind.dbVarchar, name: "tsquery")
  311. of 2970: return DbType(kind: DbTypeKind.dbVarchar, name: "txid_snapshot")
  312. of 27: return DbType(kind: DbTypeKind.dbComposite, name: "tid")
  313. of 1790: return DbType(kind: DbTypeKind.dbComposite, name: "refcursor")
  314. of 2249: return DbType(kind: DbTypeKind.dbComposite, name: "record")
  315. of 3904: return DbType(kind: DbTypeKind.dbComposite, name: "int4range")
  316. of 3906: return DbType(kind: DbTypeKind.dbComposite, name: "numrange")
  317. of 3908: return DbType(kind: DbTypeKind.dbComposite, name: "tsrange")
  318. of 3910: return DbType(kind: DbTypeKind.dbComposite, name: "tstzrange")
  319. of 3912: return DbType(kind: DbTypeKind.dbComposite, name: "daterange")
  320. of 3926: return DbType(kind: DbTypeKind.dbComposite, name: "int8range")
  321. of 22: return DbType(kind: DbTypeKind.dbArray, name: "int2vector")
  322. of 30: return DbType(kind: DbTypeKind.dbArray, name: "oidvector")
  323. of 143: return DbType(kind: DbTypeKind.dbArray, name: "xml[]")
  324. of 199: return DbType(kind: DbTypeKind.dbArray, name: "json[]")
  325. of 629: return DbType(kind: DbTypeKind.dbArray, name: "line[]")
  326. of 651: return DbType(kind: DbTypeKind.dbArray, name: "cidr[]")
  327. of 719: return DbType(kind: DbTypeKind.dbArray, name: "circle[]")
  328. of 791: return DbType(kind: DbTypeKind.dbArray, name: "money[]")
  329. of 1000: return DbType(kind: DbTypeKind.dbArray, name: "bool[]")
  330. of 1001: return DbType(kind: DbTypeKind.dbArray, name: "bytea[]")
  331. of 1002: return DbType(kind: DbTypeKind.dbArray, name: "char[]")
  332. of 1003: return DbType(kind: DbTypeKind.dbArray, name: "name[]")
  333. of 1005: return DbType(kind: DbTypeKind.dbArray, name: "int2[]")
  334. of 1006: return DbType(kind: DbTypeKind.dbArray, name: "int2vector[]")
  335. of 1007: return DbType(kind: DbTypeKind.dbArray, name: "int4[]")
  336. of 1008: return DbType(kind: DbTypeKind.dbArray, name: "regproc[]")
  337. of 1009: return DbType(kind: DbTypeKind.dbArray, name: "text[]")
  338. of 1028: return DbType(kind: DbTypeKind.dbArray, name: "oid[]")
  339. of 1010: return DbType(kind: DbTypeKind.dbArray, name: "tid[]")
  340. of 1011: return DbType(kind: DbTypeKind.dbArray, name: "xid[]")
  341. of 1012: return DbType(kind: DbTypeKind.dbArray, name: "cid[]")
  342. of 1013: return DbType(kind: DbTypeKind.dbArray, name: "oidvector[]")
  343. of 1014: return DbType(kind: DbTypeKind.dbArray, name: "bpchar[]")
  344. of 1015: return DbType(kind: DbTypeKind.dbArray, name: "varchar[]")
  345. of 1016: return DbType(kind: DbTypeKind.dbArray, name: "int8[]")
  346. of 1017: return DbType(kind: DbTypeKind.dbArray, name: "point[]")
  347. of 1018: return DbType(kind: DbTypeKind.dbArray, name: "lseg[]")
  348. of 1019: return DbType(kind: DbTypeKind.dbArray, name: "path[]")
  349. of 1020: return DbType(kind: DbTypeKind.dbArray, name: "box[]")
  350. of 1021: return DbType(kind: DbTypeKind.dbArray, name: "float4[]")
  351. of 1022: return DbType(kind: DbTypeKind.dbArray, name: "float8[]")
  352. of 1023: return DbType(kind: DbTypeKind.dbArray, name: "abstime[]")
  353. of 1024: return DbType(kind: DbTypeKind.dbArray, name: "reltime[]")
  354. of 1025: return DbType(kind: DbTypeKind.dbArray, name: "tinterval[]")
  355. of 1027: return DbType(kind: DbTypeKind.dbArray, name: "polygon[]")
  356. of 1040: return DbType(kind: DbTypeKind.dbArray, name: "macaddr[]")
  357. of 1041: return DbType(kind: DbTypeKind.dbArray, name: "inet[]")
  358. of 1263: return DbType(kind: DbTypeKind.dbArray, name: "cstring[]")
  359. of 1115: return DbType(kind: DbTypeKind.dbArray, name: "timestamp[]")
  360. of 1182: return DbType(kind: DbTypeKind.dbArray, name: "date[]")
  361. of 1183: return DbType(kind: DbTypeKind.dbArray, name: "time[]")
  362. of 1185: return DbType(kind: DbTypeKind.dbArray, name: "timestamptz[]")
  363. of 1187: return DbType(kind: DbTypeKind.dbArray, name: "interval[]")
  364. of 1231: return DbType(kind: DbTypeKind.dbArray, name: "numeric[]")
  365. of 1270: return DbType(kind: DbTypeKind.dbArray, name: "timetz[]")
  366. of 1561: return DbType(kind: DbTypeKind.dbArray, name: "bit[]")
  367. of 1563: return DbType(kind: DbTypeKind.dbArray, name: "varbit[]")
  368. of 2201: return DbType(kind: DbTypeKind.dbArray, name: "refcursor[]")
  369. of 2951: return DbType(kind: DbTypeKind.dbArray, name: "uuid[]")
  370. of 3643: return DbType(kind: DbTypeKind.dbArray, name: "tsvector[]")
  371. of 3645: return DbType(kind: DbTypeKind.dbArray, name: "tsquery[]")
  372. of 3807: return DbType(kind: DbTypeKind.dbArray, name: "jsonb[]")
  373. of 2949: return DbType(kind: DbTypeKind.dbArray, name: "txid_snapshot[]")
  374. of 3905: return DbType(kind: DbTypeKind.dbArray, name: "int4range[]")
  375. of 3907: return DbType(kind: DbTypeKind.dbArray, name: "numrange[]")
  376. of 3909: return DbType(kind: DbTypeKind.dbArray, name: "tsrange[]")
  377. of 3911: return DbType(kind: DbTypeKind.dbArray, name: "tstzrange[]")
  378. of 3913: return DbType(kind: DbTypeKind.dbArray, name: "daterange[]")
  379. of 3927: return DbType(kind: DbTypeKind.dbArray, name: "int8range[]")
  380. of 2287: return DbType(kind: DbTypeKind.dbArray, name: "record[]")
  381. of 705: return DbType(kind: DbTypeKind.dbUnknown, name: "unknown")
  382. else: return DbType(kind: DbTypeKind.dbUnknown, name: $oid) ## Query the system table pg_type to determine exactly which type is referenced.
  383. proc setColumnInfo(columns: var DbColumns; res: PPGresult, L: int32) =
  384. setLen(columns, L)
  385. for i in 0'i32..<L:
  386. columns[i].name = $pqfname(res, i)
  387. columns[i].typ = getColumnType(res, i)
  388. columns[i].tableName = $(pqftable(res, i)) ## Returns the OID of the table from which the given column was fetched.
  389. ## Query the system table pg_class to determine exactly which table is referenced.
  390. #columns[i].primaryKey = libpq does not have a function for that
  391. #columns[i].foreignKey = libpq does not have a function for that
  392. iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery;
  393. args: varargs[string, `$`]): InstantRow
  394. {.tags: [ReadDbEffect].} =
  395. setupSingeRowQuery(db, query, args)
  396. var res: PPGresult = nil
  397. var colsObtained = false
  398. while true:
  399. res = pqgetresult(db)
  400. if not colsObtained:
  401. setColumnInfo(columns, res, pqnfields(res))
  402. colsObtained = true
  403. if res == nil:
  404. break
  405. let status = pqresultStatus(res)
  406. if status == PGRES_TUPLES_OK:
  407. discard
  408. elif status != PGRES_SINGLE_TUPLE:
  409. dbError(db)
  410. else:
  411. yield InstantRow(res: res)
  412. pqclear(res)
  413. proc `[]`*(row: InstantRow; col: int): string {.inline.} =
  414. ## returns text for given column of the row
  415. $pqgetvalue(row.res, int32(0), int32(col))
  416. proc unsafeColumnAt*(row: InstantRow, index: int): cstring {.inline.} =
  417. ## Return cstring of given column of the row
  418. pqgetvalue(row.res, int32(0), int32(index))
  419. proc len*(row: InstantRow): int {.inline.} =
  420. ## returns number of columns in the row
  421. int(pqNfields(row.res))
  422. proc getRow(res: PPGresult): Row =
  423. let L = pqnfields(res)
  424. result = newRow(L)
  425. if pqntuples(res) > 0:
  426. setRow(res, result, 0, L)
  427. pqclear(res)
  428. proc getRow*(db: DbConn, query: SqlQuery,
  429. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  430. ## retrieves a single row. If the query doesn't return any rows, this proc
  431. ## will return a Row with empty strings for each column.
  432. let res = setupQuery(db, query, args)
  433. result = getRow(res)
  434. proc getRow*(db: DbConn, stmtName: SqlPrepared,
  435. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  436. let res = setupQuery(db, stmtName, args)
  437. result = getRow(res)
  438. proc getAllRows(res: PPGresult): seq[Row] =
  439. let N = pqntuples(res)
  440. let L = pqnfields(res)
  441. result = newSeqOfCap[Row](N)
  442. var row = newRow(L)
  443. for i in 0'i32..N-1:
  444. setRow(res, row, i, L)
  445. result.add(row)
  446. pqclear(res)
  447. proc getAllRows*(db: DbConn, query: SqlQuery,
  448. args: varargs[string, `$`]): seq[Row] {.
  449. tags: [ReadDbEffect].} =
  450. ## executes the query and returns the whole result dataset.
  451. let res = setupQuery(db, query, args)
  452. result = getAllRows(res)
  453. proc getAllRows*(db: DbConn, stmtName: SqlPrepared,
  454. args: varargs[string, `$`]): seq[Row] {.tags:
  455. [ReadDbEffect].} =
  456. ## executes the prepared query and returns the whole result dataset.
  457. let res = setupQuery(db, stmtName, args)
  458. result = getAllRows(res)
  459. iterator rows*(db: DbConn, query: SqlQuery,
  460. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  461. ## same as `fastRows`, but slower and safe.
  462. for r in items(getAllRows(db, query, args)): yield r
  463. iterator rows*(db: DbConn, stmtName: SqlPrepared,
  464. args: varargs[string, `$`]): Row {.tags: [ReadDbEffect].} =
  465. ## same as `fastRows`, but slower and safe.
  466. for r in items(getAllRows(db, stmtName, args)): yield r
  467. proc getValue(res: PPGresult): string =
  468. if pqntuples(res) > 0:
  469. var x = pqgetvalue(res, 0, 0)
  470. result = if isNil(x): "" else: $x
  471. else:
  472. result = ""
  473. proc getValue*(db: DbConn, query: SqlQuery,
  474. args: varargs[string, `$`]): string {.
  475. tags: [ReadDbEffect].} =
  476. ## executes the query and returns the first column of the first row of the
  477. ## result dataset. Returns "" if the dataset contains no rows or the database
  478. ## value is NULL.
  479. let res = setupQuery(db, query, args)
  480. result = getValue(res)
  481. pqclear(res)
  482. proc getValue*(db: DbConn, stmtName: SqlPrepared,
  483. args: varargs[string, `$`]): string {.
  484. tags: [ReadDbEffect].} =
  485. ## executes the query and returns the first column of the first row of the
  486. ## result dataset. Returns "" if the dataset contains no rows or the database
  487. ## value is NULL.
  488. let res = setupQuery(db, stmtName, args)
  489. result = getValue(res)
  490. pqclear(res)
  491. proc tryInsertID*(db: DbConn, query: SqlQuery,
  492. args: varargs[string, `$`]): int64 {.
  493. tags: [WriteDbEffect].}=
  494. ## executes the query (typically "INSERT") and returns the
  495. ## generated ID for the row or -1 in case of an error. For Postgre this adds
  496. ## `RETURNING id` to the query, so it only works if your primary key is
  497. ## named `id`.
  498. let res = setupQuery(db, SqlQuery(string(query) & " RETURNING id"),
  499. args)
  500. var x = pqgetvalue(res, 0, 0)
  501. if not isNil(x):
  502. result = parseBiggestInt($x)
  503. else:
  504. result = -1
  505. pqclear(res)
  506. proc insertID*(db: DbConn, query: SqlQuery,
  507. args: varargs[string, `$`]): int64 {.
  508. tags: [WriteDbEffect].} =
  509. ## executes the query (typically "INSERT") and returns the
  510. ## generated ID for the row. For Postgre this adds
  511. ## `RETURNING id` to the query, so it only works if your primary key is
  512. ## named `id`.
  513. result = tryInsertID(db, query, args)
  514. if result < 0: dbError(db)
  515. proc tryInsert*(db: DbConn, query: SqlQuery,pkName: string,
  516. args: varargs[string, `$`]): int64
  517. {.tags: [WriteDbEffect], since: (1, 3).}=
  518. ## executes the query (typically "INSERT") and returns the
  519. ## generated ID for the row or -1 in case of an error.
  520. let res = setupQuery(db, SqlQuery(string(query) & " RETURNING " & pkName),
  521. args)
  522. var x = pqgetvalue(res, 0, 0)
  523. if not isNil(x):
  524. result = parseBiggestInt($x)
  525. else:
  526. result = -1
  527. pqclear(res)
  528. proc insert*(db: DbConn, query: SqlQuery, pkName: string,
  529. args: varargs[string, `$`]): int64
  530. {.tags: [WriteDbEffect], since: (1, 3).} =
  531. ## executes the query (typically "INSERT") and returns the
  532. ## generated ID
  533. result = tryInsert(db, query, pkName, args)
  534. if result < 0: dbError(db)
  535. proc execAffectedRows*(db: DbConn, query: SqlQuery,
  536. args: varargs[string, `$`]): int64 {.tags: [
  537. ReadDbEffect, WriteDbEffect].} =
  538. ## executes the query (typically "UPDATE") and returns the
  539. ## number of affected rows.
  540. var q = dbFormat(query, args)
  541. var res = pqExec(db, q)
  542. if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  543. result = parseBiggestInt($pqcmdTuples(res))
  544. pqclear(res)
  545. proc execAffectedRows*(db: DbConn, stmtName: SqlPrepared,
  546. args: varargs[string, `$`]): int64 {.tags: [
  547. ReadDbEffect, WriteDbEffect].} =
  548. ## executes the query (typically "UPDATE") and returns the
  549. ## number of affected rows.
  550. var arr = allocCStringArray(args)
  551. var res = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
  552. nil, nil, 0)
  553. deallocCStringArray(arr)
  554. if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
  555. result = parseBiggestInt($pqcmdTuples(res))
  556. pqclear(res)
  557. proc close*(db: DbConn) {.tags: [DbEffect].} =
  558. ## closes the database connection.
  559. if db != nil: pqfinish(db)
  560. proc open*(connection, user, password, database: string): DbConn {.
  561. tags: [DbEffect].} =
  562. ## opens a database connection. Raises `EDb` if the connection could not
  563. ## be established.
  564. ##
  565. ## Clients can also use Postgres keyword/value connection strings to
  566. ## connect.
  567. ##
  568. ## Example:
  569. ##
  570. ## .. code-block:: nim
  571. ##
  572. ## con = open("", "", "", "host=localhost port=5432 dbname=mydb")
  573. ##
  574. ## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  575. ## for more information.
  576. let
  577. colonPos = connection.find(':')
  578. host = if colonPos < 0: connection
  579. else: substr(connection, 0, colonPos-1)
  580. port = if colonPos < 0: ""
  581. else: substr(connection, colonPos+1)
  582. result = pqsetdbLogin(host, port, nil, nil, database, user, password)
  583. if pqStatus(result) != CONNECTION_OK: dbError(result) # result = nil
  584. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  585. tags: [DbEffect].} =
  586. ## sets the encoding of a database connection, returns true for
  587. ## success, false for failure.
  588. return pqsetClientEncoding(connection, encoding) == 0
  589. # Tests are in ../../tests/untestable/tpostgres.