db_odbc.nim 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## A higher level `ODBC` database wrapper.
  10. ##
  11. ## This is the same interface that is implemented for other databases.
  12. ##
  13. ## This has NOT yet been (extensively) tested against ODBC drivers for
  14. ## Teradata, Oracle, Sybase, MSSqlvSvr, et. al. databases.
  15. ##
  16. ## Currently all queries are ANSI calls, not Unicode.
  17. ##
  18. ## See also: `db_postgres <db_postgres.html>`_, `db_sqlite <db_sqlite.html>`_,
  19. ## `db_mysql <db_mysql.html>`_.
  20. ##
  21. ## Parameter substitution
  22. ## ----------------------
  23. ##
  24. ## All ``db_*`` modules support the same form of parameter substitution.
  25. ## That is, using the ``?`` (question mark) to signify the place where a
  26. ## value should be placed. For example:
  27. ##
  28. ## .. code-block:: Nim
  29. ## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
  30. ##
  31. ##
  32. ## Examples
  33. ## --------
  34. ##
  35. ## Opening a connection to a database
  36. ## ==================================
  37. ##
  38. ## .. code-block:: Nim
  39. ## import db_odbc
  40. ## var db = open("localhost", "user", "password", "dbname")
  41. ## db.close()
  42. ##
  43. ## Creating a table
  44. ## ================
  45. ##
  46. ## .. code-block:: Nim
  47. ## db.exec(sql"DROP TABLE IF EXISTS myTable")
  48. ## db.exec(sql("""CREATE TABLE myTable (
  49. ## id integer,
  50. ## name varchar(50) not null)"""))
  51. ##
  52. ## Inserting data
  53. ## ==============
  54. ##
  55. ## .. code-block:: Nim
  56. ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
  57. ## "Andreas")
  58. ##
  59. ## Large example
  60. ## =============
  61. ##
  62. ## .. code-block:: Nim
  63. ##
  64. ## import db_odbc, math
  65. ##
  66. ## var theDb = open("localhost", "nim", "nim", "test")
  67. ##
  68. ## theDb.exec(sql"Drop table if exists myTestTbl")
  69. ## theDb.exec(sql("create table myTestTbl (" &
  70. ## " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
  71. ## " Name VARCHAR(50) NOT NULL, " &
  72. ## " i INT(11), " &
  73. ## " f DECIMAL(18,10))"))
  74. ##
  75. ## theDb.exec(sql"START TRANSACTION")
  76. ## for i in 1..1000:
  77. ## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  78. ## "Item#" & $i, i, sqrt(i.float))
  79. ## theDb.exec(sql"COMMIT")
  80. ##
  81. ## for x in theDb.fastRows(sql"select * from myTestTbl"):
  82. ## echo x
  83. ##
  84. ## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
  85. ## "Item#1001", 1001, sqrt(1001.0))
  86. ## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
  87. ##
  88. ## theDb.close()
  89. import strutils, odbcsql
  90. import db_common
  91. export db_common
  92. type
  93. OdbcConnTyp = tuple[hDb: SqlHDBC, env: SqlHEnv, stmt: SqlHStmt]
  94. DbConn* = OdbcConnTyp ## encapsulates a database connection
  95. Row* = seq[string] ## a row of a dataset. NULL database values will be
  96. ## converted to nil.
  97. InstantRow* = tuple[row: seq[string], len: int] ## a handle that can be
  98. ## used to get a row's
  99. ## column text on demand
  100. {.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].}
  101. var
  102. buf: array[0..4096, char]
  103. proc properFreeResult(hType: int, sqlres: var SqlHandle) {.
  104. tags: [WriteDbEffect], raises: [].} =
  105. try:
  106. discard SQLFreeHandle(hType.TSqlSmallInt, sqlres)
  107. sqlres = nil
  108. except: discard
  109. proc getErrInfo(db: var DbConn): tuple[res: int, ss, ne, msg: string] {.
  110. tags: [ReadDbEffect], raises: [].} =
  111. ## Returns ODBC error information
  112. var
  113. sqlState: array[0..512, char]
  114. nativeErr: array[0..512, char]
  115. errMsg: array[0..512, char]
  116. retSz: TSqlSmallInt = 0
  117. res: TSqlSmallInt = 0
  118. try:
  119. sqlState[0] = '\0'
  120. nativeErr[0] = '\0'
  121. errMsg[0] = '\0'
  122. res = SQLErr(db.env, db.hDb, db.stmt,
  123. cast[PSQLCHAR](sqlState.addr),
  124. cast[PSQLCHAR](nativeErr.addr),
  125. cast[PSQLCHAR](errMsg.addr),
  126. 511.TSqlSmallInt, retSz.addr.PSQLSMALLINT)
  127. except:
  128. discard
  129. return (res.int, $sqlState, $nativeErr, $errMsg)
  130. proc dbError*(db: var DbConn) {.
  131. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError] .} =
  132. ## Raises an `[DbError]` exception with ODBC error information
  133. var
  134. e: ref DbError
  135. ss, ne, msg: string = ""
  136. isAnError = false
  137. res: int = 0
  138. prevSs = ""
  139. while true:
  140. prevSs = ss
  141. (res, ss, ne, msg) = db.getErrInfo()
  142. if prevSs == ss:
  143. break
  144. # sqlState of 00000 is not an error
  145. elif ss == "00000":
  146. break
  147. elif ss == "01000":
  148. echo "\nWarning: ", ss, " ", msg
  149. continue
  150. else:
  151. isAnError = true
  152. echo "\nError: ", ss, " ", msg
  153. if isAnError:
  154. new(e)
  155. e.msg = "ODBC Error"
  156. if db.stmt != nil:
  157. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  158. properFreeResult(SQL_HANDLE_DBC, db.hDb)
  159. properFreeResult(SQL_HANDLE_ENV, db.env)
  160. raise e
  161. proc sqlCheck(db: var DbConn, resVal: TSqlSmallInt) {.raises: [DbError]} =
  162. ## Wrapper that raises [EDb] if ``resVal`` is neither SQL_SUCCESS or SQL_NO_DATA
  163. if resVal notIn [SQL_SUCCESS, SQL_NO_DATA]: dbError(db)
  164. proc sqlGetDBMS(db: var DbConn): string {.
  165. tags: [ReadDbEffect, WriteDbEffect], raises: [] .} =
  166. ## Returns the ODBC SQL_DBMS_NAME string
  167. const
  168. SQL_DBMS_NAME = 17.SqlUSmallInt
  169. var
  170. sz: TSqlSmallInt = 0
  171. buf[0] = '\0'
  172. try:
  173. db.sqlCheck(SQLGetInfo(db.hDb, SQL_DBMS_NAME, cast[SqlPointer](buf.addr),
  174. 4095.TSqlSmallInt, sz.addr))
  175. except: discard
  176. return $(addr buf)
  177. proc dbQuote*(s: string): string {.noSideEffect.} =
  178. ## DB quotes the string.
  179. result = "'"
  180. for c in items(s):
  181. if c == '\'': add(result, "''")
  182. else: add(result, c)
  183. add(result, '\'')
  184. proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string {.
  185. noSideEffect.} =
  186. ## Replace any ``?`` placeholders with `args`,
  187. ## and quotes the arguments
  188. result = ""
  189. var a = 0
  190. for c in items(string(formatstr)):
  191. if c == '?':
  192. add(result, dbQuote(args[a]))
  193. inc(a)
  194. else:
  195. add(result, c)
  196. proc prepareFetch(db: var DbConn, query: SqlQuery,
  197. args: varargs[string, `$`]): TSqlSmallInt {.
  198. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  199. # Prepare a statement, execute it and fetch the data to the driver
  200. # ready for retrieval of the data
  201. # Used internally by iterators and retrieval procs
  202. # requires calling
  203. # properFreeResult(SQL_HANDLE_STMT, db.stmt)
  204. # when finished
  205. db.sqlCheck(SQLAllocHandle(SQL_HANDLE_STMT, db.hDb, db.stmt))
  206. var q = dbFormat(query, args)
  207. db.sqlCheck(SQLPrepare(db.stmt, q.PSQLCHAR, q.len.TSqlSmallInt))
  208. db.sqlCheck(SQLExecute(db.stmt))
  209. result = SQLFetch(db.stmt)
  210. db.sqlCheck(result)
  211. proc prepareFetchDirect(db: var DbConn, query: SqlQuery,
  212. args: varargs[string, `$`]) {.
  213. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  214. # Prepare a statement, execute it and fetch the data to the driver
  215. # ready for retrieval of the data
  216. # Used internally by iterators and retrieval procs
  217. # requires calling
  218. # properFreeResult(SQL_HANDLE_STMT, db.stmt)
  219. # when finished
  220. db.sqlCheck(SQLAllocHandle(SQL_HANDLE_STMT, db.hDb, db.stmt))
  221. var q = dbFormat(query, args)
  222. db.sqlCheck(SQLExecDirect(db.stmt, q.PSQLCHAR, q.len.TSqlSmallInt))
  223. db.sqlCheck(SQLFetch(db.stmt))
  224. proc tryExec*(db: var DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.
  225. tags: [ReadDbEffect, WriteDbEffect], raises: [].} =
  226. ## Tries to execute the query and returns true if successful, false otherwise.
  227. var
  228. res:TSqlSmallInt = -1
  229. try:
  230. db.prepareFetchDirect(query, args)
  231. var
  232. rCnt = -1
  233. res = SQLRowCount(db.stmt, rCnt)
  234. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  235. if res != SQL_SUCCESS: dbError(db)
  236. except: discard
  237. return res == SQL_SUCCESS
  238. proc rawExec(db: var DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  239. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  240. db.prepareFetchDirect(query, args)
  241. proc exec*(db: var DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  242. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  243. ## Executes the query and raises EDB if not successful.
  244. db.prepareFetchDirect(query, args)
  245. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  246. proc newRow(L: int): Row {.noSideEFfect.} =
  247. newSeq(result, L)
  248. for i in 0..L-1: result[i] = ""
  249. iterator fastRows*(db: var DbConn, query: SqlQuery,
  250. args: varargs[string, `$`]): Row {.
  251. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  252. ## Executes the query and iterates over the result dataset.
  253. ##
  254. ## This is very fast, but potentially dangerous. Use this iterator only
  255. ## if you require **ALL** the rows.
  256. ##
  257. ## Breaking the fastRows() iterator during a loop may cause a driver error
  258. ## for subsequenct queries
  259. ##
  260. ## Rows are retrieved from the server at each iteration.
  261. var
  262. rowRes: Row
  263. sz: TSqlSmallInt = 0
  264. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  265. res: TSqlSmallInt = 0.TSqlSmallInt
  266. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  267. # tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  268. # after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  269. # so the values of the temporary variable to store the cCnt.
  270. # After every cycle and specified to cCnt. To ensure the traversal of all fields.
  271. res = db.prepareFetch(query, args)
  272. if res == SQL_NO_DATA:
  273. discard
  274. elif res == SQL_SUCCESS:
  275. res = SQLNumResultCols(db.stmt, cCnt)
  276. rowRes = newRow(cCnt)
  277. rowRes.setLen(max(cCnt,0))
  278. tempcCnt = cCnt
  279. while res == SQL_SUCCESS:
  280. for colId in 1..cCnt:
  281. buf[0] = '\0'
  282. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  283. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  284. rowRes[colId-1] = $(addr buf)
  285. cCnt = tempcCnt
  286. yield rowRes
  287. res = SQLFetch(db.stmt)
  288. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  289. db.sqlCheck(res)
  290. iterator instantRows*(db: var DbConn, query: SqlQuery,
  291. args: varargs[string, `$`]): InstantRow
  292. {.tags: [ReadDbEffect, WriteDbEffect].} =
  293. ## Same as fastRows but returns a handle that can be used to get column text
  294. ## on demand using []. Returned handle is valid only within the interator body.
  295. var
  296. rowRes: Row = @[]
  297. sz: TSqlSmallInt = 0
  298. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  299. res: TSqlSmallInt = 0.TSqlSmallInt
  300. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  301. # tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  302. # after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  303. # so the values of the temporary variable to store the cCnt.
  304. # After every cycle and specified to cCnt. To ensure the traversal of all fields.
  305. res = db.prepareFetch(query, args)
  306. if res == SQL_NO_DATA:
  307. discard
  308. elif res == SQL_SUCCESS:
  309. res = SQLNumResultCols(db.stmt, cCnt)
  310. rowRes = newRow(cCnt)
  311. rowRes.setLen(max(cCnt,0))
  312. tempcCnt = cCnt
  313. while res == SQL_SUCCESS:
  314. for colId in 1..cCnt:
  315. buf[0] = '\0'
  316. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  317. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  318. rowRes[colId-1] = $(addr buf)
  319. cCnt = tempcCnt
  320. yield (row: rowRes, len: cCnt.int)
  321. res = SQLFetch(db.stmt)
  322. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  323. db.sqlCheck(res)
  324. proc `[]`*(row: InstantRow, col: int): string {.inline.} =
  325. ## Returns text for given column of the row
  326. row.row[col]
  327. proc len*(row: InstantRow): int {.inline.} =
  328. ## Returns number of columns in the row
  329. row.len
  330. proc getRow*(db: var DbConn, query: SqlQuery,
  331. args: varargs[string, `$`]): Row {.
  332. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  333. ## Retrieves a single row. If the query doesn't return any rows, this proc
  334. ## will return a Row with empty strings for each column.
  335. var
  336. rowRes: Row
  337. sz: TSqlSmallInt = 0.TSqlSmallInt
  338. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  339. res: TSqlSmallInt = 0.TSqlSmallInt
  340. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  341. ## tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  342. ## after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  343. ## so the values of the temporary variable to store the cCnt.
  344. ## After every cycle and specified to cCnt. To ensure the traversal of all fields.
  345. res = db.prepareFetch(query, args)
  346. if res == SQL_NO_DATA:
  347. result = @[]
  348. elif res == SQL_SUCCESS:
  349. res = SQLNumResultCols(db.stmt, cCnt)
  350. rowRes = newRow(cCnt)
  351. rowRes.setLen(max(cCnt,0))
  352. tempcCnt = cCnt
  353. for colId in 1..cCnt:
  354. buf[0] = '\0'
  355. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  356. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  357. rowRes[colId-1] = $(addr buf)
  358. cCnt = tempcCnt
  359. res = SQLFetch(db.stmt)
  360. result = rowRes
  361. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  362. db.sqlCheck(res)
  363. proc getAllRows*(db: var DbConn, query: SqlQuery,
  364. args: varargs[string, `$`]): seq[Row] {.
  365. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError] .} =
  366. ## Executes the query and returns the whole result dataset.
  367. var
  368. rows: seq[Row] = @[]
  369. rowRes: Row
  370. sz: TSqlSmallInt = 0
  371. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  372. res: TSqlSmallInt = 0.TSqlSmallInt
  373. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  374. ## tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  375. ## after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  376. ## so the values of the temporary variable to store the cCnt.
  377. ## After every cycle and specified to cCnt. To ensure the traversal of all fields.
  378. res = db.prepareFetch(query, args)
  379. if res == SQL_NO_DATA:
  380. result = @[]
  381. elif res == SQL_SUCCESS:
  382. res = SQLNumResultCols(db.stmt, cCnt)
  383. rowRes = newRow(cCnt)
  384. rowRes.setLen(max(cCnt,0))
  385. tempcCnt = cCnt
  386. while res == SQL_SUCCESS:
  387. for colId in 1..cCnt:
  388. buf[0] = '\0'
  389. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  390. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  391. rowRes[colId-1] = $(addr buf)
  392. cCnt = tempcCnt
  393. rows.add(rowRes)
  394. res = SQLFetch(db.stmt)
  395. result = rows
  396. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  397. db.sqlCheck(res)
  398. iterator rows*(db: var DbConn, query: SqlQuery,
  399. args: varargs[string, `$`]): Row {.
  400. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  401. ## Same as `fastRows`, but slower and safe.
  402. ##
  403. ## This retrieves ALL rows into memory before
  404. ## iterating through the rows.
  405. ## Large dataset queries will impact on memory usage.
  406. for r in items(getAllRows(db, query, args)): yield r
  407. proc getValue*(db: var DbConn, query: SqlQuery,
  408. args: varargs[string, `$`]): string {.
  409. tags: [ReadDbEffect, WriteDbEffect], raises: [].} =
  410. ## Executes the query and returns the first column of the first row of the
  411. ## result dataset. Returns "" if the dataset contains no rows or the database
  412. ## value is NULL.
  413. result = ""
  414. try:
  415. result = getRow(db, query, args)[0]
  416. except: discard
  417. proc tryInsertId*(db: var DbConn, query: SqlQuery,
  418. args: varargs[string, `$`]): int64 {.
  419. tags: [ReadDbEffect, WriteDbEffect], raises: [].} =
  420. ## Executes the query (typically "INSERT") and returns the
  421. ## generated ID for the row or -1 in case of an error.
  422. if not tryExec(db, query, args):
  423. result = -1'i64
  424. else:
  425. result = -1'i64
  426. try:
  427. case sqlGetDBMS(db).toLower():
  428. of "postgresql":
  429. result = getValue(db, sql"SELECT LASTVAL();", []).parseInt
  430. of "mysql":
  431. result = getValue(db, sql"SELECT LAST_INSERT_ID();", []).parseInt
  432. of "sqlite":
  433. result = getValue(db, sql"SELECT LAST_INSERT_ROWID();", []).parseInt
  434. of "microsoft sql server":
  435. result = getValue(db, sql"SELECT SCOPE_IDENTITY();", []).parseInt
  436. of "oracle":
  437. result = getValue(db, sql"SELECT id.currval FROM DUAL;", []).parseInt
  438. else: result = -1'i64
  439. except: discard
  440. proc insertId*(db: var DbConn, query: SqlQuery,
  441. args: varargs[string, `$`]): int64 {.
  442. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  443. ## Executes the query (typically "INSERT") and returns the
  444. ## generated ID for the row.
  445. result = tryInsertID(db, query, args)
  446. if result < 0: dbError(db)
  447. proc execAffectedRows*(db: var DbConn, query: SqlQuery,
  448. args: varargs[string, `$`]): int64 {.
  449. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  450. ## Runs the query (typically "UPDATE") and returns the
  451. ## number of affected rows
  452. result = -1
  453. db.sqlCheck(SQLAllocHandle(SQL_HANDLE_STMT, db.hDb, db.stmt.SqlHandle))
  454. var q = dbFormat(query, args)
  455. db.sqlCheck(SQLPrepare(db.stmt, q.PSQLCHAR, q.len.TSqlSmallInt))
  456. rawExec(db, query, args)
  457. var rCnt = -1
  458. db.sqlCheck(SQLRowCount(db.hDb, rCnt))
  459. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  460. result = rCnt
  461. proc close*(db: var DbConn) {.
  462. tags: [WriteDbEffect], raises: [].} =
  463. ## Closes the database connection.
  464. if db.hDb != nil:
  465. try:
  466. var res = SQLDisconnect(db.hDb)
  467. if db.stmt != nil:
  468. res = SQLFreeHandle(SQL_HANDLE_STMT, db.stmt)
  469. res = SQLFreeHandle(SQL_HANDLE_DBC, db.hDb)
  470. res = SQLFreeHandle(SQL_HANDLE_ENV, db.env)
  471. db = (hDb: nil, env: nil, stmt: nil)
  472. except:
  473. discard
  474. proc open*(connection, user, password, database: string): DbConn {.
  475. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  476. ## Opens a database connection.
  477. ##
  478. ## Raises `EDb` if the connection could not be established.
  479. ##
  480. ## Currently the database parameter is ignored,
  481. ## but included to match ``open()`` in the other db_xxxxx library modules.
  482. var
  483. val: TSqlInteger = SQL_OV_ODBC3
  484. resLen = 0
  485. result = (hDb: nil, env: nil, stmt: nil)
  486. # allocate environment handle
  487. var res = SQLAllocHandle(SQL_HANDLE_ENV, result.env, result.env)
  488. if res != SQL_SUCCESS: dbError("Error: unable to initialise ODBC environment.")
  489. res = SQLSetEnvAttr(result.env,
  490. SQL_ATTR_ODBC_VERSION.TSqlInteger,
  491. val, resLen.TSqlInteger)
  492. if res != SQL_SUCCESS: dbError("Error: unable to set ODBC driver version.")
  493. # allocate hDb handle
  494. res = SQLAllocHandle(SQL_HANDLE_DBC, result.env, result.hDb)
  495. if res != SQL_SUCCESS: dbError("Error: unable to allocate connection handle.")
  496. # Connect: connection = dsn str,
  497. res = SQLConnect(result.hDb,
  498. connection.PSQLCHAR , connection.len.TSqlSmallInt,
  499. user.PSQLCHAR, user.len.TSqlSmallInt,
  500. password.PSQLCHAR, password.len.TSqlSmallInt)
  501. if res != SQL_SUCCESS:
  502. result.dbError()
  503. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  504. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  505. ## Currently not implemented for ODBC.
  506. ##
  507. ## Sets the encoding of a database connection, returns true for
  508. ## success, false for failure.
  509. ##result = set_character_set(connection, encoding) == 0
  510. dbError("setEncoding() is currently not implemented by the db_odbc module")