db_odbc.nim 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 $buf.cstring
  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. if args[a] == nil:
  193. add(result, "NULL")
  194. else:
  195. add(result, dbQuote(args[a]))
  196. inc(a)
  197. else:
  198. add(result, c)
  199. proc prepareFetch(db: var DbConn, query: SqlQuery,
  200. args: varargs[string, `$`]): TSqlSmallInt {.
  201. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  202. # Prepare a statement, execute it and fetch the data to the driver
  203. # ready for retrieval of the data
  204. # Used internally by iterators and retrieval procs
  205. # requires calling
  206. # properFreeResult(SQL_HANDLE_STMT, db.stmt)
  207. # when finished
  208. db.sqlCheck(SQLAllocHandle(SQL_HANDLE_STMT, db.hDb, db.stmt))
  209. var q = dbFormat(query, args)
  210. db.sqlCheck(SQLPrepare(db.stmt, q.PSQLCHAR, q.len.TSqlSmallInt))
  211. db.sqlCheck(SQLExecute(db.stmt))
  212. result = SQLFetch(db.stmt)
  213. db.sqlCheck(result)
  214. proc prepareFetchDirect(db: var DbConn, query: SqlQuery,
  215. args: varargs[string, `$`]) {.
  216. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  217. # Prepare a statement, execute it and fetch the data to the driver
  218. # ready for retrieval of the data
  219. # Used internally by iterators and retrieval procs
  220. # requires calling
  221. # properFreeResult(SQL_HANDLE_STMT, db.stmt)
  222. # when finished
  223. db.sqlCheck(SQLAllocHandle(SQL_HANDLE_STMT, db.hDb, db.stmt))
  224. var q = dbFormat(query, args)
  225. db.sqlCheck(SQLExecDirect(db.stmt, q.PSQLCHAR, q.len.TSqlSmallInt))
  226. db.sqlCheck(SQLFetch(db.stmt))
  227. proc tryExec*(db: var DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.
  228. tags: [ReadDbEffect, WriteDbEffect], raises: [].} =
  229. ## Tries to execute the query and returns true if successful, false otherwise.
  230. var
  231. res:TSqlSmallInt = -1
  232. try:
  233. db.prepareFetchDirect(query, args)
  234. var
  235. rCnt = -1
  236. res = SQLRowCount(db.stmt, rCnt)
  237. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  238. if res != SQL_SUCCESS: dbError(db)
  239. except: discard
  240. return res == SQL_SUCCESS
  241. proc rawExec(db: var DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  242. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  243. db.prepareFetchDirect(query, args)
  244. proc exec*(db: var DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
  245. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  246. ## Executes the query and raises EDB if not successful.
  247. db.prepareFetchDirect(query, args)
  248. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  249. proc newRow(L: int): Row {.noSideEFfect.} =
  250. newSeq(result, L)
  251. for i in 0..L-1: result[i] = ""
  252. iterator fastRows*(db: var DbConn, query: SqlQuery,
  253. args: varargs[string, `$`]): Row {.
  254. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  255. ## Executes the query and iterates over the result dataset.
  256. ##
  257. ## This is very fast, but potentially dangerous. Use this iterator only
  258. ## if you require **ALL** the rows.
  259. ##
  260. ## Breaking the fastRows() iterator during a loop may cause a driver error
  261. ## for subsequenct queries
  262. ##
  263. ## Rows are retrieved from the server at each iteration.
  264. var
  265. rowRes: Row
  266. sz: TSqlSmallInt = 0
  267. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  268. res: TSqlSmallInt = 0.TSqlSmallInt
  269. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  270. # tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  271. # after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  272. # so the values of the temporary variable to store the cCnt.
  273. # After every cycle and specified to cCnt. To ensure the traversal of all fields.
  274. res = db.prepareFetch(query, args)
  275. if res == SQL_NO_DATA:
  276. discard
  277. elif res == SQL_SUCCESS:
  278. res = SQLNumResultCols(db.stmt, cCnt)
  279. rowRes = newRow(cCnt)
  280. rowRes.setLen(max(cCnt,0))
  281. tempcCnt = cCnt
  282. while res == SQL_SUCCESS:
  283. for colId in 1..cCnt:
  284. buf[0] = '\0'
  285. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  286. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  287. rowRes[colId-1] = $buf.cstring
  288. cCnt = tempcCnt
  289. yield rowRes
  290. res = SQLFetch(db.stmt)
  291. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  292. db.sqlCheck(res)
  293. iterator instantRows*(db: var DbConn, query: SqlQuery,
  294. args: varargs[string, `$`]): InstantRow
  295. {.tags: [ReadDbEffect, WriteDbEffect].} =
  296. ## Same as fastRows but returns a handle that can be used to get column text
  297. ## on demand using []. Returned handle is valid only within the interator body.
  298. var
  299. rowRes: Row = @[]
  300. sz: TSqlSmallInt = 0
  301. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  302. res: TSqlSmallInt = 0.TSqlSmallInt
  303. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  304. # tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  305. # after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  306. # so the values of the temporary variable to store the cCnt.
  307. # After every cycle and specified to cCnt. To ensure the traversal of all fields.
  308. res = db.prepareFetch(query, args)
  309. if res == SQL_NO_DATA:
  310. discard
  311. elif res == SQL_SUCCESS:
  312. res = SQLNumResultCols(db.stmt, cCnt)
  313. rowRes = newRow(cCnt)
  314. rowRes.setLen(max(cCnt,0))
  315. tempcCnt = cCnt
  316. while res == SQL_SUCCESS:
  317. for colId in 1..cCnt:
  318. buf[0] = '\0'
  319. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  320. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  321. rowRes[colId-1] = $buf.cstring
  322. cCnt = tempcCnt
  323. yield (row: rowRes, len: cCnt.int)
  324. res = SQLFetch(db.stmt)
  325. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  326. db.sqlCheck(res)
  327. proc `[]`*(row: InstantRow, col: int): string {.inline.} =
  328. ## Returns text for given column of the row
  329. row.row[col]
  330. proc len*(row: InstantRow): int {.inline.} =
  331. ## Returns number of columns in the row
  332. row.len
  333. proc getRow*(db: var DbConn, query: SqlQuery,
  334. args: varargs[string, `$`]): Row {.
  335. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  336. ## Retrieves a single row. If the query doesn't return any rows, this proc
  337. ## will return a Row with empty strings for each column.
  338. var
  339. rowRes: Row
  340. sz: TSqlSmallInt = 0.TSqlSmallInt
  341. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  342. res: TSqlSmallInt = 0.TSqlSmallInt
  343. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  344. ## tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  345. ## after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  346. ## so the values of the temporary variable to store the cCnt.
  347. ## After every cycle and specified to cCnt. To ensure the traversal of all fields.
  348. res = db.prepareFetch(query, args)
  349. if res == SQL_NO_DATA:
  350. result = @[]
  351. elif res == SQL_SUCCESS:
  352. res = SQLNumResultCols(db.stmt, cCnt)
  353. rowRes = newRow(cCnt)
  354. rowRes.setLen(max(cCnt,0))
  355. tempcCnt = cCnt
  356. for colId in 1..cCnt:
  357. buf[0] = '\0'
  358. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  359. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  360. rowRes[colId-1] = $buf.cstring
  361. cCnt = tempcCnt
  362. res = SQLFetch(db.stmt)
  363. result = rowRes
  364. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  365. db.sqlCheck(res)
  366. proc getAllRows*(db: var DbConn, query: SqlQuery,
  367. args: varargs[string, `$`]): seq[Row] {.
  368. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError] .} =
  369. ## Executes the query and returns the whole result dataset.
  370. var
  371. rows: seq[Row] = @[]
  372. rowRes: Row
  373. sz: TSqlSmallInt = 0
  374. cCnt: TSqlSmallInt = 0.TSqlSmallInt
  375. res: TSqlSmallInt = 0.TSqlSmallInt
  376. tempcCnt: TSqlSmallInt # temporary cCnt,Fix the field values to be null when the release schema is compiled.
  377. ## tempcCnt,A field to store the number of temporary variables, for unknown reasons,
  378. ## after performing a sqlgetdata function and circulating variables cCnt value will be changed to 0,
  379. ## so the values of the temporary variable to store the cCnt.
  380. ## After every cycle and specified to cCnt. To ensure the traversal of all fields.
  381. res = db.prepareFetch(query, args)
  382. if res == SQL_NO_DATA:
  383. result = @[]
  384. elif res == SQL_SUCCESS:
  385. res = SQLNumResultCols(db.stmt, cCnt)
  386. rowRes = newRow(cCnt)
  387. rowRes.setLen(max(cCnt,0))
  388. tempcCnt = cCnt
  389. while res == SQL_SUCCESS:
  390. for colId in 1..cCnt:
  391. buf[0] = '\0'
  392. db.sqlCheck(SQLGetData(db.stmt, colId.SqlUSmallInt, SQL_C_CHAR,
  393. cast[cstring](buf.addr), 4095.TSqlSmallInt, sz.addr))
  394. rowRes[colId-1] = $buf.cstring
  395. cCnt = tempcCnt
  396. rows.add(rowRes)
  397. res = SQLFetch(db.stmt)
  398. result = rows
  399. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  400. db.sqlCheck(res)
  401. iterator rows*(db: var DbConn, query: SqlQuery,
  402. args: varargs[string, `$`]): Row {.
  403. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  404. ## Same as `fastRows`, but slower and safe.
  405. ##
  406. ## This retrieves ALL rows into memory before
  407. ## iterating through the rows.
  408. ## Large dataset queries will impact on memory usage.
  409. for r in items(getAllRows(db, query, args)): yield r
  410. proc getValue*(db: var DbConn, query: SqlQuery,
  411. args: varargs[string, `$`]): string {.
  412. tags: [ReadDbEffect, WriteDbEffect], raises: [].} =
  413. ## Executes the query and returns the first column of the first row of the
  414. ## result dataset. Returns "" if the dataset contains no rows or the database
  415. ## value is NULL.
  416. result = ""
  417. try:
  418. result = getRow(db, query, args)[0]
  419. except: discard
  420. proc tryInsertId*(db: var DbConn, query: SqlQuery,
  421. args: varargs[string, `$`]): int64 {.
  422. tags: [ReadDbEffect, WriteDbEffect], raises: [].} =
  423. ## Executes the query (typically "INSERT") and returns the
  424. ## generated ID for the row or -1 in case of an error.
  425. if not tryExec(db, query, args):
  426. result = -1'i64
  427. else:
  428. result = -1'i64
  429. try:
  430. case sqlGetDBMS(db).toLower():
  431. of "postgresql":
  432. result = getValue(db, sql"SELECT LASTVAL();", []).parseInt
  433. of "mysql":
  434. result = getValue(db, sql"SELECT LAST_INSERT_ID();", []).parseInt
  435. of "sqlite":
  436. result = getValue(db, sql"SELECT LAST_INSERT_ROWID();", []).parseInt
  437. of "microsoft sql server":
  438. result = getValue(db, sql"SELECT SCOPE_IDENTITY();", []).parseInt
  439. of "oracle":
  440. result = getValue(db, sql"SELECT id.currval FROM DUAL;", []).parseInt
  441. else: result = -1'i64
  442. except: discard
  443. proc insertId*(db: var DbConn, query: SqlQuery,
  444. args: varargs[string, `$`]): int64 {.
  445. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  446. ## Executes the query (typically "INSERT") and returns the
  447. ## generated ID for the row.
  448. result = tryInsertID(db, query, args)
  449. if result < 0: dbError(db)
  450. proc execAffectedRows*(db: var DbConn, query: SqlQuery,
  451. args: varargs[string, `$`]): int64 {.
  452. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  453. ## Runs the query (typically "UPDATE") and returns the
  454. ## number of affected rows
  455. result = -1
  456. db.sqlCheck(SQLAllocHandle(SQL_HANDLE_STMT, db.hDb, db.stmt.SqlHandle))
  457. var q = dbFormat(query, args)
  458. db.sqlCheck(SQLPrepare(db.stmt, q.PSQLCHAR, q.len.TSqlSmallInt))
  459. rawExec(db, query, args)
  460. var rCnt = -1
  461. db.sqlCheck(SQLRowCount(db.hDb, rCnt))
  462. properFreeResult(SQL_HANDLE_STMT, db.stmt)
  463. result = rCnt
  464. proc close*(db: var DbConn) {.
  465. tags: [WriteDbEffect], raises: [].} =
  466. ## Closes the database connection.
  467. if db.hDb != nil:
  468. try:
  469. var res = SQLDisconnect(db.hDb)
  470. if db.stmt != nil:
  471. res = SQLFreeHandle(SQL_HANDLE_STMT, db.stmt)
  472. res = SQLFreeHandle(SQL_HANDLE_DBC, db.hDb)
  473. res = SQLFreeHandle(SQL_HANDLE_ENV, db.env)
  474. db = (hDb: nil, env: nil, stmt: nil)
  475. except:
  476. discard
  477. proc open*(connection, user, password, database: string): DbConn {.
  478. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  479. ## Opens a database connection.
  480. ##
  481. ## Raises `EDb` if the connection could not be established.
  482. ##
  483. ## Currently the database parameter is ignored,
  484. ## but included to match ``open()`` in the other db_xxxxx library modules.
  485. var
  486. val: TSqlInteger = SQL_OV_ODBC3
  487. resLen = 0
  488. result = (hDb: nil, env: nil, stmt: nil)
  489. # allocate environment handle
  490. var res = SQLAllocHandle(SQL_HANDLE_ENV, result.env, result.env)
  491. if res != SQL_SUCCESS: dbError("Error: unable to initialise ODBC environment.")
  492. res = SQLSetEnvAttr(result.env,
  493. SQL_ATTR_ODBC_VERSION.TSqlInteger,
  494. val, resLen.TSqlInteger)
  495. if res != SQL_SUCCESS: dbError("Error: unable to set ODBC driver version.")
  496. # allocate hDb handle
  497. res = SQLAllocHandle(SQL_HANDLE_DBC, result.env, result.hDb)
  498. if res != SQL_SUCCESS: dbError("Error: unable to allocate connection handle.")
  499. # Connect: connection = dsn str,
  500. res = SQLConnect(result.hDb,
  501. connection.PSQLCHAR , connection.len.TSqlSmallInt,
  502. user.PSQLCHAR, user.len.TSqlSmallInt,
  503. password.PSQLCHAR, password.len.TSqlSmallInt)
  504. if res != SQL_SUCCESS:
  505. result.dbError()
  506. proc setEncoding*(connection: DbConn, encoding: string): bool {.
  507. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} =
  508. ## Currently not implemented for ODBC.
  509. ##
  510. ## Sets the encoding of a database connection, returns true for
  511. ## success, false for failure.
  512. ##result = set_character_set(connection, encoding) == 0
  513. dbError("setEncoding() is currently not implemented by the db_odbc module")