psqlodbc.git / summary / log / commit / refs
commit 2c0f7b6db33da930f81f4136c7c23fada08aec6a
Author: Dave Cramer <davecramer@gmail.com>
Commit: GitHub <noreply@github.com>
Date: Thu Nov 26 11:56:55 2026 +0000
Fix the correctness defects found reviewing the driver (#244)
A review of the driver, run alongside the security review behind
18.00.0007, found defects in result and cursor handling, descriptors,
parameter binding, transactions, diagnostics, MSDTC enlistment and the
Windows CI jobs.
Changelog.md lists under Unreleased every change an application can
observe. Each of those a test can reach has a regression test: 22 new
files under test/src, with their expected output and their entries in
test/tests.
The Windows CI jobs install PostgreSQL 17.12 as an instance of their own
and check the major version the server reports, so a PostgreSQL that the
runner image ships is left stopped rather than upgraded in place.
.github/workflows/main.yml | 51 +++--
Changelog.md | 40 ++++
bind.c | 23 ++
connection.c | 302 +++++++++++++++++++++-----
connection.h | 10 +-
convert.c | 275 ++++++++++++++++-------
descriptor.c | 70 ++++--
dlg_specific.c | 20 +-
dlg_wingui.c | 4 +-
drvconn.c | 15 ++
environ.c | 74 ++++++-
environ.h | 3 +-
execute.c | 187 +++++++++++-----
info.c | 88 +++++++-
misc.c | 16 +-
msdtc_enlist.cpp | 41 +++-
multibyte.c | 20 +-
mylog.c | 2 +-
odbcapi.c | 2 +-
odbcapi30.c | 25 ++-
odbcapi30w.c | 228 +++++++++++++++++--
odbcapiw.c | 28 ++-
options.c | 41 +++-
parse.c | 26 ++-
pgapi30.c | 282 ++++++++++++++++++++++--
pgapifunc.h | 4 +
pgtypes.c | 5 +
pgxalib.cpp | 36 ++-
qresult.c | 76 ++++++-
qresult.h | 2 +
results.c | 158 +++++++++++---
secure_sscanf.c | 19 +-
setup.c | 28 ++-
statement.c | 220 +++++++++++++++----
statement.h | 15 +-
test/expected/arraybinding.out | 6 +
test/expected/bookmark-buffer-length.out | 5 +
test/expected/bulk-bookmark-declare-fetch.out | 6 +
test/expected/catalog-error-rollback.out | 10 +
test/expected/catalog-error-rollback_1.out | 10 +
test/expected/commit-failure.out | 9 +
test/expected/copydesc-param-name.out | 5 +
test/expected/desc-threads.out | 4 +
test/expected/descrec.out | 8 +
test/expected/descrec_1.out | 8 +
test/expected/descrec_2.out | 8 +
test/expected/diag-threads.out | 4 +
test/expected/diagnostic-w.out | 11 +
test/expected/error-rollback-readonly.out | 26 +++
test/expected/extendedfetch-rowcount.out | 26 +++
test/expected/fetch-before-first.out | 9 +
test/expected/fetch-refcursors.out | 9 +
test/expected/getdata-binary-nodata.out | 8 +
test/expected/identity.out | 5 +
test/expected/inheritance-keyset.out | 29 +++
test/expected/interval-type-name.out | 10 +
test/expected/ird-smallint-fields.out | 29 +++
test/expected/large-object-open-error.out | 7 +
test/expected/large-object.out | 3 +
test/expected/lost-connection-commit.out | 9 +
test/expected/lost-connection-commit_1.out | 9 +
test/expected/odbc-escapes.out | 14 ++
test/expected/odbc-escapes_1.out | 14 ++
test/expected/param-negative-length.out | 12 +
test/expected/positioned-delete-rollback.out | 14 ++
test/expected/pqopt-many.out | 4 +
test/expected/putdata-descriptor-params.out | 12 +
test/expected/query-timeout.out | 21 ++
test/expected/query-timeout_1.out | 19 ++
test/runsuite.c | 6 +-
test/src/arraybinding-test.c | 83 +++++++
test/src/bookmark-buffer-length-test.c | 93 ++++++++
test/src/bulk-bookmark-declare-fetch-test.c | 140 ++++++++++++
test/src/catalog-error-rollback-test.c | 150 +++++++++++++
test/src/commit-failure-test.c | 110 ++++++++++
test/src/copydesc-param-name-test.c | 56 +++++
test/src/desc-threads-test.c | 204 +++++++++++++++++
test/src/descrec-test.c | 65 ++++++
test/src/diag-threads-test.c | 203 +++++++++++++++++
test/src/diagnostic-w-test.c | 158 ++++++++++++++
test/src/error-rollback-readonly-test.c | 204 +++++++++++++++++
test/src/extendedfetch-rowcount-test.c | 77 +++++++
test/src/fetch-before-first-test.c | 104 +++++++++
test/src/fetch-refcursors-test.c | 76 +++++++
test/src/getdata-binary-nodata-test.c | 74 +++++++
test/src/identity-test.c | 24 ++
test/src/inheritance-keyset-test.c | 237 ++++++++++++++++++++
test/src/interval-type-name-test.c | 66 ++++++
test/src/ird-smallint-fields-test.c | 116 ++++++++++
test/src/large-object-open-error-test.c | 93 ++++++++
test/src/large-object-test.c | 28 +++
test/src/lost-connection-commit-test.c | 108 +++++++++
test/src/odbc-escapes-test.c | 7 +
test/src/param-negative-length-test.c | 97 +++++++++
test/src/positioned-delete-rollback-test.c | 167 ++++++++++++++
test/src/pqopt-many-test.c | 148 +++++++++++++
test/src/putdata-descriptor-params-test.c | 109 ++++++++++
test/src/query-timeout-test.c | 192 ++++++++++++++++
test/tests | 26 ++-
win_unicode.c | 5 +-
100 files changed, 5638 insertions(+), 407 deletions(-)
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 66027d10..2261e324 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -33,8 +33,11 @@ env:
WINFLEXBISON_VERSION: '2.5.24'
WORKFLOW_VERSION_POSTGRESQL: '1' # increment to invalidate cache
- # PostgreSQL x64 test server (EDB installer).
- POSTGRESQL_PACKAGE_FILEID: '1259019'
+ # PostgreSQL x64 test server (EDB installer): fileid 1260665 is
+ # postgresql-17.12-1-windows-x64.exe. Keep POSTGRESQL_SERVER_MAJOR in step:
+ # the test jobs fail if the server reports another major version.
+ POSTGRESQL_PACKAGE_FILEID: '1260665'
+ POSTGRESQL_SERVER_MAJOR: '17'
# Test utilities.
DIFFUTILS_VERSION: '2.8.7-1'
@@ -312,13 +315,19 @@ jobs:
target: c:\OTHERBIN
filename: postgresql_install.exe
- name: Install and start PostgreSQL server
- shell: cmd
+ shell: powershell
run: |
- echo on
- C:\OTHERBIN\postgresql_install.exe --mode unattended --unattendedmodeui none --superpassword password --enable-components server
- sc config "postgresql-x64-17" start= auto
- sc start "postgresql-x64-17"
- ping -n 6 127.0.0.1 >nul
+ # Some runner images ship a PostgreSQL of their own (windows-latest has
+ # 17.x as a disabled postgresql-x64-17 service). The EDB installer
+ # would upgrade that installation in place and keep its data directory
+ # and password, so keep it stopped, hide it from the installer and
+ # install the test server as a separate instance.
+ Get-Service postgresql* -ErrorAction SilentlyContinue | ForEach-Object { Stop-Service $_.Name -Force; Set-Service $_.Name -StartupType Disabled }
+ Remove-Item "HKLM:\SOFTWARE\PostgreSQL\Installations\postgresql-x64-*" -Recurse -ErrorAction SilentlyContinue
+ Remove-Item "HKLM:\SOFTWARE\PostgreSQL\Services\postgresql-x64-*" -Recurse -ErrorAction SilentlyContinue
+ $installer = Start-Process C:\OTHERBIN\postgresql_install.exe -Wait -PassThru -ArgumentList '--mode unattended --unattendedmodeui none --superpassword password --enable-components server --prefix C:\pgsql-ci --datadir C:\pgsql-ci\data --servicename postgresql-ci --serverport 5432'
+ if ($installer.ExitCode -ne 0) { Get-Content "$env:TEMP\install-postgresql.log" -Tail 40; throw "PostgreSQL installer exited with $($installer.ExitCode)" }
+ Get-Service postgresql* | Format-Table -AutoSize Name, Status, StartType | Out-String -Width 200
# -----------------------------------------------------------------
# Build and test psqlodbc
@@ -357,10 +366,10 @@ jobs:
working-directory: psqlodbc
run: |
# Compare against test/expected/v<major> where the server has one.
- $psql = (Get-ChildItem "C:\Program Files\PostgreSQL\*\bin\psql.exe" | Select-Object -First 1).FullName
+ $psql = "C:\pgsql-ci\bin\psql.exe"
$env:PGPASSWORD = 'password'
$serverVersion = [int][math]::Floor([int](& $psql -h localhost -U postgres -d postgres -Atc "show server_version_num") / 10000)
- if ($serverVersion -le 0) { throw "could not read the server version" }
+ if ($serverVersion -ne ${{env.POSTGRESQL_SERVER_MAJOR}}) { throw "expected a PostgreSQL ${{env.POSTGRESQL_SERVER_MAJOR}} server, found $serverVersion" }
Write-Output "PostgreSQL server major version $serverVersion"
if ('${{matrix.variant}}' -eq 'mimalloc') {
winbuild\regress.ps1 -DsnInfo "SERVER=localhost|DATABASE=contrib_regression|PORT=5432|UID=postgres|PWD=password" -ServerVersion $serverVersion -ExpectMimalloc
@@ -679,13 +688,19 @@ jobs:
target: c:\OTHERBIN
filename: postgresql_install.exe
- name: Install and start PostgreSQL server
- shell: cmd
+ shell: powershell
run: |
- echo on
- C:\OTHERBIN\postgresql_install.exe --mode unattended --unattendedmodeui none --superpassword password --enable-components server
- sc config "postgresql-x64-17" start= auto
- sc start "postgresql-x64-17"
- ping -n 6 127.0.0.1 >nul
+ # Some runner images ship a PostgreSQL of their own (windows-latest has
+ # 17.x as a disabled postgresql-x64-17 service). The EDB installer
+ # would upgrade that installation in place and keep its data directory
+ # and password, so keep it stopped, hide it from the installer and
+ # install the test server as a separate instance.
+ Get-Service postgresql* -ErrorAction SilentlyContinue | ForEach-Object { Stop-Service $_.Name -Force; Set-Service $_.Name -StartupType Disabled }
+ Remove-Item "HKLM:\SOFTWARE\PostgreSQL\Installations\postgresql-x64-*" -Recurse -ErrorAction SilentlyContinue
+ Remove-Item "HKLM:\SOFTWARE\PostgreSQL\Services\postgresql-x64-*" -Recurse -ErrorAction SilentlyContinue
+ $installer = Start-Process C:\OTHERBIN\postgresql_install.exe -Wait -PassThru -ArgumentList '--mode unattended --unattendedmodeui none --superpassword password --enable-components server --prefix C:\pgsql-ci --datadir C:\pgsql-ci\data --servicename postgresql-ci --serverport 5432'
+ if ($installer.ExitCode -ne 0) { Get-Content "$env:TEMP\install-postgresql.log" -Tail 40; throw "PostgreSQL installer exited with $($installer.ExitCode)" }
+ Get-Service postgresql* | Format-Table -AutoSize Name, Status, StartType | Out-String -Width 200
# Put the arm64 libpq (and its OpenSSL DLLs) ahead of the emulated x64
# server's bin so the arm64 driver loads the matching arm64 libpq at runtime.
@@ -730,10 +745,10 @@ jobs:
working-directory: psqlodbc
run: |
# Compare against test/expected/v<major> where the server has one.
- $psql = (Get-ChildItem "C:\Program Files\PostgreSQL\*\bin\psql.exe" | Select-Object -First 1).FullName
+ $psql = "C:\pgsql-ci\bin\psql.exe"
$env:PGPASSWORD = 'password'
$serverVersion = [int][math]::Floor([int](& $psql -h localhost -U postgres -d postgres -Atc "show server_version_num") / 10000)
- if ($serverVersion -le 0) { throw "could not read the server version" }
+ if ($serverVersion -ne ${{env.POSTGRESQL_SERVER_MAJOR}}) { throw "expected a PostgreSQL ${{env.POSTGRESQL_SERVER_MAJOR}} server, found $serverVersion" }
Write-Output "PostgreSQL server major version $serverVersion"
if ('${{matrix.variant}}' -eq 'mimalloc') {
winbuild\regress.ps1 -Platform ARM64 -DsnInfo "SERVER=localhost|DATABASE=contrib_regression|PORT=5432|UID=postgres|PWD=password" -ServerVersion $serverVersion -ExpectMimalloc
diff --git a/Changelog.md b/Changelog.md
index be981404..1fd190d3 100644
--- a/Changelog.md
+++ b/Changelog.md
@@ -2,6 +2,46 @@
Release notes for psqlODBC, converted from docs/release.html and docs/release-7.3.html.
+## Unreleased
+
+Behavior changes:
+
+- A COMMIT that fails is reported as an error. Before, a COMMIT rejected by a deferred constraint, or answered with `ROLLBACK` because the transaction had already failed, could be reported as success and the work was lost without a diagnostic. SQLEndTran, SQLSetConnectAttr with `SQL_ATTR_AUTOCOMMIT` or `SQL_ATTR_TXN_ISOLATION` (both commit the open transaction), SQLSetPos and SQLBulkOperations, and statements whose implicit commit fails now return `SQL_ERROR`. With `UseDeclareFetch=1` in autocommit mode, a fetch that reaches the end of the result and whose commit fails returns `SQL_ERROR` instead of `SQL_NO_DATA`.
+- SQLEndTran with `SQL_COMMIT`, and switching to `SQL_AUTOCOMMIT_ON`, fail with `08S01` on a connection the driver has found to be lost, even when no transaction was open. Before, they returned `SQL_SUCCESS` although the server had rolled the transaction back. `SQL_ROLLBACK` still succeeds.
+- `SQL_ATTR_QUERY_TIMEOUT` stays in effect after a rollback. The driver sends `SET statement_timeout` only when the value changes, and a rollback undid the server's setting while the driver still took it as set, so the timeout silently stopped working. The timeout now also applies to the UPDATE, DELETE and INSERT statements that SQLSetPos and SQLBulkOperations run, which ran without a timeout and left the session's timeout at 0. A query that ran past its timeout without being cancelled before can now be cancelled with `57014`.
+- In autocommit mode, reading a large object runs in a transaction of the driver's own. When opening the object fails, the driver now rolls that transaction back, where later queries on the connection failed with `25P02`. When the application reads only part of an object and then closes or frees the statement, the driver now commits the transaction; before, it stayed open and later work on the connection was lost at disconnect.
+- With statement-level rollback (`Protocol=7.4-2`), a positioned UPDATE or DELETE on a partitioned or inherited table is counted as a write. Before, the read-only lookup that precedes it made the driver skip the next SAVEPOINT, so a failure in the next statement rolled back the whole transaction instead of that statement.
+- With statement-level rollback (`Protocol=7.4-2`) inside a transaction, a failing statement or call rolls back only itself in two cases where it rolled back the whole transaction without telling the application: when the call just before it only read, such as a catalog function, a fetch on a keyset-driven cursor or a FETCH with `UseDeclareFetch=1`, and when a catalog function (SQLTables, SQLColumns, SQLSpecialColumns, SQLStatistics, SQLPrimaryKeys) or a SQLSetPos or SQLBulkOperations write itself fails. The driver now sets its SAVEPOINT in front of these as in front of any other statement. That sends one more round trip for each call that follows a read-only call, and for each such catalog call or positioned write, inside a transaction. In autocommit mode, for the first statement of a transaction, and with `Protocol=7.4-1` or `7.4-0`, the behaviour is unchanged.
+- With `FetchRefcursors=1`, a COMMIT or ROLLBACK now clears the cursors of every refcursor result, not only the first. Before, closing the statement in the next transaction sent a CLOSE for a cursor the server had already closed, which aborted that transaction.
+- Positioned operations on a table that has inheritance children or partitions look a row up by both `ctid` and `tableoid`. Before, a positioned refresh, SQLSetPos `SQL_DELETE` and the existence check matched rows of the children at the same `ctid`, and a positioned delete on a parent row could also delete a child's row. A row whose `tableoid` names a relation outside the cursor's table and its descendants is no longer updated, deleted or refreshed; the operation fails. With `UseDeclareFetch=1`, SQLBulkOperations by bookmark acts on the bookmarked row. Before, it could act on a neighbouring row after an earlier update through the cursor.
+- A converted statement may be at most 1 GB, the largest query the server accepts. ODBC escapes nested inside each other, such as `{fn insert(...)}`, can double the text at each level; such a statement now fails instead of allocating without bound.
+- The driver names its server-side objects (prepared statements, cursors, keyset queries and its savepoint) from a counter kept per connection. Before, the names contained memory addresses of the driver. Names such as `_PLAN0x...` and `SQL_CUR0x...` seen in `pg_prepared_statements`, `pg_cursors` or the server log change form, and the driver's savepoint always has the same name.
+- When the server does not report `standard_conforming_strings`, as servers before 8.1 and some proxies do not, the driver doubles backslashes in parameter values it puts into the statement text. Before, it left them as they were, and a server that reads backslash escapes could end the literal early.
+- SQLGetData with `SQL_C_BINARY` on an `int4`, `uuid` or `int2vector` column returns `SQL_NO_DATA` once the value has been read, as for other columns. Before, every further call returned the value again.
+- SQLColAttribute with `SQL_DESC_TYPE_NAME` or `SQL_DESC_LOCAL_TYPE_NAME` returns `interval` for a column of plain `interval` type. Before, it returned `SQL_SUCCESS` with length 0 and left the buffer as it was.
+- In `SELECT @@IDENTITY` rewriting, the character that follows `@@identity` is kept. Before, `select @@identity;select ...` lost its `;` and `select @@identity from t` lost the blank.
+- A column-wise parameter array bound with `SQL_C_DEFAULT` sends each row's value. Before, the driver stepped through the array by `BufferLength`, which ODBC ignores for fixed-length types, so it sent the first row's value for every row or read past the array.
+- After a parameter-array execution is given up part-way, for example by SQLCancel or a rejected SQLPutData during data at execution, the next execution on the statement no longer sends the abandoned batch's rows ahead of its own statement.
+- When SQLPutData or SQLParamData fails, or SQLCancel is called, during a SQLSetPos or SQLBulkOperations data-at-execution sequence, the pending operation is cancelled and autocommit is restored. SQLPutData accepts a zero-length piece after the first one, as ODBC allows; it was rejected with "bad cbValue".
+- SQLCancel sends the server a cancel request only while the statement, or the inner statement the driver executes on its behalf, is executing a query. Before, it read the inner statement without the statement lock, while another thread could be freeing it.
+- On Windows, a `SQL_C_CHAR` parameter that is not valid in the application's ANSI code page fails with `HY000` "Could not convert the current data ... to wide chars", as on other platforms. Before, it was sent as an empty string with a `01S01` warning.
+- A character or binary parameter whose length indicator is negative and is not `SQL_NTS`, `SQL_NULL_DATA`, `SQL_DEFAULT_PARAM` or a data-at-execution value, such as `SQL_NO_TOTAL`, is refused with an error instead of being read as a huge length.
+- SQLGetInfo, SQLGetConnectAttr, SQLDriverConnect and SQLColAttributeW return `HY090` for a negative buffer length, and SQLDriverConnect returns `HY009` for a NULL input connection string. Lengths that SQLDescribeCol, SQLColAttribute and their Unicode forms report are capped at 32767 instead of wrapping negative, and when a Unicode function cannot convert a string it returns an empty string with length 0.
+- SQLGetDescField on an IRD writes the fields that ODBC defines as `SQLSMALLINT`, such as `SQL_DESC_TYPE`, `SQL_DESC_NULLABLE` and `SQL_DESC_PRECISION`, as 2 bytes. Before, it wrote 4 bytes, past the end of a correctly sized variable. An application that reads such a field into a 4-byte variable must now initialise it first. No field is written when the field identifier is invalid.
+- SQLGetDescRec returns an empty name for a record of an ARD or APD, and returns the name's length whenever it succeeds, including when the name is truncated. SQLSetDescField with `SQL_DESC_NAME` on an IPD copies at most `BufferLength` bytes of a name that is not null-terminated.
+- SQLSetStmtAttr refuses an IRD, an IPD or another statement's implicit descriptor as `SQL_ATTR_APP_ROW_DESC` or `SQL_ATTR_APP_PARAM_DESC`. SQLCopyDesc gives the target descriptor the type of the source, and refuses to copy an IRD or IPD into a descriptor that a statement uses as its ARD or APD.
+- A `CX` connection attribute without a valid flag word, such as `CX=` or `CX=1c`, or with non-hex flag digits, leaves the options as they were. Before, an empty or short value set about twenty options from uninitialised memory, and non-hex digits turned every flag off.
+- Every libpq keyword given in `pqopt` is passed to libpq. Before, the driver kept room for 30 keywords in all, its own included, and dropped the rest without an error, so a long `pqopt` could lose settings such as `target_session_attrs`, `gssencmode` or `require_auth`. A connection that relied on such a keyword being ignored now gets it applied.
+- On Linux and other non-Windows platforms, connecting no longer changes the process locale. The driver used to call `setlocale(LC_CTYPE, "")` on every connect, replacing the application's `LC_CTYPE`. It now takes the client encoding of the ANSI driver from the application's current locale and, if that names no code set (the `C` locale of an application that never set one), from `LC_ALL`, `LC_CTYPE` or `LANG`. An application that sets a locale other than the one in its environment now gets the encoding of the locale it set.
+- On unixODBC builds, a failed SQLExtendedFetch sets the row count to 0. Before, the row count was left holding a stale or meaningless value.
+- The debug logs (MyLog and CommLog) no longer show passwords or other secrets in any form the connection string or `pqopt` syntax allows: braced, quoted, escaped, or under libpq's `oauth_client_secret` and other options libpq marks as secret. The strings that the Unicode conversion routines handle are logged by length only.
+- SQLSetConnectAttr(`SQL_ATTR_ENLIST_IN_DTC`) on a connection with an open local transaction fails with an error when the driver cannot roll that transaction back. Before, the failure was ignored and the enlistment went ahead; switching the connection to the distributed transaction then committed whatever was still open, and could not report it when that commit failed too.
+- ConfigDSN and SQLConfigDataSource skip an attribute whose keyword is 33 bytes or longer, or whose value is `MAXPGPATH` bytes or longer, and apply the attributes after it. Before, such a value could be applied to the previous keyword or read past its buffer.
+- On 64-bit platforms SQLGetDescField writes a whole `SQLLEN` (8 bytes) for `SQL_DESC_OCTET_LENGTH` on every descriptor type, and for `SQL_DESC_LENGTH` and `SQL_DESC_DISPLAY_SIZE` on an IRD, as ODBC defines these fields. The driver used to write only 4 bytes, so the rest of the application's variable kept whatever it held and a length could read back as huge or negative. An application that passes a 4-byte `SQLINTEGER` for these fields must pass a `SQLLEN`. SQLGetDescRec, whose `Length` argument was always a `SQLLEN`, now fills all of it.
+- SQLGetDiagRec and SQLGetDiagField on a statement or connection handle now take that handle's lock, as the other entry points do, so they wait while another thread is in a call on the same handle instead of reading its errors as they change. On POSIX the statement lock is now recursive, like the connection lock. SQLCancel still takes no lock.
+- SQLGetDiagRecW and SQLGetDiagFieldW no longer lose a piece of a long error message when the piece is cut inside a multibyte UTF-8 character. The partial character at either end of the piece is dropped instead, so a character that straddles two pieces is missing from both, where before the whole piece came back empty (SQLGetDiagFieldW) or as `Error: SqlState=...` (SQLGetDiagRecW).
+- SQLGetDescField, SQLSetDescField, SQLGetDescRec, SQLSetDescRec, SQLCopyDesc and SQLFreeHandle(SQL_HANDLE_DESC) on a statement's implicit descriptors (the ARD, APD, IRD and IPD returned by SQLGetStmtAttr) now take that statement's lock, so they wait while another thread is in a call on the statement; SQLCopyDesc between two statements' descriptors takes both locks. Explicit descriptors from SQLAllocHandle(SQL_HANDLE_DESC) are not locked: an application must not change one while a statement it is attached to is in a call on another thread.
+
## 18.00.0007
This release fixes the following vulnerabilities. All releases before 18.00.0007 are affected unless an entry gives a narrower range.
diff --git a/bind.c b/bind.c
index 978ce9df..94c3690b 100644
--- a/bind.c
+++ b/bind.c
@@ -230,6 +230,19 @@ MYLOG(DETAIL_LOG_LEVEL, "Bind column 0 is type %d not of type SQL_C_BOOKMARK\n",
ret = SQL_ERROR;
goto cleanup;
}
+ /*
+ * A SQL_C_VARBOOKMARK buffer length is also the row stride of
+ * column-wise binding, so a negative one would write rows
+ * before the buffer.
+ */
+ if (SQL_C_VARBOOKMARK == fCType && cbValueMax < 0)
+ {
+ SC_set_error(stmt, STMT_INVALID_BUFFER_LENGTH,
+ "Invalid buffer length for the bookmark column",
+ func);
+ ret = SQL_ERROR;
+ goto cleanup;
+ }
bookmark = ARD_AllocBookmark(opts);
if (!bookmark)
@@ -524,6 +537,16 @@ create_empty_bindings(int num_columns)
new_bindings[i].buffer = NULL;
new_bindings[i].used =
new_bindings[i].indicator = NULL;
+ /*
+ * SQL_C_DEFAULT is the initial SQL_DESC_TYPE of an ARD record.
+ * Give every field a value here: they are read back by
+ * SQLGetDescField/SQLGetDescRec and used as the conversion
+ * target by SQLGetData(SQL_ARD_TYPE) and SQLFetch.
+ */
+ new_bindings[i].returntype = SQL_C_DEFAULT;
+ new_bindings[i].precision = 0;
+ new_bindings[i].scale = 0;
+ new_bindings[i].dummy_data = 0;
}
return new_bindings;
diff --git a/connection.c b/connection.c
index 7c409874..f9d5a9ce 100644
--- a/connection.c
+++ b/connection.c
@@ -370,6 +370,15 @@ CC_Destructor(ConnectionClass *self)
if (self->status == CONN_EXECUTING)
return 0;
+#ifdef _HANDLE_ENLIST_IN_DTC_
+ /*
+ * SQLDisconnect detaches the connection from its MSDTC enlistment. Make
+ * sure that no enlistment keeps a pointer to the connection freed below.
+ */
+ if (NULL != self->asdum)
+ CALL_DtcOnDisconnect(self);
+#endif /* _HANDLE_ENLIST_IN_DTC_ */
+
CC_cleanup(self, FALSE); /* cleanup socket and statements */
MYLOG(0, "after CC_Cleanup\n");
@@ -416,9 +425,13 @@ CC_cursor_count(ConnectionClass *self)
CONNLOCK_ACQUIRE(self);
for (i = 0; i < self->num_stmts; i++)
{
- stmt = self->stmts[i];
- if (stmt && (res = SC_get_Result(stmt)) && QR_get_cursor(res))
- count++;
+ if (stmt = self->stmts[i], NULL == stmt)
+ continue;
+ for (res = SC_get_Result(stmt); res; res = QR_nextr(res))
+ {
+ if (QR_get_cursor(res))
+ count++;
+ }
}
CONNLOCK_RELEASE(self);
@@ -497,6 +510,17 @@ CC_commit(ConnectionClass *self)
QResultClass *res = CC_send_query(self, cmtcmd, NULL, 0, NULL);
MYLOG(0, " sending COMMIT!\n");
ret = QR_command_maybe_successful(res);
+ /*
+ * COMMIT of a transaction that had already failed succeeds
+ * with the tag ROLLBACK: the work is gone all the same.
+ */
+ if (ret && QR_command_rolled_back(res))
+ {
+ CC_set_error(self, CONN_EXEC_ERROR, "The transaction had failed and was rolled back instead of committed", __FUNCTION__);
+ ret = FALSE;
+ }
+ else if (!ret && 0 == CC_get_errornumber(self))
+ CC_set_error(self, CONN_EXEC_ERROR, "Could not commit the transaction", __FUNCTION__);
QR_Destructor(res);
}
}
@@ -523,24 +547,29 @@ CC_abort(ConnectionClass *self)
return ret;
}
-/* This is called by SQLSetConnectOption etc also */
+/*
+ * This is called by SQLSetConnectOption etc also.
+ * Returns FALSE if the open transaction could not be committed; the mode
+ * is changed all the same, as the transaction is gone either way.
+ */
char
CC_set_autocommit(ConnectionClass *self, BOOL on)
{
BOOL currsts = CC_is_in_autocommit(self);
+ char ret = TRUE;
if ((on && currsts) ||
(!on && !currsts))
- return on;
+ return ret;
MYLOG(0, " %d->%d\n", currsts, on);
if (CC_is_in_trans(self))
- CC_commit(self);
+ ret = CC_commit(self);
if (on)
self->transact_status |= CONN_IN_AUTOCOMMIT;
else
self->transact_status &= ~CONN_IN_AUTOCOMMIT;
- return on;
+ return ret;
}
/* Clear cached table info */
@@ -699,11 +728,22 @@ CC_cleanup(ConnectionClass *self, BOOL keepCommunication)
/* Cancel an ongoing transaction */
/* We are always in the middle of a transaction, */
/* even if we are in auto commit. */
- if (self->pqconn)
{
- QLOG(0, "PQfinish: %p\n", self->pqconn);
- PQfinish(self->pqconn);
+ PGconn *pqconn;
+
+ /*
+ * CC_send_cancel_request() reads pqconn under CONNLOCK from another
+ * thread, so it is cleared under that lock before it is finished.
+ */
+ CONNLOCK_ACQUIRE(self);
+ pqconn = self->pqconn;
self->pqconn = NULL;
+ CONNLOCK_RELEASE(self);
+ if (pqconn)
+ {
+ QLOG(0, "PQfinish: %p\n", pqconn);
+ PQfinish(pqconn);
+ }
}
MYLOG(0, "after PQfinish\n");
@@ -757,6 +797,9 @@ CC_cleanup(ConnectionClass *self, BOOL keepCommunication)
self->status = CONN_NOT_CONNECTED;
self->transact_status = CONN_IN_AUTOCOMMIT;
self->unnamed_prepared_stmt = NULL;
+ /* a new session starts without the timeout the old one had */
+ self->stmt_timeout_in_effect = 0;
+ self->stmt_timeout_set_in_trans = 0;
}
if (!keepCommunication)
{
@@ -1402,8 +1445,16 @@ char CC_get_escape(const ConnectionClass *self)
}
if (scf == NULL)
{
- /* we're connected to a pre-8.1 server, and E'' is not supported */
- return '\0';
+ /*
+ * A pre-8.2 server, which is before the setting was reported, or a
+ * server or proxy that doesn't report it. Either may treat a
+ * backslash in a literal as an escape, so double it: a value the
+ * driver leaves undoubled can end the literal and have the rest of
+ * it read as SQL. A doubled backslash is right whatever the
+ * setting is as long as the literal carries the E prefix, which
+ * CC_can_write_literal_extension() decides.
+ */
+ return ESCAPE_IN_LITERAL;
}
if (strcmp(scf, "on") != 0)
return ESCAPE_IN_LITERAL;
@@ -1411,6 +1462,43 @@ char CC_get_escape(const ConnectionClass *self)
return '\0';
}
+/*
+ * Return TRUE when a literal this connection sends may carry the E prefix,
+ * which keeps a doubled backslash in it standing for one backslash
+ * whatever standard_conforming_strings is set to.
+ *
+ * The server has taken E'' since 8.1. A server that reports no version at
+ * all leaves pg_version_major 0, and that is not one of those older
+ * servers: every real one reports its version, while something that
+ * reports neither the version nor standard_conforming_strings is a proxy
+ * in front of a server new enough to have both. Writing the prefix there
+ * is what keeps the doubled backslash from reaching the table as two.
+ */
+BOOL
+CC_can_write_literal_extension(const ConnectionClass *self)
+{
+ return PG_VERSION_GE(self, 8.1) || 0 == self->pg_version_major;
+}
+
+/*
+ * The prefix a literal needs when the driver has doubled the backslashes
+ * inside it: "E", under which a doubled backslash stands for one backslash
+ * whatever standard_conforming_strings is set to. Empty when the driver
+ * leaves backslashes alone, and when the server cannot take the prefix.
+ *
+ * Every literal built from identifierEscape() or simpleCatalogEscape()
+ * carries this, since those double the backslash whenever
+ * CC_get_escape() asks for it. gen_opestr() writes the prefix into the
+ * catalog operators for the same reason.
+ */
+const char *
+CC_literal_prefix(const ConnectionClass *self)
+{
+ if (0 != CC_get_escape(self) && CC_can_write_literal_extension(self))
+ return "E";
+ return NULL_STRING;
+}
+
int CC_get_max_idlen(ConnectionClass *self)
{
@@ -1535,10 +1623,14 @@ CC_get_error(ConnectionClass *self, int *number, char **message)
CONNLOCK_ACQUIRE(self);
+ /*
+ * Hand back a copy: another thread may replace and free the message
+ * as soon as the lock is released. The caller frees it.
+ */
if (CC_get_errornumber(self))
{
*number = CC_get_errornumber(self);
- *message = CC_get_errormsg(self);
+ *message = CC_get_errormsg(self) ? strdup(CC_get_errormsg(self)) : NULL;
}
rv = (CC_get_errornumber(self) != 0);
@@ -1563,17 +1655,18 @@ static int CC_close_eof_cursors(ConnectionClass *self)
{
if (stmt = self->stmts[i], NULL == stmt)
continue;
- if (res = SC_get_Result(stmt), NULL == res)
- continue;
- if (NULL != QR_get_cursor(res) &&
- QR_is_withhold(res) &&
- QR_once_reached_eof(res))
+ for (res = SC_get_Result(stmt); res; res = QR_nextr(res))
{
- if (QR_get_num_cached_tuples(res) >= QR_get_num_total_tuples(res) ||
- SQL_CURSOR_FORWARD_ONLY == stmt->options.cursor_type)
+ if (NULL != QR_get_cursor(res) &&
+ QR_is_withhold(res) &&
+ QR_once_reached_eof(res))
{
- QR_close(res);
- ccount++;
+ if (QR_get_num_cached_tuples(res) >= QR_get_num_total_tuples(res) ||
+ SQL_CURSOR_FORWARD_ONLY == stmt->options.cursor_type)
+ {
+ QR_close(res);
+ ccount++;
+ }
}
}
}
@@ -1617,10 +1710,17 @@ static void CC_clear_cursors(ConnectionClass *self, BOOL on_abort)
CONNLOCK_ACQUIRE(self);
for (i = 0; i < self->num_stmts; i++)
{
- stmt = self->stmts[i];
- if (stmt && (res = SC_get_Result(stmt)) &&
- (NULL != QR_get_cursor(res)))
+ if (stmt = self->stmts[i], NULL == stmt)
+ continue;
+ /*
+ * Every result in the chain may own a cursor of its own
+ * (e.g. one per refcursor with FetchRefcursors), so walk
+ * the whole chain, not just the first result.
+ */
+ for (res = SC_get_Result(stmt); res; res = QR_nextr(res))
{
+ if (NULL == QR_get_cursor(res))
+ continue;
/*
* non-holdable cursors are automatically closed
* at commit time.
@@ -1675,12 +1775,14 @@ static void CC_mark_cursors_doubtful(ConnectionClass *self)
CONNLOCK_ACQUIRE(self);
for (i = 0; i < self->num_stmts; i++)
{
- stmt = self->stmts[i];
- if (NULL != stmt &&
- NULL != (res = SC_get_Result(stmt)) &&
- NULL != QR_get_cursor(res) &&
- !QR_is_permanent(res))
- QR_set_survival_check(res);
+ if (stmt = self->stmts[i], NULL == stmt)
+ continue;
+ for (res = SC_get_Result(stmt); res; res = QR_nextr(res))
+ {
+ if (NULL != QR_get_cursor(res) &&
+ !QR_is_permanent(res))
+ QR_set_survival_check(res);
+ }
}
CONNLOCK_RELEASE(self);
}
@@ -1696,6 +1798,20 @@ void CC_on_commit(ConnectionClass *conn)
CC_set_no_trans(conn);
CC_set_no_manual_trans(conn);
}
+ /*
+ * A SET statement_timeout issued inside the transaction is undone by
+ * a ROLLBACK and kept by a COMMIT, and this is reached for both:
+ * every clean transition to idle comes here, including the one
+ * CC_abort() relies on. There is no way to tell them apart from
+ * here, so the server-side value must be treated as unknown. Any
+ * guess can disagree with the server, and SC_execute() skips the SET
+ * a statement needs whenever its timeout equals the wrong guess.
+ */
+ if (conn->stmt_timeout_set_in_trans)
+ {
+ conn->stmt_timeout_in_effect = STMT_TIMEOUT_UNKNOWN;
+ conn->stmt_timeout_set_in_trans = 0;
+ }
CC_svp_init(conn);
CC_start_stmt(conn);
CC_clear_cursors(conn, FALSE);
@@ -1727,6 +1843,12 @@ MYLOG(0, "entering opt=%x\n", opt);
CC_set_no_trans(conn);
CC_set_no_manual_trans(conn);
set_no_trans = TRUE;
+ /* the ROLLBACK also undid SET statement_timeout */
+ if (conn->stmt_timeout_set_in_trans)
+ {
+ conn->stmt_timeout_in_effect = conn->stmt_timeout_before_trans;
+ conn->stmt_timeout_set_in_trans = 0;
+ }
}
}
CC_svp_init(conn);
@@ -1737,11 +1859,17 @@ MYLOG(0, "entering opt=%x\n", opt);
conn->status = CONN_DOWN;
if (conn->pqconn)
{
+ /*
+ * Cleared before it is finished, under CONNLOCK, which
+ * CC_send_cancel_request() holds while it reads pqconn.
+ */
+ PGconn *pqconn = conn->pqconn;
+
+ conn->pqconn = NULL;
CONNLOCK_RELEASE(conn);
- QLOG(0, "PQfinish: %p\n", conn->pqconn);
- PQfinish(conn->pqconn);
+ QLOG(0, "PQfinish: %p\n", pqconn);
+ PQfinish(pqconn);
CONNLOCK_ACQUIRE(conn);
- conn->pqconn = NULL;
}
}
else if (set_no_trans)
@@ -1764,6 +1892,13 @@ void CC_on_abort_partial(ConnectionClass *conn)
{
MYLOG(0, "entering\n");
CONNLOCK_ACQUIRE(conn);
+ /*
+ * ROLLBACK TO SAVEPOINT undoes SET statement_timeout when the SET
+ * came after the savepoint. We don't know, so have SC_execute()
+ * issue it again.
+ */
+ if (conn->stmt_timeout_set_in_trans)
+ conn->stmt_timeout_in_effect = STMT_TIMEOUT_UNKNOWN;
ProcessRollback(conn, TRUE, TRUE);
CC_discard_marked_objects(conn);
CONNLOCK_RELEASE(conn);
@@ -1776,7 +1911,7 @@ is_setting_search_path(const char *query)
if (strnicmp(q, "set", 3) != 0)
return FALSE;
q += 3;
- while (isspace(*q)) q++;
+ while (isspace((UCHAR) *q)) q++;
for (; *q;)
{
if (IS_NOT_SPACE(*q))
@@ -2118,6 +2253,19 @@ CC_send_query_append(ConnectionClass *self, const char *query, QueryInfo *qi, UD
goto cleanup;
}
}
+ else
+ {
+ /*
+ * The rollback point of this call is already set, but
+ * still record what kind of query follows it. A call
+ * that reads first and writes afterwards (e.g. a
+ * positioned DELETE/UPDATE on a partitioned table looks
+ * up the child table's name before writing) must not be
+ * remembered as read-only, or the next call skips its
+ * SAVEPOINT and a failure there rolls the write back.
+ */
+ self->opt_in_progress &= svpopt;
+ }
}
}
@@ -2748,6 +2896,17 @@ CC_send_function(ConnectionClass *self, const char *fn_name, void *result_buf, I
QLOG(0, "\tgot result with length: %d\n", *actual_result_len);
+ /*
+ * An integer result must be present. PQgetlength() is 0 for a NULL
+ * or empty reply, which would otherwise skip the copy below and leave
+ * the caller's result_buf unset while reporting success.
+ */
+ if (result_is_int && *actual_result_len <= 0)
+ {
+ CC_set_errormsg(self, "null result from large_object function");
+ goto cleanup;
+ }
+
if (*actual_result_len > 0)
{
char *value = PQgetvalue(pgres, 0, 0);
@@ -2993,7 +3152,8 @@ int CC_mark_a_object_to_discard(ConnectionClass *conn, int type, const char *pla
int CC_discard_marked_objects(ConnectionClass *conn)
{
QResultClass *res;
- char *pname, cmd[64];
+ char *pname, *cmd;
+ size_t cmdlen;
if (conn->num_discardp <= 0)
return 0;
@@ -3006,12 +3166,21 @@ int CC_discard_marked_objects(ConnectionClass *conn)
* send and free the same entry again.
*/
pname = conn->discardp[--conn->num_discardp];
- if ('s' == pname[0])
- SPRINTF_FIXED(cmd, "DEALLOCATE \"%s\"", pname + 1);
- else
- SPRINTF_FIXED(cmd, "CLOSE \"%s\"", pname + 1);
+ /* a refcursor's name comes from the server and has no length limit */
+ cmdlen = strlen(pname + 1) + sizeof("DEALLOCATE \"\"");
+ cmd = malloc(cmdlen);
+ if (cmd)
+ {
+ if ('s' == pname[0])
+ snprintf(cmd, cmdlen, "DEALLOCATE \"%s\"", pname + 1);
+ else
+ snprintf(cmd, cmdlen, "CLOSE \"%s\"", pname + 1);
+ }
free(pname);
+ if (!cmd)
+ continue;
res = CC_send_query(conn, cmd, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN | READ_ONLY_QUERY, NULL);
+ free(cmd);
QR_Destructor(res);
}
@@ -3063,7 +3232,8 @@ LIBPQ_update_transaction_status(ConnectionClass *self)
}
}
-#define PROTOCOL3_OPTS_MAX 30
+/* the most keywords LIBPQ_connect() sets itself, before the pqopt ones */
+#define PROTOCOL3_FIXED_OPTS 16
/*
* Return TRUE if the value of the libpq keyword is a secret. options is
@@ -3122,7 +3292,8 @@ LIBPQ_connect(ConnectionClass *self)
void *pqconn = NULL;
int pqret;
int pversion;
- const char *opts[PROTOCOL3_OPTS_MAX], *vals[PROTOCOL3_OPTS_MAX];
+ const char **opts = NULL, **vals = NULL;
+ size_t nopts;
PQconninfoOption *conninfoOption = NULL, *pqopt;
int cnt;
char login_timeout_str[20];
@@ -3148,7 +3319,23 @@ LIBPQ_connect(ConnectionClass *self)
}
if (pqopt_str[0] != '\0')
log_pqopt_options(conninfoOption);
- /* Build arrays of keywords & values, for PQconnectDBParams */
+ /*
+ * Build arrays of keywords & values, for PQconnectDBParams. Size them
+ * for every keyword pqopt sets, so that none of them is dropped.
+ */
+ nopts = PROTOCOL3_FIXED_OPTS + 1;
+ for (pqopt = conninfoOption; pqopt->keyword != NULL; pqopt++)
+ {
+ if (pqopt->val != NULL)
+ nopts++;
+ }
+ opts = (const char **) malloc(nopts * sizeof(*opts));
+ vals = (const char **) malloc(nopts * sizeof(*vals));
+ if (NULL == opts || NULL == vals)
+ {
+ CC_set_error(self, CONN_NO_MEMORY_ERROR, "Could not allocate memory for the connection parameters", func);
+ goto cleanup;
+ }
cnt = 0;
if (ci->server[0])
{
@@ -3225,14 +3412,15 @@ LIBPQ_connect(ConnectionClass *self)
{
char emsg[100];
+ /* the same value again: already in the arrays */
if (vals[j] != NULL && strcmp(vals[j], val) == 0)
- continue;
+ break;
SPRINTF_FIXED(emsg, "%s parameter in pqopt option conflicts with other ordinary option", keyword);
CC_set_error(self, CONN_OPENDB_ERROR, emsg, func);
goto cleanup;
}
}
- if (j >= cnt && cnt < PROTOCOL3_OPTS_MAX - 1)
+ if (j >= cnt && (size_t) cnt < nopts - 1)
{
opts[cnt] = keyword; vals[cnt++] = val;
}
@@ -3324,7 +3512,9 @@ MYLOG(DETAIL_LOG_LEVEL, "status=%d\n", pqret);
cleanup:
if (errmsg != NULL)
- free(errmsg);
+ PQfreemem(errmsg); /* libpq's allocation, not the driver's */
+ free(opts);
+ free(vals);
PQconninfoFree(conninfoOption);
if (ret != 1)
{
@@ -3341,17 +3531,25 @@ cleanup:
}
int
-CC_send_cancel_request(const ConnectionClass *conn)
+CC_send_cancel_request(ConnectionClass *conn)
{
int ret = 0;
char errbuf[256];
- void *cancel;
+ void *cancel = NULL;
- /* Check we have an open connection */
- if (!conn || !conn->pqconn)
+ if (!conn)
return FALSE;
-
- cancel = PQgetCancel(conn->pqconn);
+ /*
+ * SQLCancel runs in another thread than the call it cancels, which may
+ * finish pqconn meanwhile. CC_on_abort() and CC_cleanup() clear pqconn
+ * under CONNLOCK before they finish it, so it is read under that lock.
+ * PQgetCancel() copies what the cancel request needs, so the request
+ * itself is sent without the lock.
+ */
+ CONNLOCK_ACQUIRE(conn);
+ if (conn->pqconn)
+ cancel = PQgetCancel(conn->pqconn);
+ CONNLOCK_RELEASE(conn);
if (!cancel)
return FALSE;
ret = PQcancel(cancel, errbuf, sizeof(errbuf));
diff --git a/connection.h b/connection.h
index b9d86ba4..46e88679 100644
--- a/connection.h
+++ b/connection.h
@@ -71,6 +71,7 @@ typedef enum
#define CONN_INVALID_INFO_TYPE 215
#define CONN_OPTION_NOT_FOR_THE_DRIVER 216
#define CONN_EXEC_ERROR 217
+#define CONN_INVALID_BUFFER_LENGTH 218
/* Conn_status defines */
#define CONN_IN_AUTOCOMMIT 1L
@@ -343,6 +344,9 @@ struct ConnectionClass_
pgNAME schemaIns;
pgNAME tableIns;
SQLULEN stmt_timeout_in_effect;
+ SQLULEN stmt_timeout_before_trans; /* what a ROLLBACK restores */
+ char stmt_timeout_set_in_trans; /* SET statement_timeout was
+ * issued in the current transaction */
UInt4 name_serial; /* last number handed out by CC_get_name_serial() */
#if defined(WIN_MULTITHREAD_SUPPORT)
CRITICAL_SECTION cs;
@@ -431,7 +435,7 @@ int CC_send_function(ConnectionClass *conn, const char *fn_name, void *result_b
char CC_send_settings(ConnectionClass *self, const char *set_query);
void CC_initialize_pg_version(ConnectionClass *conn);
void CC_log_error(const char *func, const char *desc, const ConnectionClass *self);
-int CC_send_cancel_request(const ConnectionClass *conn);
+int CC_send_cancel_request(ConnectionClass *conn);
void CC_on_commit(ConnectionClass *conn);
void CC_on_abort(ConnectionClass *conn, unsigned int opt);
void CC_on_abort_partial(ConnectionClass *conn);
@@ -444,6 +448,8 @@ void CC_abort_copy(ConnectionClass *self);
int CC_get_max_idlen(ConnectionClass *self);
char CC_get_escape(const ConnectionClass *self);
+BOOL CC_can_write_literal_extension(const ConnectionClass *self);
+const char *CC_literal_prefix(const ConnectionClass *self);
char * identifierEscape(const SQLCHAR *src, SQLLEN srclen, const ConnectionClass *conn, char *buf, size_t bufsize, BOOL double_quote);
/*
* A buffer that holds the identifierEscape() output of any name the
@@ -493,6 +499,8 @@ enum {
/* CC_on_abort options */
#define NO_TRANS 1L
#define CONN_DEAD (1L << 1) /* connection is no longer valid */
+/* the session's statement_timeout is unknown, SC_execute() must SET it */
+#define STMT_TIMEOUT_UNKNOWN ((SQLULEN) -1)
/*
* This is a libpq notice receiver callback, for handling incoming NOTICE
diff --git a/convert.c b/convert.c
index 1ed65718..de930a46 100644
--- a/convert.c
+++ b/convert.c
@@ -1457,7 +1457,7 @@ MYLOG(0, "null_cvt_date_string=%d\n", conn->connInfo.cvt_null_date_string);
case SQL_C_DEFAULT:
if (rgbValueBindRow && cbValueMax >= sizeof(DATE_STRUCT))
{
- pg_memset(rgbValueBindRow, 0, cbValueMax);
+ pg_memset(rgbValueBindRow, 0, sizeof(DATE_STRUCT));
if (pcbValueBindRow)
*pcbValueBindRow = sizeof(DATE_STRUCT);
}
@@ -1671,7 +1671,7 @@ MYLOG(DETAIL_LOG_LEVEL, "2stime fr=%d\n", std_time.fr);
while (IS_NOT_SPACE(*vp))
vp++;
/* and skip the space to the next token */
- while ((*vp != '\0') && (isspace(*vp)))
+ while ((*vp != '\0') && (isspace((UCHAR) *vp)))
vp++;
if (*vp == '\0')
break;
@@ -1684,6 +1684,9 @@ MYLOG(DETAIL_LOG_LEVEL, "2stime fr=%d\n", std_time.fr);
len = (nval + 1) * sizeof(short);
if (pcbValue)
*pcbValueBindRow = len;
+ /* no piecewise retrieval here: the column is done either way */
+ if (cbValueMax > 0 && stmt->current_col >= 0)
+ gdata->gdata[stmt->current_col].data_left = 0;
if (len <= cbValueMax)
return COPY_OK; /* dont go any further or the data will be
@@ -1833,6 +1836,8 @@ MYLOG(DETAIL_LOG_LEVEL, "2stime fr=%d\n", std_time.fr);
if (pre_convert)
neut_str = midtemp;
result = convert_text_field_to_sql_c(gdata, stmt->current_col, neut_str, field_type, fCType, rgbValueBindRow, cbValueMax, conn, &len);
+ if (COPY_GENERAL_ERROR == result)
+ SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for the field value", func);
}
else
{
@@ -2141,15 +2146,11 @@ MYLOG(DETAIL_LOG_LEVEL, "2stime fr=%d\n", std_time.fr);
UInt4 ival = ATOI32U(neut_str);
MYLOG(DETAIL_LOG_LEVEL, "SQL_C_VARBOOKMARK value=%d\n", ival);
- if (pcbValue)
- *pcbValueBindRow = sizeof(ival);
- if (cbValueMax >= sizeof(ival))
- {
- memcpy(rgbValueBindRow, &ival, sizeof(ival));
- return COPY_OK;
- }
+ len = sizeof(ival);
+ if (cbValueMax >= len)
+ memcpy(rgbValueBindRow, &ival, len);
else
- return COPY_RESULT_TRUNCATED;
+ result = COPY_RESULT_TRUNCATED;
}
else if (PG_TYPE_UUID == field_type)
{
@@ -2157,21 +2158,27 @@ MYLOG(DETAIL_LOG_LEVEL, "SQL_C_VARBOOKMARK value=%d\n", ival);
if (COPY_OK != rtn)
return rtn;
- if (pcbValue)
- *pcbValueBindRow = sizeof(g);
- if (cbValueMax >= sizeof(g))
- {
- memcpy(rgbValueBindRow, &g, sizeof(g));
- return COPY_OK;
- }
+ len = sizeof(g);
+ if (cbValueMax >= len)
+ memcpy(rgbValueBindRow, &g, len);
else
- return COPY_RESULT_TRUNCATED;
+ result = COPY_RESULT_TRUNCATED;
}
else
{
MYLOG(0, "couldn't convert the type %d to SQL_C_BINARY\n", field_type);
return COPY_UNSUPPORTED_TYPE;
}
+ /*
+ * These values are stored whole or not at all, so a
+ * SQLGetData() whose buffer was too small is done with
+ * the column as well (COPY_OK is handled below); otherwise
+ * every later call would return the value again and never
+ * SQL_NO_DATA. A call with cbValueMax == 0 just asks for
+ * the length, as in setup_getdataclass().
+ */
+ if (COPY_RESULT_TRUNCATED == result && cbValueMax > 0 && stmt->current_col >= 0)
+ gdata->gdata[stmt->current_col].data_left = 0;
break;
case SQL_C_GUID:
@@ -2362,6 +2369,8 @@ typedef struct _QueryBuild {
} QueryBuild;
#define INIT_MIN_ALLOC 4096
+/* the largest query message the server takes */
+#define MAX_CONVERTED_STATEMENT_SIZE ((size_t) 0x40000000)
/*
* convert_escape() recurses once for every {fn ...( )} escape nested in
* the argument list of another, with well over 1kB of stack per level.
@@ -2408,7 +2417,7 @@ QB_initialize(QueryBuild *qb, size_t size, StatementClass *stmt, ResolveParamMod
qb->flags |= FLGB_CONVERT_LF;
qb->ccsc = qb->conn->ccsc;
if (CC_get_escape(qb->conn) &&
- PG_VERSION_GE(qb->conn, 8.1))
+ CC_can_write_literal_extension(qb->conn))
qb->flags |= FLGB_LITERAL_EXTENSION;
if (PG_VERSION_GE(qb->conn, 9.0))
qb->flags |= FLGB_HEX_BIN_FORMAT;
@@ -2584,13 +2593,24 @@ static ssize_t
enlarge_query_statement(QueryBuild *qb, size_t newsize)
{
size_t newalsize = INIT_MIN_ALLOC;
+ char *newbuf = NULL;
CSTR func = "enlarge_statement";
- while (newalsize <= newsize)
- newalsize *= 2;
- if (!(qb->query_statement = realloc(qb->query_statement, newalsize)))
+ /*
+ * The server takes no query message over 1GB, and nested escapes such
+ * as {fn insert(...)} that use an argument twice double the converted
+ * text at every level, so a short statement could otherwise ask for
+ * any amount of memory.
+ */
+ if (newsize < MAX_CONVERTED_STATEMENT_SIZE)
{
- qb->str_alsize = 0;
+ while (newalsize <= newsize)
+ newalsize *= 2;
+ newbuf = realloc(qb->query_statement, newalsize);
+ }
+ if (NULL == newbuf)
+ {
+ /* qb->query_statement is still allocated, and freed with qb */
if (qb->stmt)
{
SC_set_error(qb->stmt, STMT_EXEC_ERROR, "Query buffer allocate error in copy_statement_with_parameters", func);
@@ -2602,6 +2622,7 @@ enlarge_query_statement(QueryBuild *qb, size_t newsize)
}
return 0;
}
+ qb->query_statement = newbuf;
qb->str_alsize = newalsize;
return newalsize;
}
@@ -3068,6 +3089,11 @@ MYLOG(DETAIL_LOG_LEVEL, "entering\n");
SC_scanQueryAndCountParams(orgquery, conn, &endp1, &num_p1, &multi, NULL);
SC_scanQueryAndCountParams(srvquery, conn, &endp2, NULL, NULL, NULL);
MYLOG(0, "parsed for the first command length=" FORMAT_SSIZE_T "(" FORMAT_SSIZE_T ") num_p=%d\n", endp2, endp1, num_p1);
+ /*
+ * Discard the list built by a previous (not completed) prepare attempt
+ * of this statement, otherwise it would be lost.
+ */
+ SC_free_processed_statements(stmt);
pstmt = buildProcessedStmt(srvquery,
endp2 < 0 ? SQL_NTS : endp2,
fake_params ? 0 : num_p1);
@@ -3079,6 +3105,16 @@ MYLOG(DETAIL_LOG_LEVEL, "entering\n");
stmt->processed_statements = last_pstmt = pstmt;
while (multi > 0)
{
+ /*
+ * The original query has another command, so the converted
+ * one must have one too. Otherwise srvquery would not advance
+ * and the rest of it would be copied once per remaining command.
+ */
+ if (endp2 < 0)
+ {
+ SC_set_error(stmt, STMT_INTERNAL_ERROR, "The converted query has fewer commands than the original one", func);
+ goto cleanup;
+ }
orgquery += (endp1 + 1);
srvquery += (endp2 + 1);
num_pa += num_p1;
@@ -3408,7 +3444,7 @@ MYLOG(DETAIL_LOG_LEVEL, "type=" FORMAT_UINTEGER " concur=" FORMAT_UINTEGER "\n",
if (npos = F_NewPos(qb) - 1, npos >= 0)
ptr = F_NewPtr(qb) - 1;
- for (; npos >= 0 && isspace(*ptr); npos--, ptr--) ;
+ for (; npos >= 0 && isspace((UCHAR) *ptr); npos--, ptr--) ;
if (npos >= 0 && semi_colon == *ptr)
{
qb->npos = npos;
@@ -3703,7 +3739,7 @@ eatTableIdentifiers(const UCHAR *str, const ConnectionClass *conn, pgNAME *table
const UCHAR *next_token;
const UCHAR *tstr = str;
- while (isspace(*tstr)) tstr++;
+ while (isspace((UCHAR) *tstr)) tstr++;
if ((len = findIdentifier(tstr, ccsc, &next_token)) <= 0)
return len; /* table name doesn't exist */
@@ -4178,7 +4214,9 @@ inner_process_tokens(QueryParse *qp, QueryBuild *qb)
* server), so never hand its result to
* CVT_APPEND_STR() unchecked.
*/
- CVT_APPEND_STR(qb, "currval(pg_get_serial_sequence('");
+ CVT_APPEND_STR(qb, "currval(pg_get_serial_sequence(");
+ CVT_APPEND_STR(qb, CC_literal_prefix(conn));
+ CVT_APPEND_STR(qb, "'");
if (NAME_IS_VALID(conn->schemaIns))
{
if (NULL != (escaped = identifierEscape((const SQLCHAR *) SAFE_NAME(conn->schemaIns), SQL_NTS, conn, relcnv, sizeof(relcnv), TRUE)))
@@ -4187,7 +4225,9 @@ inner_process_tokens(QueryParse *qp, QueryBuild *qb)
}
if (NULL != (escaped = identifierEscape((const SQLCHAR *) SAFE_NAME(conn->tableIns), SQL_NTS, conn, relcnv, sizeof(relcnv), TRUE)))
CVT_APPEND_STR(qb, escaped);
- CVT_APPEND_STR(qb, "','");
+ CVT_APPEND_STR(qb, "',");
+ CVT_APPEND_STR(qb, CC_literal_prefix(conn));
+ CVT_APPEND_STR(qb, "'");
if (NULL != (escaped = identifierEscape((const SQLCHAR *) column_name, SQL_NTS, conn, relcnv, sizeof(relcnv), FALSE)))
CVT_APPEND_STR(qb, escaped);
CVT_APPEND_STR(qb, "')::regclass)");
@@ -4195,11 +4235,19 @@ inner_process_tokens(QueryParse *qp, QueryBuild *qb)
}
}
}
- TI_ClearObject(pti);
+ {
+ int entered = 0;
+
+ /* the refcnt of the connection's column info */
+ ENTER_INNER_CONN_CS(conn, entered);
+ TI_ClearObject(pti);
+ CLEANUP_FUNC_CONN_CS(entered, conn);
+ }
}
if (!converted)
CVT_APPEND_STR(qb, "NULL");
- qp->opos += 10;
+ /* skip the rest of @@identity; the caller's loop steps over its last character */
+ qp->opos += 9;
return SQL_SUCCESS;
}
@@ -4463,12 +4511,13 @@ build_libpq_bind_params(StatementClass *stmt,
CSTR func = "build_libpq_bind_params";
QueryBuild qb;
SQLSMALLINT num_p;
- int i, num_params;
+ int i, num_params, pno = 0;
ConnectionClass *conn = SC_get_conn(stmt);
BOOL ret = FALSE, discard_output;
RETCODE retval;
const IPDFields *ipdopts = SC_get_IPDF(stmt);
+ *nParams = 0;
*paramTypes = NULL;
*paramValues = NULL;
*paramLengths = NULL;
@@ -4519,11 +4568,9 @@ build_libpq_bind_params(StatementClass *stmt,
num_p = num_params - qb.num_discard_params;
MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p);
discard_output = (0 != (qb.flags & FLGB_DISCARD_OUTPUT));
- *nParams = 0;
if (num_p > 0)
{
ParameterImplClass *parameters = ipdopts->parameters;
- int pno;
BOOL isnull;
BOOL isbinary;
@@ -4533,7 +4580,7 @@ MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p);
/*
* Now build the parameter values.
*/
- for (i = 0, pno = 0; i < stmt->num_params; i++)
+ for (i = 0; i < stmt->num_params; i++)
{
qb.npos = 0;
retval = ResolveOneParam(&qb, NULL, &isnull, &isbinary, &pgType);
@@ -4561,6 +4608,8 @@ MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p);
}
if (!isnull)
{
+ if (qb.npos > INT_MAX)
+ goto cleanup;
val_copy = malloc(qb.npos + 1);
if (!val_copy)
goto cleanup;
@@ -4569,8 +4618,6 @@ MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p);
(*paramTypes)[pno] = pgType;
(*paramValues)[pno] = val_copy;
- if (qb.npos > INT_MAX)
- goto cleanup;
(*paramLengths)[pno] = (int) qb.npos;
}
else
@@ -4585,7 +4632,6 @@ MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p);
pno++;
}
- *nParams = pno;
}
/* result format is text */
@@ -4595,6 +4641,12 @@ MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p);
cleanup:
QB_Destructor(&qb);
+ /*
+ * The caller frees the first *nParams entries of *paramValues, so
+ * report the entries filled so far even when we bail out of the
+ * loop above; otherwise the copies made before the error leak.
+ */
+ *nParams = pno;
return ret;
}
@@ -4802,12 +4854,12 @@ parameter_is_with_cast(const QueryParse *qp)
const char *str = F_OldPtr(qp);
if ('?' != *str) return FALSE;
- while (isspace(*(++str))) ;
+ while (isspace((UCHAR) *(++str))) ;
if (strncmp(str, "::", 2) == 0)
return TRUE;
if (strnicmp(str, "as", 2) != 0)
return FALSE;
- if (isspace(str[2]))
+ if (isspace((UCHAR) str[2]))
return TRUE;
return FALSE;
}
@@ -4817,12 +4869,14 @@ enum {
ErrorOutConversionErrors /* error out conversion errors */
, ReturnZeroLengthString /* simply returns zero length strings */
};
-static int convert_err_flag =
-#ifdef WIN32
- ReturnZeroLengthString;
-#else
- ErrorOutConversionErrors;
-#endif /* WIN32 */
+/*
+ * A character parameter that cannot be converted from the ANSI code page is
+ * an error on every platform. Returning a zero-length string instead runs
+ * the statement with a 01S01 warning, and the server then compares or
+ * stores '' in place of the value the application checked, so this flag
+ * stays at ErrorOutConversionErrors.
+ */
+static int convert_err_flag = ErrorOutConversionErrors;
static BOOL
handle_lu_onvert_error(QueryBuild *qb, int flag, char *buffer, SQLLEN paralen)
@@ -4931,7 +4985,7 @@ ResolveOneParam(QueryBuild *qb, QueryParse *qp, BOOL *isnull, BOOL *isbinary,
SQLLEN used;
const char *send_buf;
- char *buffer, *allocbuf = NULL, *lastadd = NULL;
+ char *buffer, *allocbuf = NULL, *binbuf, *lastadd = NULL;
OID lobj_oid;
int lobj_fd;
SQLULEN offset = apdopts->param_offset_ptr ? *apdopts->param_offset_ptr : 0;
@@ -5102,6 +5156,37 @@ MYLOG(DETAIL_LOG_LEVEL, "ipara=%p paramName=%s paramType=%d %d proc_return=%d\n"
* those cases.
*/
+ param_ctype = apara->CType;
+ param_sqltype = ipara->SQLType;
+ param_pgtype = PIC_dsp_pgtype(qb->conn, *ipara);
+
+ /* XXX: should we use param_pgtype here instead? */
+ *pgType = sqltype_to_bind_pgtype(conn, param_sqltype);
+
+ if (0 == param_sqltype) /* calling SQLSetStmtAttr(.., SQL_ATTR_APP_PARAM_DES, an ARD of another statement) may cause this */
+ {
+ if (0 != param_pgtype)
+ {
+ param_sqltype = pgtype_attr_to_concise_type(conn, param_pgtype, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET);
+ MYLOG(0, "convert from pgtype(%u) to sqltype(%d)\n", param_pgtype, param_sqltype);
+ }
+ }
+
+ /*
+ * replace DEFAULT with something we can use. This must be done before
+ * the address of the current row is computed below, which needs the
+ * length of the real C type for column-wise bound arrays.
+ */
+ if (param_ctype == SQL_C_DEFAULT)
+ {
+ param_ctype = sqltype_to_default_ctype(conn, param_sqltype);
+#ifdef UNICODE_SUPPORT
+ if (param_ctype == SQL_C_WCHAR
+ && CC_default_is_c(conn))
+ param_ctype =SQL_C_CHAR;
+#endif
+ }
+
/* Assign correct buffers based on data at exec param or not */
if (apara->data_at_exec)
{
@@ -5123,7 +5208,7 @@ MYLOG(DETAIL_LOG_LEVEL, "ipara=%p paramName=%s paramType=%d %d proc_return=%d\n"
{
if (bind_size > 0)
buffer += (bind_size * current_row);
- else if (ctypelen = ctype_length(apara->CType), ctypelen > 0)
+ else if (ctypelen = ctype_length(param_ctype), ctypelen > 0)
buffer += current_row * ctypelen;
else
buffer += current_row * apara->buflen;
@@ -5168,22 +5253,6 @@ MYLOG(DETAIL_LOG_LEVEL, "ipara=%p paramName=%s paramType=%d %d proc_return=%d\n"
return SQL_SUCCESS;
} */
- param_ctype = apara->CType;
- param_sqltype = ipara->SQLType;
- param_pgtype = PIC_dsp_pgtype(qb->conn, *ipara);
-
- /* XXX: should we use param_pgtype here instead? */
- *pgType = sqltype_to_bind_pgtype(conn, param_sqltype);
-
- if (0 == param_sqltype) /* calling SQLSetStmtAttr(.., SQL_ATTR_APP_PARAM_DES, an ARD of another statement) may cause this */
- {
- if (0 != param_pgtype)
- {
- param_sqltype = pgtype_attr_to_concise_type(conn, param_pgtype, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET);
- MYLOG(0, "convert from pgtype(%u) to sqltype(%d)\n", param_pgtype, param_sqltype);
- }
- }
-
MYLOG(0, "from(fcType)=%d, to(fSqlType)=%d(%u), *pgType=%u\n",
param_ctype, param_sqltype, param_pgtype, *pgType);
@@ -5225,17 +5294,6 @@ MYLOG(DETAIL_LOG_LEVEL, "ipara=%p paramName=%s paramType=%d %d proc_return=%d\n"
}
}
- /* replace DEFAULT with something we can use */
- if (param_ctype == SQL_C_DEFAULT)
- {
- param_ctype = sqltype_to_default_ctype(conn, param_sqltype);
-#ifdef UNICODE_SUPPORT
- if (param_ctype == SQL_C_WCHAR
- && CC_default_is_c(conn))
- param_ctype =SQL_C_CHAR;
-#endif
- }
-
/*
* SQLSetPos() and SQLBulkOperations() bind the application's column
* buffers as the parameters of an internal statement (whose
@@ -5266,6 +5324,30 @@ MYLOG(DETAIL_LOG_LEVEL, "ipara=%p paramName=%s paramType=%d %d proc_return=%d\n"
return SQL_ERROR;
}
+ /*
+ * For character and binary C types 'used' is the byte count of the
+ * value or SQL_NTS from here on. Reject other negative values
+ * (SQL_NO_TOTAL, SQL_COLUMN_IGNORE, ...) as SQLPutData does instead
+ * of using them as a length. Data-at-exec lengths are only recognized
+ * at execution time, so when faking parameters treat them as unknown
+ * values.
+ */
+ switch (param_ctype)
+ {
+ case SQL_C_CHAR:
+ case SQL_C_BINARY:
+#ifdef UNICODE_SUPPORT
+ case SQL_C_WCHAR:
+#endif /* UNICODE_SUPPORT */
+ if (used < 0 && used != SQL_NTS)
+ {
+ qb->errormsg = "Invalid string or buffer length";
+ qb->errornumber = STMT_INVALID_ARGUMENT_NO;
+ return SQL_ERROR;
+ }
+ break;
+ }
+
allocbuf = NULL;
send_buf = NULL;
param_string[0] = '\0';
@@ -5728,12 +5810,24 @@ MYLOG(0, "cvt_null_date_string=%d pgtype=%d send_buf=%p\n", conn->connInfo.cvt_n
used = strlen(send_buf);
break;
}
- allocbuf = malloc(used / 2 + 1);
- if (allocbuf)
+ binbuf = malloc(used / 2 + 1);
+ if (!binbuf)
{
- used = pg_hex2bin(send_buf, allocbuf, used);
- send_buf = allocbuf;
+ qb->errormsg = "Could not allocate memory for the binary parameter";
+ qb->errornumber = STMT_NO_MEMORY_ERROR;
+ goto cleanup;
}
+ used = pg_hex2bin(send_buf, binbuf, used);
+ /*
+ * send_buf may be the converted copy owned by
+ * allocbuf (SQL_C_WCHAR, or SQL_C_CHAR in a locale
+ * whose encoding differs from the connection's);
+ * release it before allocbuf takes over the
+ * decoded buffer.
+ */
+ if (allocbuf)
+ free(allocbuf);
+ send_buf = allocbuf = binbuf;
break;
default:
qb->errormsg = "Could not convert the ctype to binary type";
@@ -5790,6 +5884,9 @@ MYLOG(0, "cvt_null_date_string=%d pgtype=%d send_buf=%p\n", conn->connInfo.cvt_n
{
qb->errornumber = STMT_EXEC_ERROR;
qb->errormsg = "Couldn't create (in-line) large object.";
+ /* don't leave the (aborted) in-line transaction behind */
+ if (!is_in_trans_at_entry)
+ CC_abort(conn);
goto cleanup;
}
@@ -5799,6 +5896,8 @@ MYLOG(0, "cvt_null_date_string=%d pgtype=%d send_buf=%p\n", conn->connInfo.cvt_n
{
qb->errornumber = STMT_EXEC_ERROR;
qb->errormsg = "Couldn't open (in-line) large object for writing.";
+ if (!is_in_trans_at_entry)
+ CC_abort(conn);
goto cleanup;
}
@@ -5811,6 +5910,8 @@ MYLOG(0, "cvt_null_date_string=%d pgtype=%d send_buf=%p\n", conn->connInfo.cvt_n
{
qb->errornumber = STMT_EXEC_ERROR;
qb->errormsg = "Couldn't write to (in-line) large object.";
+ if (!is_in_trans_at_entry)
+ CC_abort(conn);
goto cleanup;
}
@@ -6347,7 +6448,7 @@ convert_escape(QueryParse *qp, QueryBuild *qb)
int i, from, to;
const char * p;
- for (i = param_pos[0][0], p = nqb.query_statement + i; i <= param_pos[0][1] && isspace(*p); i++, p++)
+ for (i = param_pos[0][0], p = nqb.query_statement + i; i <= param_pos[0][1] && isspace((UCHAR) *p); i++, p++)
;
from = i;
for (; i <= param_pos[0][1] && IS_NOT_SPACE(*p); i++, p++)
@@ -6416,7 +6517,7 @@ convert_escape(QueryParse *qp, QueryBuild *qb)
memcpy(sqltype, nqb.query_statement + from, typel);
sqltype[typel] = '\0';
MYLOG(0, FORMAT_LEN "-" FORMAT_LEN " SQLtype=%s SQL_BIT=%d\n", to, from, sqltype, SQL_BIT);
- for (type = sqltype; *type && isspace(*type); type++)
+ for (type = sqltype; *type && isspace((UCHAR) *type); type++)
;
if (strncmp(type, "SQL_", 4) == 0)
{
@@ -6619,6 +6720,7 @@ parse_datetime(const char *buf, SIMPLE_TIME *st)
int nf;
int status = 0;
BOOL bZone; int zone;
+ BOOL year_first;
y = m = d = hh = mm = ss = 0;
st->fr = 0;
@@ -6640,7 +6742,9 @@ parse_datetime(const char *buf, SIMPLE_TIME *st)
bZone = FALSE;
if (timestamp2stime(buf, st, &bZone, &zone))
return TRUE;
- if (buf[4] == '-') /* year first */
+ /* don't look at buf[4] unless the string is at least that long */
+ year_first = (strlen(buf) > 4 && buf[4] == '-');
+ if (year_first)
nf = secure_sscanf(buf, &status, "%4d-%2d-%2d %2d:%2d:%2d",
ARG_INT(&y), ARG_INT(&m), ARG_INT(&d),
ARG_INT(&hh), ARG_INT(&mm), ARG_INT(&ss));
@@ -6661,7 +6765,7 @@ parse_datetime(const char *buf, SIMPLE_TIME *st)
return TRUE;
}
- if (buf[4] == '-') /* year first */
+ if (year_first)
nf = secure_sscanf(buf, &status, "%4d-%2d-%2d",
ARG_INT(&y), ARG_INT(&m), ARG_INT(&d));
else
@@ -7138,6 +7242,15 @@ convert_lo(StatementClass *stmt, const void *value, SQLSMALLINT fCType, PTR rgbV
stmt->lobj_fd = odbc_lo_open(conn, oid, INV_READ);
if (stmt->lobj_fd < 0)
{
+ /*
+ * The failed lo_open has aborted the transaction. In
+ * autocommit mode it is the driver's own (begun above or
+ * for the cursor), not the application's, so end it here;
+ * otherwise every later query on this connection fails
+ * with 25P02 and SQLEndTran can't get rid of it.
+ */
+ if (CC_does_autocommit(conn))
+ CC_abort(conn);
SC_set_error(stmt, STMT_EXEC_ERROR, "Couldnt open large object for reading.", func);
return COPY_GENERAL_ERROR;
}
diff --git a/descriptor.c b/descriptor.c
index 4efc68dc..d24a4e50 100644
--- a/descriptor.c
+++ b/descriptor.c
@@ -547,6 +547,12 @@ static void APDFields_copy(const APDFields *src, APDFields *target)
static void ParameterImplClass_copy(const ParameterImplClass *src, ParameterImplClass *target)
{
memcpy(target, src, sizeof(ParameterImplClass));
+ /*
+ * The parameter name is allocated, and each descriptor frees its own.
+ * The target must get a copy of the string, not of the pointer.
+ */
+ INIT_NAME(target->paramName);
+ NAME_TO_NAME(target->paramName, src->paramName);
}
static void IPDFields_copy(const IPDFields *src, IPDFields *target)
{
@@ -568,6 +574,36 @@ static void IPDFields_copy(const IPDFields *src, IPDFields *target)
}
}
+/* Is an explicit descriptor attached to a statement as its ARD or APD? */
+static BOOL
+desc_attached_as_app_desc(const DescriptorClass *desc)
+{
+ ConnectionClass *conn = DC_get_conn(desc);
+ int i;
+ BOOL found = FALSE;
+
+ if (!conn)
+ return FALSE;
+ /*
+ * CC_add_statement() reallocs this array under the connection lock, so
+ * a scan without it can read the array it replaced. SQLCopyDesc on an
+ * explicit descriptor reaches here holding no statement lock either.
+ */
+ CONNLOCK_ACQUIRE(conn);
+ for (i = 0; i < conn->num_stmts; i++)
+ {
+ const StatementClass *stmt = conn->stmts[i];
+
+ if (stmt && (stmt->ard == desc || stmt->apd == desc))
+ {
+ found = TRUE;
+ break;
+ }
+ }
+ CONNLOCK_RELEASE(conn);
+ return found;
+}
+
RETCODE SQL_API
PGAPI_CopyDesc(SQLHDESC SourceDescHandle,
SQLHDESC TargetDescHandle)
@@ -608,17 +644,29 @@ MYLOG(DETAIL_LOG_LEVEL, "source type=%d -> target type=%d\n", srchd->desc_type,
return ret;
}
}
- DC_Destructor(target);
}
+ /*
+ * An explicit descriptor in use as a statement's ARD or APD must keep
+ * that layout, typed or not.
+ */
+ if (!targethd->embedded &&
+ SQL_ATTR_APP_ROW_DESC != srchd->desc_type &&
+ SQL_ATTR_APP_PARAM_DESC != srchd->desc_type &&
+ desc_attached_as_app_desc(target))
+ {
+ MYLOG(0, "target is in use as an application descriptor\n");
+ DC_set_error(target, DESC_EXEC_ERROR, "the target descriptor is in use as an application descriptor");
+ return ret;
+ }
+ if (targethd->type_defined)
+ DC_Destructor(target);
ret = SQL_SUCCESS;
switch (srchd->desc_type)
{
case SQL_ATTR_APP_ROW_DESC:
MYLOG(DETAIL_LOG_LEVEL, "src=%p target=%p type=%d", src, target, srchd->desc_type);
- if (!targethd->type_defined)
- {
- targethd->desc_type = srchd->desc_type;
- }
+ /* the type always follows the contents */
+ targethd->desc_type = srchd->desc_type;
ard_src = &(src->ardf);
MYPRINTF(DETAIL_LOG_LEVEL, " rowset_size=" FORMAT_LEN " bind_size=" FORMAT_UINTEGER " ope_ptr=%p off_ptr=%p\n",
ard_src->size_of_rowset, ard_src->bind_size,
@@ -629,19 +677,15 @@ MYPRINTF(DETAIL_LOG_LEVEL, " target=%p", ard_tgt);
MYPRINTF(DETAIL_LOG_LEVEL, " offset_ptr=%p\n", ard_tgt->row_offset_ptr);
break;
case SQL_ATTR_APP_PARAM_DESC:
- if (!targethd->type_defined)
- {
- targethd->desc_type = srchd->desc_type;
- }
+ /* the type always follows the contents */
+ targethd->desc_type = srchd->desc_type;
apd_src = &(src->apdf);
apd_tgt = &(target->apdf);
APDFields_copy(apd_src, apd_tgt);
break;
case SQL_ATTR_IMP_PARAM_DESC:
- if (!targethd->type_defined)
- {
- targethd->desc_type = srchd->desc_type;
- }
+ /* the type always follows the contents */
+ targethd->desc_type = srchd->desc_type;
ipd_src = &(src->ipdf);
ipd_tgt = &(target->ipdf);
IPDFields_copy(ipd_src, ipd_tgt);
diff --git a/dlg_specific.c b/dlg_specific.c
index 17d72e40..a78beb5e 100644
--- a/dlg_specific.c
+++ b/dlg_specific.c
@@ -608,14 +608,20 @@ MYLOG(DETAIL_LOG_LEVEL, "hlen=" FORMAT_SSIZE_T "\n", hlen);
static void
unfoldCXAttribute(ConnInfo *ci, const char *value)
{
- int count;
- UInt4 flag;
+ int count = 0;
+ UInt4 flag = 0;
int status = 0;
+ /*
+ * secure_sscanf() leaves its arguments untouched when the string
+ * holds no field to parse. Leave the options alone when the flag
+ * word is missing instead of applying an indeterminate value.
+ */
if (strlen(value) < 2)
{
count = 3;
- secure_sscanf(value, &status, "%x", ARG_UINT(&flag));
+ if (secure_sscanf(value, &status, "%x", ARG_UINT(&flag)) < 1)
+ return;
}
else
{
@@ -623,7 +629,8 @@ unfoldCXAttribute(ConnInfo *ci, const char *value)
memcpy(cnt, value, 2);
cnt[2] = '\0';
secure_sscanf(cnt, &status, "%x", ARG_UINT(&count));
- secure_sscanf(value + 2, &status, "%x", ARG_UINT(&flag));
+ if (secure_sscanf(value + 2, &status, "%x", ARG_UINT(&flag)) < 1)
+ return;
}
ci->allow_keyset = (char)((flag & BIT_UPDATABLECURSORS) != 0);
ci->lf_conversion = (char)((flag & BIT_LFCONVERSION) != 0);
@@ -742,7 +749,8 @@ copyConnAttributes(ConnInfo *ci, const char *attribute, const char *value)
}
else if (stricmp(attribute, INI_PQOPT) == 0 || stricmp(attribute, ABBR_PQOPT) == 0)
{
- char *hide_str = hide_conninfo_secrets(value);
+ char *hide_str = get_mylog() ?
+ hide_conninfo_secrets(value) : NULL;
NULL_THE_NAME(ci->pqopt);
ci->pqopt_in_str = TRUE;
@@ -1116,7 +1124,7 @@ MYLOG(0, "drivername=%s\n", drivername);
*/
for (ptr = (UCHAR *) temp, pspace = TRUE, nspcnt = 0; *ptr; ptr++)
{
- if (isspace(*ptr))
+ if (isspace((UCHAR) *ptr))
pspace = TRUE;
else
{
diff --git a/dlg_wingui.c b/dlg_wingui.c
index 700db937..99274237 100644
--- a/dlg_wingui.c
+++ b/dlg_wingui.c
@@ -123,7 +123,9 @@ GetDlgStuff(HWND hdlg, ConnInfo *ci)
STR_TO_NAME(ci->password, medium_buf);
GetDlgItemText(hdlg, IDC_PORT, ci->port, sizeof(ci->port));
sslposition = (int)(DWORD)SendMessage(GetDlgItem(hdlg, IDC_SSLMODE), CB_GETCURSEL, 0L, 0L);
- STRCPY_FIXED(ci->sslmode, modetab[sslposition].modestr);
+ /* CB_ERR (-1) without a selected item: keep the current mode */
+ if (sslposition >= 0 && sslposition < (int) (sizeof(modetab) / sizeof(modetab[0])))
+ STRCPY_FIXED(ci->sslmode, modetab[sslposition].modestr);
}
static void
diff --git a/drvconn.c b/drvconn.c
index 4e877bf0..8f9c6e01 100644
--- a/drvconn.c
+++ b/drvconn.c
@@ -104,7 +104,22 @@ PGAPI_DriverConnect(HDBC hdbc,
return SQL_INVALID_HANDLE;
}
+ if (cbConnStrOutMax < 0)
+ {
+ CC_set_error(conn, CONN_INVALID_BUFFER_LENGTH, "Invalid string or buffer length", func);
+ return SQL_ERROR;
+ }
connStrIn = make_string(szConnStrIn, cbConnStrIn, NULL, 0);
+ if (NULL == connStrIn)
+ {
+ if (NULL == szConnStrIn)
+ CC_set_error(conn, CONN_INVALID_ARGUMENT_NO, "No connection string", func);
+ else if (cbConnStrIn < 0 && SQL_NTS != cbConnStrIn)
+ CC_set_error(conn, CONN_INVALID_BUFFER_LENGTH, "Invalid string or buffer length", func);
+ else
+ CC_set_error(conn, CONN_NO_MEMORY_ERROR, "Could not allocate memory for the connection string", func);
+ return SQL_ERROR;
+ }
#ifdef FORCE_PASSWORD_DISPLAY
MYLOG(0, "**** fDriverCompletion=%d, connStrIn='%s'\n", fDriverCompletion, connStrIn);
diff --git a/environ.c b/environ.c
index 4cb8a27d..ab6b185e 100644
--- a/environ.c
+++ b/environ.c
@@ -52,13 +52,38 @@ void shortterm_common_unlock(void)
LEAVE_COMMON_CS;
}
-int getConnCount(void)
-{
- return conns_count;
-}
-ConnectionClass * const *getConnList(void)
+/*
+ * Return a malloc'd copy of the list of the connections of the environment
+ * env, and set *count to their number. EN_add_connection() may move the
+ * global list meanwhile, so the copy is taken under conns_cs and is used
+ * without it. Return NULL, with *count 0, when the environment has no
+ * connection, and NULL, with *count -1, when memory runs out.
+ */
+ConnectionClass **
+EN_get_connections(const EnvironmentClass *env, int *count)
{
- return conns;
+ ConnectionClass **list = NULL;
+ int i, n = 0;
+
+ ENTER_CONNS_CS;
+ for (i = 0; i < conns_count; i++)
+ if (conns[i] && CC_get_env(conns[i]) == env)
+ n++;
+ if (n > 0)
+ {
+ if (NULL == (list = malloc(n * sizeof(ConnectionClass *))))
+ n = -1;
+ else
+ {
+ n = 0;
+ for (i = 0; i < conns_count; i++)
+ if (conns[i] && CC_get_env(conns[i]) == env)
+ list[n++] = conns[i];
+ }
+ }
+ LEAVE_CONNS_CS;
+ *count = n;
+ return list;
}
RETCODE SQL_API
@@ -306,7 +331,17 @@ PGAPI_ConnectError(HDBC hdbc,
msglen = strlen(msg);
if (NULL != pcbErrorMsg)
{
- *pcbErrorMsg = (SQLSMALLINT) msglen;
+ /*
+ * The message comes from the server and may be longer than an
+ * SQLSMALLINT can hold. Clamp the reported length instead of
+ * letting it wrap, and leave room for the "+ 1" of a caller
+ * that sizes its buffer from the value (as ER_ReturnError
+ * never reports more than cbErrorMsgMax - 1 either).
+ */
+ if (msglen < INT16_MAX)
+ *pcbErrorMsg = (SQLSMALLINT) msglen;
+ else
+ *pcbErrorMsg = INT16_MAX - 1;
if (cbErrorMsgMax == 0)
once_again = TRUE;
else if (msglen >= cbErrorMsgMax)
@@ -314,6 +349,7 @@ PGAPI_ConnectError(HDBC hdbc,
}
if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0))
strncpy_null((char *) szErrorMsg, msg, cbErrorMsgMax);
+ free(msg); /* CC_get_error's copy */
if (NULL != pfNativeError)
*pfNativeError = status;
@@ -378,6 +414,9 @@ PGAPI_ConnectError(HDBC hdbc,
case CONN_INVALID_INFO_TYPE:
pg_sqlstate_set(env, szSqlState, "HY096", "S1096");
break;
+ case CONN_INVALID_BUFFER_LENGTH:
+ pg_sqlstate_set(env, szSqlState, "HY090", "S1090");
+ break;
case CONN_OPTION_NOT_FOR_THE_DRIVER:
pg_sqlstate_set(env, szSqlState, "HY092", "S1092");
break;
@@ -439,7 +478,15 @@ PGAPI_EnvError(HENV henv,
MYLOG(0, "EN_get_error: status = %d, msg = #%s#\n", status, msg);
if (NULL != pcbErrorMsg)
- *pcbErrorMsg = (SQLSMALLINT) strlen(msg);
+ {
+ size_t msglen = strlen(msg);
+
+ /* same clamp as in PGAPI_ConnectError */
+ if (msglen < INT16_MAX)
+ *pcbErrorMsg = (SQLSMALLINT) msglen;
+ else
+ *pcbErrorMsg = INT16_MAX - 1;
+ }
if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0))
strncpy_null((char *) szErrorMsg, msg, cbErrorMsgMax);
if (NULL != pfNativeError)
@@ -633,17 +680,20 @@ char
EN_remove_connection(EnvironmentClass *self, ConnectionClass *conn)
{
int i;
+ char ret = FALSE;
+ /* the whole scan: EN_add_connection() may move the list meanwhile */
+ ENTER_CONNS_CS;
for (i = 0; i < conns_count; i++)
if (conns[i] == conn && conns[i]->status != CONN_EXECUTING)
{
- ENTER_CONNS_CS;
conns[i] = NULL;
- LEAVE_CONNS_CS;
- return TRUE;
+ ret = TRUE;
+ break;
}
+ LEAVE_CONNS_CS;
- return FALSE;
+ return ret;
}
diff --git a/environ.h b/environ.h
index 63d43886..aa9fb54d 100644
--- a/environ.h
+++ b/environ.h
@@ -41,8 +41,7 @@ char EN_get_error(EnvironmentClass *self, int *number, char **message);
char EN_add_connection(EnvironmentClass *self, ConnectionClass *conn);
char EN_remove_connection(EnvironmentClass *self, ConnectionClass *conn);
void EN_log_error(const char *func, char *desc, EnvironmentClass *self);
-int getConnCount(void);
-ConnectionClass * const *getConnList(void);
+ConnectionClass **EN_get_connections(const EnvironmentClass *env, int *count);
#define EN_OV_ODBC2 1L
#define EN_CONN_POOLING (1L<<1)
diff --git a/execute.c b/execute.c
index 8d88df54..7ea71e0d 100644
--- a/execute.c
+++ b/execute.c
@@ -792,6 +792,18 @@ SetStatementSvp(StatementClass *stmt, unsigned int option)
if (CC_is_in_error_trans(conn))
return ret;
+ /*
+ * Statements the driver allocates for its own queries (the catalog
+ * functions, the column info of updatable cursors) never pass through
+ * StartRollbackState(), which only the SQL* entry points call on the
+ * application's statement. Give them the rollback mode of the
+ * connection here, otherwise no SAVEPOINT is set in front of their
+ * query and DiscardStatementSvp() can only roll back the whole
+ * transaction when the call fails.
+ */
+ if (!stmt->external && !SC_is_rb_stmt(stmt) && !SC_is_tc_stmt(stmt))
+ StartRollbackState(stmt);
+
if (!stmt->lock_CC_for_rb)
{
ENTER_CONN_CS(conn);
@@ -805,8 +817,16 @@ MYLOG(DETAIL_LOG_LEVEL, " %p->accessed=%d opt=%u in_progress=%u prev=%u\n", conn
case STMT_TYPE_TRANSACTION:
return ret;
}
- /* If rbpoint is not yet started and the previous statement was not read-only */
- if (!CC_started_rbpoint(conn) && 0 == (conn->opt_previous & SVPOPT_RDONLY))
+ /*
+ * Every statement that reaches here needs a SAVEPOINT of its own,
+ * including one whose predecessor only read: skipping it on the
+ * grounds that the savepoint set before the read is still good
+ * leaves the rbpoint unmarked as started, and an error then rolls
+ * back the whole transaction. That shortcut holds only where every
+ * write has been recorded as a started rbpoint, which the driver
+ * does not guarantee. The new savepoint sends one more round trip.
+ */
+ if (!CC_started_rbpoint(conn))
{
BOOL need_savep = FALSE;
@@ -1312,17 +1332,32 @@ PGAPI_Transact(HENV henv,
*/
if (hdbc == SQL_NULL_HDBC && henv != SQL_NULL_HENV)
{
- ConnectionClass * const *conns = getConnList();
- const int conn_count = getConnCount();
- for (lf = 0; lf < conn_count; lf++)
+ /*
+ * A copy of the list: the lock that protects it is not held across
+ * the round trips of the commits.
+ */
+ int conn_count;
+ ConnectionClass **conns = EN_get_connections((EnvironmentClass *) henv, &conn_count);
+ RETCODE ret = SQL_SUCCESS;
+
+ if (conn_count < 0)
{
- conn = conns[lf];
+ EnvironmentClass *env = (EnvironmentClass *) henv;
- if (conn && CC_get_env(conn) == henv)
- if (PGAPI_Transact(henv, (HDBC) conn, fType) != SQL_SUCCESS)
- return SQL_ERROR;
+ env->errornumber = ENV_ALLOC_ERROR;
+ env->errormsg = "Couldn't allocate memory for the list of connections.";
+ return SQL_ERROR;
}
- return SQL_SUCCESS;
+ for (lf = 0; lf < conn_count; lf++)
+ {
+ if (PGAPI_Transact(henv, (HDBC) conns[lf], fType) != SQL_SUCCESS)
+ {
+ ret = SQL_ERROR;
+ break;
+ }
+ }
+ free(conns);
+ return ret;
}
conn = (ConnectionClass *) hdbc;
@@ -1334,6 +1369,21 @@ PGAPI_Transact(HENV henv,
return SQL_ERROR;
}
+ /*
+ * When the driver gave the connection up, CC_on_abort(CONN_DEAD) has
+ * already cleared the in-transaction flag, so the test below would take
+ * a discarded transaction for one without work to commit, and report
+ * success for work the server rolled back. A commit on a connection in
+ * this state fails instead. SQL_ROLLBACK is left alone, because the
+ * server has indeed rolled the transaction back.
+ */
+ if (SQL_COMMIT == fType && CONN_DOWN == conn->status)
+ {
+ CC_set_error(conn, CONNECTION_COMMUNICATION_ERROR, "Could not commit, the connection was lost", func);
+ CC_log_error(func, "", conn);
+ return SQL_ERROR;
+ }
+
/* If manual commit and in transaction, then proceed. */
if (CC_loves_visible_trans(conn) && CC_is_in_trans(conn))
{
@@ -1391,11 +1441,6 @@ PGAPI_Cancel(HSTMT hstmt) /* Statement to cancel. */
}
conn = SC_get_conn(stmt);
- if (stmt->execute_delegate)
- estmt = stmt->execute_delegate;
- else
- estmt = stmt;
-
/*
* SQLCancel works differently depending on what the statement is
* currently doing:
@@ -1413,12 +1458,26 @@ PGAPI_Cancel(HSTMT hstmt) /* Statement to cancel. */
* -> in ODBC version 2.0, same as SQLFreeStmt(SQL_CLOSE). In version
* 3.5, it has no effect.
*
- * XXX: Checking for these conditions is racy. For example, we might
- * see that the statement is waiting for SQLParamdata/SQLPutData, but
- * before we acquire the lock on the statement, another thread has
- * supplied the data and started executing. In that case, we'll block
- * on the lock until the execution finishes.
+ * The function running in another thread holds the statement lock, and
+ * it may free execute_delegate, so the delegate is read only under the
+ * lock. If the lock is taken, another thread is in a call on this
+ * statement. Whether that call is an execution shows in the fields
+ * SC_SetExecuting() writes under the common lock: the status of this
+ * statement, and delegate_executing when the executing statement is a
+ * delegate. A call that is not an execution (SQLGetDiagRec() takes the
+ * lock too) must not lead to a cancel request, which the server
+ * applies to whatever query the connection is running, and so could
+ * kill another statement's query.
*/
+ if (!TRY_ENTER_STMT_CS(stmt))
+ {
+ if (!SC_ExecutionInProgress(stmt))
+ return SQL_SUCCESS;
+ if (!CC_send_cancel_request(conn))
+ return SQL_ERROR;
+ return SQL_SUCCESS;
+ }
+ estmt = stmt->execute_delegate ? stmt->execute_delegate : stmt;
if (estmt->data_at_exec >= 0)
{
/* Waiting for more data from SQLParamData/SQLPutData. Cancel that. */
@@ -1426,32 +1485,15 @@ PGAPI_Cancel(HSTMT hstmt) /* Statement to cancel. */
* Note, any previous data-at-exec buffers will be freed
* if they call SQLExecDirect or SQLExecute again.
*/
-
- ENTER_STMT_CS(stmt);
SC_clear_error(stmt);
cancel_data_at_exec(stmt);
- LEAVE_STMT_CS(stmt);
- return ret;
- }
- else if (estmt->status == STMT_EXECUTING)
- {
- /*
- * Busy executing in a different thread. Send a cancel request to
- * the server.
- */
- if (!CC_send_cancel_request(conn))
- return SQL_ERROR;
- else
- return SQL_SUCCESS;
- }
- else
- {
- /*
- * The statement is not executing, and it's not waiting for params
- * either. Looks like it's not doing anything.
- */
- return SQL_SUCCESS;
}
+ /*
+ * Otherwise the statement is not executing, and it's not waiting for
+ * params either. Looks like it's not doing anything.
+ */
+ LEAVE_STMT_CS(stmt);
+ return ret;
}
@@ -1533,8 +1575,9 @@ PGAPI_ParamData(HSTMT hstmt,
MYLOG(0, "\tdata_at_exec=%d, params_alloc=%d\n", estmt->data_at_exec, apdopts->allocated);
/*
- * Nothing is pending, so there is nothing to abandon: return without
- * going through cleanup, which would cancel an operation on stmt.
+ * No parameter is pending, so this call has none to abandon: return
+ * without going through cleanup, which would cancel an operation on
+ * stmt.
*/
if (estmt->data_at_exec < 0)
{
@@ -1625,7 +1668,22 @@ MYPRINTF(DETAIL_LOG_LEVEL, " at exec buffer=%p", apdopts->parameters[i].buffer);
if (stmt->execute_delegate)
{
SQLULEN offset = apdopts->param_offset_ptr ? *apdopts->param_offset_ptr : 0;
- SQLLEN perrow = apdopts->param_bind_type > 0 ? apdopts->param_bind_type : apdopts->parameters[i].buflen;
+ SQLLEN perrow = apdopts->param_bind_type;
+
+ if (perrow <= 0)
+ {
+ /*
+ * column-wise binding: the rows of a fixed-length
+ * C type are sizeof(type) apart, BufferLength
+ * only counts for character and binary data.
+ */
+ Int2 ctype = apdopts->parameters[i].CType;
+
+ if (SQL_C_DEFAULT == ctype && i < ipdopts->allocated)
+ ctype = sqltype_to_default_ctype(conn, ipdopts->parameters[i].SQLType);
+ if (perrow = ctype_length(ctype), perrow <= 0)
+ perrow = apdopts->parameters[i].buflen;
+ }
MYPRINTF(DETAIL_LOG_LEVEL, " offset=" FORMAT_LEN " perrow=" FORMAT_LEN, offset, perrow);
*prgbValue = apdopts->parameters[i].buffer + offset + estmt->exec_current_row * perrow;
@@ -1700,10 +1758,34 @@ PGAPI_PutData(HSTMT hstmt,
}
apdopts = SC_get_APDF(estmt);
- current_param = &(apdopts->parameters[estmt->current_exec_param]);
+ /*
+ * PGAPI_ParamData() chooses current_exec_param within the APD.
+ * SQLBindParameter makes room for a parameter in the APD, the IPD and
+ * the put-data array together, but setting descriptor fields makes
+ * room in that one descriptor only. So the IPD and the put-data array
+ * must be brought up to the APD's size here, and the parameter must
+ * be inside all three before any of them is indexed. An array that
+ * could not be allocated has a size of 0.
+ */
ipdopts = SC_get_IPDF(estmt);
- current_iparam = &(ipdopts->parameters[estmt->current_exec_param]);
pdata = SC_get_PDTI(estmt);
+ if (estmt->current_exec_param >= apdopts->allocated)
+ {
+ SC_set_error(stmt, STMT_SEQUENCE_ERROR, "The parameter SQLParamData asked for is not in the APD any more", func);
+ retval = SQL_ERROR;
+ goto cleanup;
+ }
+ extend_iparameter_bindings(ipdopts, apdopts->allocated);
+ extend_putdata_info(pdata, apdopts->allocated, FALSE);
+ if (estmt->current_exec_param >= ipdopts->allocated ||
+ estmt->current_exec_param >= pdata->allocated)
+ {
+ SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_PutData (0)", func);
+ retval = SQL_ERROR;
+ goto cleanup;
+ }
+ current_param = &(apdopts->parameters[estmt->current_exec_param]);
+ current_iparam = &(ipdopts->parameters[estmt->current_exec_param]);
current_pdata = &(pdata->pdata[estmt->current_exec_param]);
ctype = current_param->CType;
@@ -1847,6 +1929,13 @@ PGAPI_PutData(HSTMT hstmt,
/* calling SQLPutData more than once */
MYLOG(0, "(>1) cbValue = " FORMAT_LEN "\n", cbValue);
+ /* SQLBindParameter on this parameter frees what was put so far */
+ if (!current_pdata->EXEC_used)
+ {
+ SC_set_error(stmt, STMT_SEQUENCE_ERROR, "The parameter was bound again after SQLPutData had data for it", func);
+ retval = SQL_ERROR;
+ goto cleanup;
+ }
if (*current_pdata->EXEC_used < 0)
{
SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Cannot append data after a null or default parameter indicator", func);
@@ -1897,7 +1986,7 @@ PGAPI_PutData(HSTMT hstmt,
retval = SQL_ERROR;
goto cleanup;
}
- /* a piece of length 0 is valid and adds nothing */
+ /* a piece of length 0 is valid and appends no byte */
}
}
diff --git a/info.c b/info.c
index 129781b9..be9042dd 100644
--- a/info.c
+++ b/info.c
@@ -1088,6 +1088,12 @@ MYLOG(0, "CONVERT_FUNCTIONS=" FORMAT_ULEN "\n", value);
/* char/binary data */
len = strlen(p);
+ if (rgbInfoValue && cbInfoValueMax < 0)
+ {
+ CC_set_error(conn, CONN_INVALID_BUFFER_LENGTH, "Invalid string or buffer length", func);
+ ret = SQL_ERROR;
+ goto cleanup;
+ }
if (rgbInfoValue)
{
#ifdef UNICODE_SUPPORT
@@ -1619,7 +1625,7 @@ identifierEscape(const SQLCHAR *src, SQLLEN srclen, const ConnectionClass *conn,
srclen = (SQLLEN) strlen((char *) src);
if (srclen <= 0)
return dest;
-MYLOG(0, "entering in=%s(" FORMAT_LEN ")\n", src, srclen);
+MYLOG(0, "entering in=%.*s(" FORMAT_LEN ")\n", (int) srclen, src, srclen);
if (NULL != buf && bufsize > 0)
dest = buf;
else
@@ -1644,10 +1650,13 @@ MYLOG(0, "entering in=%s(" FORMAT_LEN ")\n", src, srclen);
if (double_quote && (size_t) outlen + reserve < bufsize)
dest[outlen++] = IDENTIFIER_QUOTE;
- for (i = 0, tchar = encoded_nextchar(&encstr);
- i < srclen && (size_t) outlen + 2 + reserve <= bufsize;
- i++, tchar = encoded_nextchar(&encstr))
+ /*
+ * src may be a counted string without a terminator, so fetch
+ * the next byte only after checking i < srclen.
+ */
+ for (i = 0; i < srclen && (size_t) outlen + 2 + reserve <= bufsize; i++)
{
+ tchar = encoded_nextchar(&encstr);
if (MBCS_NON_ASCII(encstr))
{
dest[outlen++] = tchar;
@@ -1773,7 +1782,7 @@ CSTR eq_op_ext = "operator(pg_catalog.=) E";
static const char *gen_opestr(const char *orig_opestr, const ConnectionClass * conn)
{
- BOOL addE = (0 != CC_get_escape(conn) && PG_VERSION_GE(conn, 8.1));
+ BOOL addE = ('\0' != CC_literal_prefix(conn)[0]);
if (0 == strcmp(orig_opestr, eqop))
return (addE ? eq_op_ext : eq_op_sp);
@@ -1800,6 +1809,13 @@ allow_public_schema(ConnectionClass *conn, const SQLCHAR *szSchemaName, SQLSMALL
else
schemalen = cbSchemaName;
+ /*
+ * Already retrying with "public": a user named "Public" would match
+ * it again and loop for ever.
+ */
+ if (schemalen == strlen((const char *) pubstr) &&
+ strnicmp((char *) szSchemaName, (const char *) pubstr, schemalen) == 0)
+ return FALSE;
if (schemalen != userlen)
return FALSE;
if (strnicmp((char *) szSchemaName, user, userlen) != 0)
@@ -1812,6 +1828,25 @@ allow_public_schema(ConnectionClass *conn, const SQLCHAR *szSchemaName, SQLSMALL
return stricmp(curschema, (const char *) pubstr) == 0;
}
+/*
+ * The catalog functions below read the reply to their internal query
+ * through bindings by column position. A fetch fills only the bindings
+ * of the columns the reply has, so a (malicious or buggy) server that
+ * answers with fewer columns would leave the other bound variables
+ * uninitialized. Check that cat_stmt's result has at least num_cols
+ * columns before anything is bound or read from it.
+ */
+static BOOL
+catalog_result_has_columns(StatementClass *stmt, StatementClass *cat_stmt, int num_cols, const char *func)
+{
+ QResultClass *res = SC_get_Result(cat_stmt);
+
+ if (res && QR_NumPublicResultCols(res) >= num_cols)
+ return TRUE;
+ SC_set_error(stmt, STMT_EXEC_ERROR, "Unexpected number of columns in the reply to a catalog query", func);
+ return FALSE;
+}
+
#define TABLE_IN_RELKIND "('r', 'v', 'm', 'f', 'p')"
RETCODE SQL_API
@@ -2092,6 +2127,8 @@ retry_public_schema:
SC_full_error_copy(stmt, tbl_stmt, FALSE);
goto cleanup;
}
+ if (!catalog_result_has_columns(stmt, tbl_stmt, 3, func))
+ goto cleanup;
/* If not found */
if ((res = SC_get_Result(tbl_stmt)) &&
@@ -2101,6 +2138,7 @@ retry_public_schema:
{
szSchemaName = pubstr;
cbSchemaName = SQL_NTS;
+ termPQExpBuffer(&tables_query);
goto retry_public_schema;
}
}
@@ -2555,6 +2593,9 @@ retry_public_schema:
SC_full_error_copy(stmt, col_stmt, FALSE);
goto cleanup;
}
+ /* columns 1 to 18 are bound or read by position below */
+ if (!catalog_result_has_columns(stmt, col_stmt, 18, func))
+ goto cleanup;
/* If not found */
if ((flag & PODBC_SEARCH_PUBLIC_SCHEMA) != 0 &&
@@ -2568,6 +2609,7 @@ retry_public_schema:
col_stmt = NULL;
szSchemaName = pubstr;
cbSchemaName = SQL_NTS;
+ termPQExpBuffer(&columns_query);
goto retry_public_schema;
}
}
@@ -2799,7 +2841,16 @@ retry_public_schema:
}
attdef = NULL;
PGAPI_SetPos(col_stmt, 1, SQL_POSITION, 0);
- PGAPI_GetData(col_stmt, 13, internal_asis_type, NULL, 0, &len_needed);
+ /*
+ * len_needed is only set when GetData succeeds; don't size the
+ * allocation or read attdef after a failed call.
+ */
+ result = PGAPI_GetData(col_stmt, 13, internal_asis_type, NULL, 0, &len_needed);
+ if (!SQL_SUCCEEDED(result))
+ {
+ SC_full_error_copy(stmt, col_stmt, FALSE);
+ goto cleanup;
+ }
if (len_needed > 0)
{
MYLOG(0, "len_needed=" FORMAT_LEN "\n", len_needed);
@@ -2810,7 +2861,13 @@ MYLOG(0, "len_needed=" FORMAT_LEN "\n", len_needed);
goto cleanup;
}
- PGAPI_GetData(col_stmt, 13, internal_asis_type, attdef, len_needed + 1, &len_needed);
+ result = PGAPI_GetData(col_stmt, 13, internal_asis_type, attdef, len_needed + 1, &len_needed);
+ if (!SQL_SUCCEEDED(result))
+ {
+ free(attdef);
+ SC_full_error_copy(stmt, col_stmt, FALSE);
+ goto cleanup;
+ }
MYLOG(0, " and the data=%s\n", attdef);
}
tuple = QR_AddNew(res);
@@ -3166,6 +3223,8 @@ retry_public_schema:
SC_full_error_copy(stmt, col_stmt, FALSE);
goto cleanup;
}
+ if (!catalog_result_has_columns(stmt, col_stmt, 3, func))
+ goto cleanup;
/* If not found */
if ((res = SC_get_Result(col_stmt)) &&
@@ -3177,6 +3236,7 @@ retry_public_schema:
col_stmt = NULL;
szSchemaName = pubstr;
cbSchemaName = SQL_NTS;
+ termPQExpBuffer(&columns_query);
goto retry_public_schema;
}
@@ -3611,6 +3671,8 @@ PGAPI_Statistics(HSTMT hstmt,
SC_full_error_copy(stmt, indx_stmt, FALSE);
goto cleanup;
}
+ if (!catalog_result_has_columns(stmt, indx_stmt, 10, func))
+ goto cleanup;
/* bind the index name column */
result = PGAPI_BindCol(indx_stmt, 1, internal_asis_type,
@@ -4263,6 +4325,8 @@ retry_public_schema:
SC_full_error_copy(stmt, tbl_stmt, FALSE);
goto cleanup;
}
+ if (!catalog_result_has_columns(stmt, tbl_stmt, 5, func))
+ goto cleanup;
result = PGAPI_Fetch(tbl_stmt);
if (result != SQL_NO_DATA_FOUND)
@@ -4277,6 +4341,8 @@ retry_public_schema:
{
szSchemaName = pubstr;
cbSchemaName = SQL_NTS;
+ /* the label is above the initPQExpBuffer of this buffer */
+ termPQExpBuffer(&tables_query);
goto retry_public_schema;
}
}
@@ -4680,6 +4746,8 @@ PGAPI_ForeignKeys_old(HSTMT hstmt,
SC_full_error_copy(stmt, tbl_stmt, FALSE);
goto cleanup;
}
+ if (!catalog_result_has_columns(stmt, tbl_stmt, 11, func))
+ goto cleanup;
result = PGAPI_BindCol(tbl_stmt, 1, SQL_C_BINARY,
trig_args, sizeof(trig_args) - 1, &trig_args_len);
@@ -5006,6 +5074,8 @@ PGAPI_ForeignKeys_old(HSTMT hstmt,
{
goto cleanup;
}
+ if (!catalog_result_has_columns(stmt, tbl_stmt, 11, func))
+ goto cleanup;
result = PGAPI_BindCol(tbl_stmt, 1, SQL_C_BINARY,
trig_args, sizeof(trig_args) - 1, &trig_args_len);
@@ -6037,6 +6107,7 @@ retry_public_schema:
wres = NULL;
szSchemaName = pubstr;
cbSchemaName = SQL_NTS;
+ termPQExpBuffer(&proc_query);
goto retry_public_schema;
}
}
@@ -6330,7 +6401,8 @@ PGAPI_ForeignKeys_new(HSTMT hstmt,
SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_ForeignKeys.", func);
goto cleanup;
}
- SPRINTF_FIXED(catName, "'%s'::name", escCatName);
+ SPRINTF_FIXED(catName, "%s'%s'::name",
+ CC_literal_prefix(conn), escCatName);
free(escCatName);
}
STRCPY_FIXED(scmName1, "n2.nspname");
diff --git a/misc.c b/misc.c
index 55d72cec..66a5a364 100644
--- a/misc.c
+++ b/misc.c
@@ -119,9 +119,20 @@ make_string(const SQLCHAR *s, SQLINTEGER len, char *buf, size_t bufsize)
MYLOG(0, "invalid length=" FORMAT_INTEGER "\n", len);
return NULL;
}
+ /*
+ * A counted string need not be null terminated, so copy exactly
+ * length bytes and terminate the copy ourselves instead of using
+ * strncpy_null(), which would read s[length] and beyond.
+ */
if (buf)
{
- strncpy_null(buf, (char *) s, bufsize > length ? length + 1 : bufsize);
+ if (bufsize > 0)
+ {
+ if (length >= bufsize)
+ length = bufsize - 1; /* truncated */
+ memcpy(buf, s, length);
+ buf[length] = '\0';
+ }
return buf;
}
@@ -131,7 +142,8 @@ MYLOG(DETAIL_LOG_LEVEL, "str=%p\n", str);
if (!str)
return NULL;
- strncpy_null(str, (char *) s, length + 1);
+ memcpy(str, s, length);
+ str[length] = '\0';
return str;
}
diff --git a/msdtc_enlist.cpp b/msdtc_enlist.cpp
index a6fa51a0..488c305a 100755
--- a/msdtc_enlist.cpp
+++ b/msdtc_enlist.cpp
@@ -714,6 +714,34 @@ HRESULT IAsyncPG::ReleaseConnection(void)
{
isolateXAConn(true, false);
}
+ else if (!isolated && !done && dtcconn)
+ {
+ /*
+ * The session was lost (the connection is no longer CONN_CONNECTED),
+ * and the application is about to free the connection. Detach it,
+ * or AbortRequest, PrepareRequest and SetDone would use the freed
+ * ConnectionClass. Without a connection AbortRequest skips the local
+ * rollback, which the server has already done, and PrepareExec fails
+ * with E_UNEXPECTED, so the global transaction aborts.
+ *
+ * Don't isolate a dead connection instead: getLockedXAConn() would
+ * reconnect the copy, and a one-phase commit on the new session would
+ * report success for work that was lost with the old one.
+ */
+ SLOCK_RELEASE();
+ ELOCK_ACQUIRE();
+ LIFELOCK_ACQUIRE;
+ SLOCK_ACQUIRE();
+ if (!isolated && !done && dtcconn)
+ {
+ mylog("%p->ReleaseConnection detaches the lost connection %p\n", this, dtcconn);
+ PgDtc_set_async(dtcconn, NULL);
+ dtcconn = NULL;
+ }
+ SLOCK_RELEASE();
+ LIFELOCK_RELEASE;
+ ELOCK_RELEASE();
+ }
else
SLOCK_RELEASE();
mylog("%p->ReleaseConnection exit\n", this);
@@ -1299,9 +1327,20 @@ EXTERN_C RETCODE EnlistInDtc(void *conn, void *pTra, int method)
PgDtc_set_property(conn, enlisted, (void *) 0);
return SQL_SUCCESS;
}
+ /*
+ * End the local transaction here, before anything is enlisted, and
+ * refuse to enlist when that fails. PgDtc_set_async() switches
+ * autocommit off once the enlistment is made, which would commit a
+ * transaction still open then, and it cannot report a failed commit.
+ */
if (CONN_IS_IN_TRANS(conn))
{
- PgDtc_one_phase_operation(conn, SHUTDOWN_LOCAL_TRANSACTION);
+ if (!PgDtc_one_phase_operation(conn, SHUTDOWN_LOCAL_TRANSACTION) ||
+ CONN_IS_IN_TRANS(conn))
+ {
+ PgDtc_set_error(conn, "enlistment error:could not end the local transaction", __FUNCTION__);
+ return SQL_ERROR;
+ }
}
HRESULT hres;
pDtc = getITransactionDispenser(OLE_TM_FLAG_NODEMANDSTART, &hres);
diff --git a/multibyte.c b/multibyte.c
index 980fb0ed..1b61b203 100644
--- a/multibyte.c
+++ b/multibyte.c
@@ -479,6 +479,7 @@ derive_locale_encoding(const char *dbencoding)
int acp;
#else
const char *loc, *ptr;
+ char locbuf[128];
#endif /* WIN32 */
if (wenc = getenv("PGCLIENTENCODING"), NULL != wenc) /* environmnt variable */
@@ -542,9 +543,24 @@ derive_locale_encoding(const char *dbencoding)
#else
/*
* Derive the encoding from the codeset part of the current locale.
+ * Don't call setlocale(LC_CTYPE, ""): that changes the locale of
+ * the whole process and races with other threads. Query the
+ * application's locale instead and copy it at once; if it names no
+ * codeset (e.g. "C", the default when the application never set a
+ * locale), look at the environment variables setlocale() would use.
*/
- loc = setlocale(LC_CTYPE, "");
- if (loc && (ptr = strchr(loc, '.')))
+ locbuf[0] = '\0';
+ if ((loc = setlocale(LC_CTYPE, NULL)) != NULL)
+ strncpy_null(locbuf, loc, sizeof(locbuf));
+ if (NULL == strchr(locbuf, '.'))
+ {
+ if (((loc = getenv("LC_ALL")) != NULL && loc[0]) ||
+ ((loc = getenv("LC_CTYPE")) != NULL && loc[0]) ||
+ ((loc = getenv("LANG")) != NULL && loc[0]))
+ strncpy_null(locbuf, loc, sizeof(locbuf));
+ }
+ loc = locbuf;
+ if ((ptr = strchr(loc, '.')) != NULL)
{
int enc_no;
diff --git a/mylog.c b/mylog.c
index 50ec8012..02f8165e 100644
--- a/mylog.c
+++ b/mylog.c
@@ -185,7 +185,7 @@ const char *GetExeProgramName()
for (i = 0; i < sizeof(flist) / sizeof(flist[0]); i++)
{
- ssize_t len = readlink(flist[i], path_name, sizeof(path_name));
+ ssize_t len = readlink(flist[i], path_name, sizeof(path_name) - 1);
if (len > 0)
{
path_name[len] = '\0';
diff --git a/odbcapi.c b/odbcapi.c
index 9eeae2b8..ff0763d8 100644
--- a/odbcapi.c
+++ b/odbcapi.c
@@ -1167,7 +1167,7 @@ SQLExtendedFetch(HSTMT hstmt,
StartRollbackState(stmt);
#ifdef WITH_UNIXODBC
{
- SQLULEN retrieved;
+ SQLULEN retrieved = 0;
ret = PGAPI_ExtendedFetch(hstmt, fFetchType, irow, &retrieved, rgfRowStatus, 0, SC_get_ARDF(stmt)->size_of_rowset_odbc2);
if (pcrow)
diff --git a/odbcapi30.c b/odbcapi30.c
index f12eba2b..bf1c46a1 100644
--- a/odbcapi30.c
+++ b/odbcapi30.c
@@ -157,7 +157,9 @@ SQLCopyDesc(SQLHDESC SourceDescHandle,
RETCODE ret;
MYLOG(0, "Entering\n");
+ DescLockHandle(SourceDescHandle, TargetDescHandle);
ret = PGAPI_CopyDesc(SourceDescHandle, TargetDescHandle);
+ DescUnlockHandle(SourceDescHandle, TargetDescHandle);
return ret;
}
@@ -288,7 +290,16 @@ SQLFreeHandle(SQLSMALLINT HandleType, SQLHANDLE Handle)
break;
case SQL_HANDLE_DESC:
- ret = PGAPI_FreeDesc(Handle);
+ {
+ /* an explicit descriptor is freed, an implicit one is not */
+ BOOL embedded = Handle && DC_get_embedded((DescriptorClass *) Handle);
+
+ if (embedded)
+ DescLockHandle(Handle, NULL);
+ ret = PGAPI_FreeDesc(Handle);
+ if (embedded)
+ DescUnlockHandle(Handle, NULL);
+ }
break;
default:
ret = SQL_ERROR;
@@ -308,8 +319,10 @@ SQLGetDescField(SQLHDESC DescriptorHandle,
RETCODE ret;
MYLOG(0, "Entering\n");
+ DescLockHandle(DescriptorHandle, NULL);
ret = PGAPI_GetDescField(DescriptorHandle, RecNumber, FieldIdentifier,
Value, BufferLength, StringLength);
+ DescUnlockHandle(DescriptorHandle, NULL);
return ret;
}
@@ -355,9 +368,11 @@ SQLGetDescRec(SQLHDESC DescriptorHandle,
MYLOG(0, "Entering h=%p rec=%d name=%p blen=%d\n", DescriptorHandle, RecNumber, Name, BufferLength);
MYLOG(0, "str=%p type=%p sub=%p len=%p prec=%p scale=%p null=%p\n", StringLength, Type, SubType, Length, Precision, Scale, Nullable);
+ DescLockHandle(DescriptorHandle, NULL);
ret = PGAPI_GetDescRec(DescriptorHandle, RecNumber, Name, BufferLength,
StringLength, Type, SubType, Length, Precision,
Scale, Nullable);
+ DescUnlockHandle(DescriptorHandle, NULL);
return ret;
}
@@ -372,8 +387,10 @@ SQLGetDiagField(SQLSMALLINT HandleType, SQLHANDLE Handle,
RETCODE ret;
MYLOG(0, "Entering Handle=(%u,%p) Rec=%d Id=%d info=(%p,%d)\n", HandleType, Handle, RecNumber, DiagIdentifier, DiagInfo, BufferLength);
+ DiagLockHandle(HandleType, Handle);
ret = PGAPI_GetDiagField(HandleType, Handle, RecNumber, DiagIdentifier,
DiagInfo, BufferLength, StringLength);
+ DiagUnlockHandle(HandleType, Handle);
return ret;
}
@@ -387,8 +404,10 @@ SQLGetDiagRec(SQLSMALLINT HandleType, SQLHANDLE Handle,
RETCODE ret;
MYLOG(0, "Entering\n");
+ DiagLockHandle(HandleType, Handle);
ret = PGAPI_GetDiagRec(HandleType, Handle, RecNumber, Sqlstate,
NativeError, MessageText, BufferLength, TextLength);
+ DiagUnlockHandle(HandleType, Handle);
return ret;
}
#endif /* UNICODE_SUPPORTXX */
@@ -543,8 +562,10 @@ SQLSetDescField(SQLHDESC DescriptorHandle,
MYLOG(0, "Entering h=%p rec=%d field=%d val=%p\n", DescriptorHandle, RecNumber, FieldIdentifier, Value);
+ DescLockHandle(DescriptorHandle, NULL);
ret = PGAPI_SetDescField(DescriptorHandle, RecNumber, FieldIdentifier,
Value, BufferLength);
+ DescUnlockHandle(DescriptorHandle, NULL);
return ret;
}
@@ -591,9 +612,11 @@ SQLSetDescRec(SQLHDESC DescriptorHandle,
MYLOG(0, "Entering h=%p rec=%d type=%d sub=%d len=" FORMAT_LEN " prec=%d scale=%d data=%p\n", DescriptorHandle, RecNumber, Type, SubType, Length, Precision, Scale, Data);
MYLOG(0, "str=%p ind=%p\n", StringLength, Indicator);
+ DescLockHandle(DescriptorHandle, NULL);
ret = PGAPI_SetDescRec(DescriptorHandle, RecNumber, Type,
SubType, Length, Precision, Scale, Data,
StringLength, Indicator);
+ DescUnlockHandle(DescriptorHandle, NULL);
return ret;
}
diff --git a/odbcapi30w.c b/odbcapi30w.c
index dfe6916b..e5aadf76 100644
--- a/odbcapi30w.c
+++ b/odbcapi30w.c
@@ -16,6 +16,7 @@
#include "unicode_support.h"
#include <stdio.h>
#include <string.h>
+#include <limits.h>
#include "pgapifunc.h"
#include "connection.h"
@@ -226,8 +227,10 @@ SQLSetDescFieldW(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber,
vallen = BufferLength;
}
+ DescLockHandle(DescriptorHandle, NULL);
ret = PGAPI_SetDescField(DescriptorHandle, RecNumber, FieldIdentifier,
uval, (SQLINTEGER) vallen);
+ DescUnlockHandle(DescriptorHandle, NULL);
/* Free the converted string if we allocated one */
if (val_alloced)
@@ -270,7 +273,9 @@ SQLGetDescFieldW(SQLHDESC hdesc, SQLSMALLINT iRecord, SQLSMALLINT iField,
break;
}
rgbV = rgbVt;
+ DescLockHandle(hdesc, NULL);
ret = PGAPI_GetDescField(hdesc, iRecord, iField, rgbV, bMax, pcbV);
+ DescUnlockHandle(hdesc, NULL);
if (SQL_SUCCESS_WITH_INFO != ret || blen < bMax)
break;
}
@@ -293,13 +298,64 @@ SQLGetDescFieldW(SQLHDESC hdesc, SQLSMALLINT iRecord, SQLSMALLINT iField,
rgbV = rgbValue;
bMax = cbValueMax;
pcbV = pcbValue;
+ DescLockHandle(hdesc, NULL);
ret = PGAPI_GetDescField(hdesc, iRecord, iField, rgbV, bMax, pcbV);
+ DescUnlockHandle(hdesc, NULL);
break;
}
return ret;
}
+/*
+ * PGAPI_GetDiagRec() and PGAPI_GetDiagField() divide a long message text
+ * into pieces by byte count (see ER_ReturnError()), so the piece returned
+ * in a buffer of bufsize bytes may begin or end in the middle of a UTF-8
+ * character, which utf8_to_ucs2_lf() rejects as a whole when errcheck is
+ * TRUE. Skip such partial characters at both ends of the piece: a
+ * character that straddles two pieces is dropped, not the whole piece.
+ */
+static const char *
+skip_partial_utf8(const char *str, SQLSMALLINT *len, SQLSMALLINT bufsize)
+{
+ const UCHAR *s = (const UCHAR *) str;
+ SQLSMALLINT n = *len, i, clen;
+ BOOL cut = FALSE;
+
+ /* the buffer holds at most bufsize - 1 bytes and the terminator */
+ if (n >= bufsize - 1)
+ {
+ n = bufsize - 1;
+ cut = TRUE; /* the end of the piece was cut by the byte count */
+ }
+ if (n < 0)
+ n = 0;
+ /* the rest of a character which began in the previous piece */
+ for (i = 0; i < n && i < 3 && 0x80 == (s[i] & 0xc0); i++)
+ ;
+ s += i;
+ n -= i;
+ /* a character which continues in the next piece */
+ for (i = n - 1; cut && i >= 0 && i >= n - 3; i--)
+ {
+ if (0x80 == (s[i] & 0xc0))
+ continue;
+ if (0xf0 == (s[i] & 0xf8))
+ clen = 4;
+ else if (0xe0 == (s[i] & 0xf0))
+ clen = 3;
+ else if (0xc0 == (s[i] & 0xe0))
+ clen = 2;
+ else
+ clen = 1;
+ if (i + clen > n)
+ n = i;
+ break;
+ }
+ *len = n;
+ return (const char *) s;
+}
+
RETCODE SQL_API
SQLGetDiagRecW(SQLSMALLINT fHandleType,
SQLHANDLE handle,
@@ -316,20 +372,26 @@ SQLGetDiagRecW(SQLSMALLINT fHandleType,
MYLOG(0, "Entering\n");
buflen = 0;
+ tlen = 0;
if (szErrorMsg && cbErrorMsgMax > 0)
{
+ if (NULL == (mtxt = malloc(cbErrorMsgMax)))
+ return SQL_ERROR;
buflen = cbErrorMsgMax;
- mtxt = malloc(buflen);
}
+ DiagLockHandle(fHandleType, handle);
ret = PGAPI_GetDiagRec(fHandleType, handle, iRecord, (SQLCHAR *) qstr_ansi,
pfNativeError, (SQLCHAR *) mtxt, buflen, &tlen);
+ DiagUnlockHandle(fHandleType, handle);
if (SQL_SUCCEEDED(ret))
{
if (szSqlState)
utf8_to_ucs2(qstr_ansi, -1, szSqlState, 6);
if (mtxt && tlen <= cbErrorMsgMax)
{
- SQLULEN ulen = utf8_to_ucs2_lf(mtxt, tlen, FALSE, szErrorMsg, cbErrorMsgMax, TRUE);
+ SQLSMALLINT wlen = tlen;
+ const char *whole = skip_partial_utf8(mtxt, &wlen, buflen);
+ SQLULEN ulen = utf8_to_ucs2_lf(whole, wlen, FALSE, szErrorMsg, cbErrorMsgMax, TRUE);
if (ulen == (SQLULEN) -1)
tlen = (SQLSMALLINT) locale_to_sqlwchar((SQLWCHAR *) szErrorMsg, mtxt, cbErrorMsgMax, FALSE);
else
@@ -396,10 +458,25 @@ SQLColAttributeW(SQLHSTMT hstmt,
case SQL_DESC_TABLE_NAME:
case SQL_DESC_TYPE_NAME:
case SQL_COLUMN_NAME:
- bMax = cbCharAttrMax * 3 / WCLEN;
- rgbD = malloc(bMax);
+ /*
+ * The buffer length and the returned length of
+ * PGAPI_ColAttributes are SQLSMALLINT, so the scratch buffer
+ * never holds more than SHRT_MAX bytes; a longer name from
+ * the server is truncated.
+ */
+ if (cbCharAttrMax < 0)
+ {
+ SC_set_error(stmt, STMT_INVALID_BUFFER_LENGTH, "Invalid string or buffer length", func);
+ ret = SQL_ERROR;
+ break;
+ }
+ if (cbCharAttrMax < SHRT_MAX / 3)
+ bMax = cbCharAttrMax * 3 / WCLEN;
+ else
+ bMax = SHRT_MAX;
+ rgbD = malloc(bMax > 0 ? bMax : 1);
rgbL = &blen;
- for (rgbDt = rgbD;; bMax = blen + 1, rgbDt = realloc(rgbD, bMax))
+ for (rgbDt = rgbD;; bMax = (blen < SHRT_MAX ? blen + 1 : SHRT_MAX), rgbDt = realloc(rgbD, bMax))
{
if (!rgbDt)
{
@@ -407,14 +484,26 @@ SQLColAttributeW(SQLHSTMT hstmt,
break;
}
rgbD = rgbDt;
+ blen = 0;
ret = PGAPI_ColAttributes(hstmt, iCol, iField, rgbD,
bMax, rgbL, pNumAttr);
- if (SQL_SUCCESS_WITH_INFO != ret || blen < bMax)
+ if (SQL_SUCCESS_WITH_INFO != ret || (blen >= 0 && blen < bMax) || bMax >= SHRT_MAX)
break;
}
if (SQL_SUCCEEDED(ret))
{
+ if (blen < 0 || blen >= bMax)
+ blen = (bMax > 0) ? bMax - 1 : 0;
blen = (SQLSMALLINT) utf8_to_ucs2(rgbD, blen, (SQLWCHAR *) pCharAttr, cbCharAttrMax / WCLEN);
+ if (blen < 0) /* not valid UTF-8 */
+ {
+ blen = 0;
+ if (pCharAttr && cbCharAttrMax >= (SQLSMALLINT) WCLEN)
+ *((SQLWCHAR *) pCharAttr) = 0;
+ }
+ /* the length is returned in bytes and must fit in a SQLSMALLINT */
+ if (blen > SHRT_MAX / WCLEN)
+ blen = SHRT_MAX / WCLEN;
/* in characters: an odd byte count holds whole ones only */
if (SQL_SUCCESS == ret && blen >= cbCharAttrMax / WCLEN)
{
@@ -465,11 +554,23 @@ SQLGetDiagFieldW(SQLSMALLINT fHandleType,
case SQL_DIAG_SERVER_NAME:
case SQL_DIAG_SQLSTATE:
case SQL_DIAG_SUBCLASS_ORIGIN:
- bMax = cbDiagInfoMax * 3 / WCLEN + 1;
+ if (cbDiagInfoMax < 0)
+ return SQL_ERROR;
+ /*
+ * The length of a record is returned in bytes in a
+ * SQLSMALLINT, so keep the record that ER_ReturnError
+ * adopts from this request small enough for blen * WCLEN
+ * to fit; this also keeps bMax from wrapping. The rest of a
+ * longer message comes back as the following records.
+ */
+ if (cbDiagInfoMax < SHRT_MAX / 3)
+ bMax = cbDiagInfoMax * 3 / WCLEN + 1;
+ else
+ bMax = SHRT_MAX / WCLEN;
if (rgbD = malloc(bMax), !rgbD)
return SQL_ERROR;
rgbL = &blen;
- for (rgbDt = rgbD;; bMax = blen + 1, rgbDt = realloc(rgbD, bMax))
+ for (rgbDt = rgbD;; bMax = (blen < SHRT_MAX ? blen + 1 : SHRT_MAX), rgbDt = realloc(rgbD, bMax))
{
if (!rgbDt)
{
@@ -477,21 +578,41 @@ SQLGetDiagFieldW(SQLSMALLINT fHandleType,
return SQL_ERROR;
}
rgbD = rgbDt;
+ blen = 0;
+ DiagLockHandle(fHandleType, handle);
ret = PGAPI_GetDiagField(fHandleType, handle, iRecord, fDiagField, rgbD,
bMax, rgbL);
- if (SQL_SUCCESS_WITH_INFO != ret || blen < bMax)
+ DiagUnlockHandle(fHandleType, handle);
+ if (SQL_SUCCESS_WITH_INFO != ret || (blen >= 0 && blen < bMax) || bMax >= SHRT_MAX)
break;
}
if (SQL_SUCCEEDED(ret))
{
- SQLULEN ulen = (SQLSMALLINT) utf8_to_ucs2_lf(rgbD, blen, FALSE, (SQLWCHAR *) rgbDiagInfo, cbDiagInfoMax / WCLEN, TRUE);
+ SQLULEN ulen;
+ SQLSMALLINT wlen;
+ const char *whole;
+
+ if (blen < 0 || blen >= bMax)
+ blen = bMax - 1;
+ wlen = blen;
+ whole = skip_partial_utf8(rgbD, &wlen, bMax);
+ ulen = utf8_to_ucs2_lf(whole, wlen, FALSE, (SQLWCHAR *) rgbDiagInfo, cbDiagInfoMax / WCLEN, TRUE);
if (ulen == (SQLULEN) -1)
blen = (SQLSMALLINT) locale_to_sqlwchar((SQLWCHAR *) rgbDiagInfo, rgbD, cbDiagInfoMax / WCLEN, FALSE);
else
{
ucs2_terminate_output((SQLWCHAR *) rgbDiagInfo, cbDiagInfoMax / WCLEN, ulen);
- blen = (SQLSMALLINT) ulen;
+ blen = (SQLSMALLINT) (ulen > SHRT_MAX ? SHRT_MAX : ulen);
+ }
+ if (blen < 0) /* neither UTF-8 nor the locale encoding */
+ {
+ blen = 0;
+ if (rgbDiagInfo && cbDiagInfoMax >= (SQLSMALLINT) WCLEN)
+ *((SQLWCHAR *) rgbDiagInfo) = 0;
}
+ /* the length is returned in bytes and must fit in a SQLSMALLINT */
+ if (blen > SHRT_MAX / WCLEN)
+ blen = SHRT_MAX / WCLEN;
/* in characters: an odd byte count holds whole ones only */
if (SQL_SUCCESS == ret && blen >= cbDiagInfoMax / WCLEN)
ret = SQL_SUCCESS_WITH_INFO;
@@ -507,8 +628,10 @@ SQLGetDiagFieldW(SQLSMALLINT fHandleType,
rgbD = rgbDiagInfo;
bMax = cbDiagInfoMax;
rgbL = pcbDiagInfo;
+ DiagLockHandle(fHandleType, handle);
ret = PGAPI_GetDiagField(fHandleType, handle, iRecord, fDiagField, rgbD,
bMax, rgbL);
+ DiagUnlockHandle(fHandleType, handle);
break;
}
@@ -547,28 +670,46 @@ SQLGetDescRecW(SQLHDESC DescriptorHandle,
SQLSMALLINT *Scale, SQLSMALLINT *Nullable)
{
RETCODE ret;
- char *NameA = NULL; /* Temporary buffer for ANSI version of name */
- SQLSMALLINT nlen; /* Length of the name string */
+ char *NameA = NULL; /* Temporary buffer for the UTF-8 version of name */
+ SQLSMALLINT nlen = 0; /* Length of the name string */
+ SQLSMALLINT buflen = 0; /* Size of NameA in bytes */
MYLOG(0, "Entering h=%p rec=%d name=%p blen=%d\n", DescriptorHandle, RecNumber, Name, BufferLength);
MYLOG(0, "str=%p type=%p sub=%p len=%p prec=%p scale=%p null=%p\n", StringLength, Type, SubType, Length, Precision, Scale, Nullable);
- /* Allocate temporary buffer for ANSI version if buffer length is provided */
- if (BufferLength > 0)
- NameA = malloc(BufferLength);
+ /*
+ * Allocate a temporary buffer for the UTF-8 version of the name. A
+ * UCS-2 character takes up to 3 bytes in UTF-8.
+ */
+ if (Name && BufferLength > 0)
+ {
+ buflen = (BufferLength < SHRT_MAX / 3) ? BufferLength * 3 : SHRT_MAX;
+ if (NULL == (NameA = malloc(buflen)))
+ {
+ DC_set_error((DescriptorClass *) DescriptorHandle, DESC_NO_MEMORY_ERROR, "Could not allocate memory for the name");
+ return SQL_ERROR;
+ }
+ NameA[0] = '\0';
+ }
- /* Call the core implementation with ANSI parameters */
- ret = PGAPI_GetDescRec(DescriptorHandle, RecNumber, (SQLCHAR *) NameA, BufferLength,
+ /* Call the core implementation with UTF-8 parameters */
+ DescLockHandle(DescriptorHandle, NULL);
+ ret = PGAPI_GetDescRec(DescriptorHandle, RecNumber, (SQLCHAR *) NameA, buflen,
&nlen, Type, SubType, Length, Precision,
Scale, Nullable);
if (SQL_SUCCEEDED(ret))
{
- /* Convert ANSI name to Unicode if we have a valid name and buffer */
- if (NameA && nlen <= BufferLength)
+ /* Convert the name to Unicode; NameA holds at most buflen - 1 bytes */
+ if (NameA)
{
+ SQLULEN ulen;
+
+ if (nlen < 0 || nlen >= buflen)
+ nlen = (SQLSMALLINT) strlen(NameA);
+
/* Try UTF-8 to UCS-2 conversion first */
- SQLULEN ulen = utf8_to_ucs2_lf(NameA, nlen, FALSE, Name, BufferLength, TRUE);
+ ulen = utf8_to_ucs2_lf(NameA, nlen, FALSE, Name, BufferLength, TRUE);
if (ulen == (SQLULEN) -1)
/* Fall back to locale-based conversion if UTF-8 conversion fails */
@@ -578,16 +719,59 @@ SQLGetDescRecW(SQLHDESC DescriptorHandle,
ucs2_terminate_output(Name, BufferLength, ulen);
nlen = (SQLSMALLINT) ulen;
}
+ if (nlen < 0) /* neither UTF-8 nor the locale encoding */
+ {
+ nlen = 0;
+ Name[0] = 0;
+ }
/* If the name was truncated, return success with info */
if (nlen >= BufferLength)
ret = SQL_SUCCESS_WITH_INFO;
}
+ else if (StringLength && nlen > 0)
+ {
+ /*
+ * No buffer was given, so the call converted no character
+ * and nlen is still the name's length in UTF-8 bytes. The
+ * caller asking
+ * how long the name is must be told in characters, as the
+ * call with a buffer reports, or it sizes that buffer in the
+ * wrong unit. Fetch the name into a buffer of our own to
+ * count them.
+ */
+ char *cntbuf = malloc((size_t) nlen + 1);
+
+ if (cntbuf)
+ {
+ SQLSMALLINT cntlen = 0;
+
+ if (SQL_SUCCEEDED(PGAPI_GetDescRec(DescriptorHandle,
+ RecNumber, (SQLCHAR *) cntbuf,
+ (SQLSMALLINT) (nlen + 1), &cntlen,
+ NULL, NULL, NULL, NULL, NULL, NULL)))
+ {
+ SQLULEN ulen = utf8_to_ucs2_lf(cntbuf, cntlen, FALSE,
+ NULL, 0, TRUE);
+
+ if (ulen != (SQLULEN) -1)
+ nlen = (SQLSMALLINT) ulen;
+ }
+ free(cntbuf);
+ }
+ }
+
/* Return the actual string length if the caller wants it */
if (StringLength)
*StringLength = nlen;
}
+ /*
+ * Held until here: the character-counting call above reaches the
+ * statement that owns an IRD, which is what this lock protects from a
+ * concurrent SQLFreeStmt.
+ */
+ DescUnlockHandle(DescriptorHandle, NULL);
/* Clean up the temporary buffer */
if (NameA)
@@ -645,9 +829,11 @@ SQLSetDescRecW(SQLHDESC DescriptorHandle,
* point does; the bound buffer's encoding is interpreted by its C type
* at use time, not re-encoded here.
*/
+ DescLockHandle(DescriptorHandle, NULL);
ret = PGAPI_SetDescRec(DescriptorHandle, RecNumber, Type,
SubType, Length, Precision, Scale, Data,
StringLength, Indicator);
+ DescUnlockHandle(DescriptorHandle, NULL);
return ret;
}
diff --git a/odbcapiw.c b/odbcapiw.c
index c10dc843..c8b68de6 100644
--- a/odbcapiw.c
+++ b/odbcapiw.c
@@ -293,8 +293,15 @@ SQLDescribeColW(HSTMT StatementHandle,
if (SC_connection_lost_check(stmt, __FUNCTION__))
return SQL_ERROR;
+ /*
+ * The buffer length and the returned length of PGAPI_DescribeCol are
+ * SQLSMALLINT, so the scratch buffer never holds more than SHRT_MAX
+ * bytes; a longer name from the server is truncated.
+ */
buflen = 0;
- if (BufferLength > 0)
+ if (BufferLength > SHRT_MAX / 3)
+ buflen = SHRT_MAX;
+ else if (BufferLength > 0)
buflen = BufferLength * 3;
else if (NameLength)
buflen = 32;
@@ -303,7 +310,7 @@ SQLDescribeColW(HSTMT StatementHandle,
ENTER_STMT_CS(stmt);
SC_clear_error(stmt);
StartRollbackState(stmt);
- for (;; buflen = nmlen + 1, clNamet = realloc(clName, buflen))
+ for (;; buflen = (nmlen < SHRT_MAX ? nmlen + 1 : SHRT_MAX), clNamet = realloc(clName, buflen))
{
if (!clNamet)
{
@@ -316,15 +323,24 @@ SQLDescribeColW(HSTMT StatementHandle,
(SQLCHAR *) clName, buflen,
&nmlen, DataType, ColumnSize,
DecimalDigits, Nullable);
- if (SQL_SUCCESS_WITH_INFO != ret || nmlen < buflen)
+ if (SQL_SUCCESS_WITH_INFO != ret || (nmlen >= 0 && nmlen < buflen) || buflen >= SHRT_MAX)
break;
}
if (SQL_SUCCEEDED(ret))
{
- SQLLEN nmcount = nmlen;
+ SQLLEN nmcount;
- if (nmlen < buflen)
- nmcount = utf8_to_ucs2(clName, nmlen, ColumnName, BufferLength);
+ if (nmlen < 0 || nmlen >= buflen)
+ nmlen = buflen - 1;
+ nmcount = utf8_to_ucs2(clName, nmlen, ColumnName, BufferLength);
+ if (nmcount < 0) /* not valid UTF-8 */
+ {
+ nmcount = 0;
+ if (ColumnName && BufferLength > 0)
+ ColumnName[0] = 0;
+ }
+ else if (nmcount > SHRT_MAX)
+ nmcount = SHRT_MAX;
/* BufferLength counts the terminator, so an exact fit is cut too */
if (SQL_SUCCESS == ret && BufferLength > 0 && nmcount >= BufferLength)
{
diff --git a/options.c b/options.c
index f099f344..4403c708 100644
--- a/options.c
+++ b/options.c
@@ -374,9 +374,17 @@ PGAPI_SetConnectOption(HDBC hdbc,
break;
else if (!autocomm_on && SQL_AUTOCOMMIT_OFF == conn->autocommit_public)
break;
- conn->autocommit_public = (autocomm_on ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF);
MYLOG(0, "AUTOCOMMIT: transact_status=%d, vparam=" FORMAT_LEN "\n", conn->transact_status, vParam);
+ /*
+ * Every exit below this point reports the attribute as
+ * unchanged, so autocommit_public is assigned only once they
+ * are passed. Assigning it first made the tests above take a
+ * retry for a change already made and return SQL_SUCCESS
+ * without ever switching the mode, so SQLGetConnectAttr,
+ * which reads this field, reported a mode the driver was not
+ * in.
+ */
#ifdef _HANDLE_ENLIST_IN_DTC_
if (CC_is_in_global_trans(conn))
{
@@ -384,7 +392,26 @@ PGAPI_SetConnectOption(HDBC hdbc,
return SQL_ERROR;
}
#endif /* _HANDLE_ENLIST_IN_DTC_ */
- CC_set_autocommit(conn, autocomm_on);
+ /*
+ * Turning autocommit on commits the open transaction. As in
+ * PGAPI_Transact(), that cannot be done once the driver has
+ * given the connection up, so don't report that it was.
+ */
+ if (autocomm_on && CONN_DOWN == conn->status)
+ {
+ CC_set_error(conn, CONNECTION_COMMUNICATION_ERROR, "Could not commit, the connection was lost", func);
+ return SQL_ERROR;
+ }
+ /*
+ * CC_set_autocommit() changes the mode whether or not the
+ * commit it sends succeeds, so the mode holds the requested
+ * value even where it reports the failure. Record it either
+ * way, or an application that reads SQL_ATTR_AUTOCOMMIT back
+ * after the error is told the mode is the one it left.
+ */
+ conn->autocommit_public = (autocomm_on ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF);
+ if (!CC_set_autocommit(conn, autocomm_on))
+ return SQL_ERROR;
break;
case SQL_CURRENT_QUALIFIER: /* ignored */
@@ -417,7 +444,10 @@ PGAPI_SetConnectOption(HDBC hdbc,
if (CC_is_in_trans(conn))
{
if (CC_does_autocommit(conn) && !CC_is_in_error_trans(conn))
- CC_commit(conn);
+ {
+ if (!CC_commit(conn))
+ return SQL_ERROR;
+ }
else
{
CC_set_error(conn, CONN_TRANSACT_IN_PROGRES, "Cannot switch isolation level while a transaction is in progress", func);
@@ -588,6 +618,11 @@ PGAPI_GetConnectOption(HDBC hdbc,
/* char/binary data */
len = strlen(p);
+ if (pvParam && BufferLength < 0)
+ {
+ CC_set_error(conn, CONN_INVALID_BUFFER_LENGTH, "Invalid string or buffer length", func);
+ return SQL_ERROR;
+ }
if (pvParam)
{
#ifdef UNICODE_SUPPORT
diff --git a/parse.c b/parse.c
index c46df215..cfb5a0ff 100644
--- a/parse.c
+++ b/parse.c
@@ -92,7 +92,7 @@ skip_blanks_and_comments(const UCHAR *tstr)
for (;;)
{
- if (isspace(*tstr))
+ if (isspace((UCHAR) *tstr))
tstr++;
else if ('-' == tstr[0] && '-' == tstr[1])
{
@@ -646,12 +646,20 @@ void SC_initialize_cols_info(StatementClass *stmt, BOOL DCdestroy, BOOL parseRes
* may be revived later by SC_describe_ok()) must not keep
* pointing at the TABLE_INFOs freed here.
*/
+ ConnectionClass *conn = SC_get_conn(stmt);
+ int entered = 0;
+
for (i = 0; fi && i < (int) irdflds->allocated; i++)
{
if (fi[i])
fi[i]->ti = NULL;
}
+ /* the refcnt of the connection's column info, see getCOLIfromTI() */
+ if (conn)
+ ENTER_INNER_CONN_CS(conn, entered);
TI_Destructor(stmt->ti, stmt->ntab);
+ if (conn)
+ CLEANUP_FUNC_CONN_CS(entered, conn);
free(stmt->ti);
stmt->ti = NULL;
}
@@ -881,8 +889,8 @@ getCOLIfromTable(ConnectionClass *conn, StatementClass *stmt, pgNAME *schema_nam
return FALSE;
SPRINTF_FIXED(token,
"select nspname from pg_namespace n, pg_class c"
- " where c.relnamespace=n.oid and c.oid='%s'::regclass",
- escaped);
+ " where c.relnamespace=n.oid and c.oid=%s'%s'::regclass",
+ CC_literal_prefix(conn), escaped);
/*
* The statement and ROLLBACK_ON_ERROR give this probe a savepoint
* of its own. Without them a name that is not a relation the role
@@ -1146,6 +1154,7 @@ BOOL getCOLIfromTI(const char *func, ConnectionClass *conn, StatementClass *stmt
OID greloid = reloid;
TABLE_INFO *wti = *pti;
COL_INFO *coli;
+ int entered = 0;
MYLOG(DETAIL_LOG_LEVEL, "entering reloid=%u ti=%p\n", reloid, wti);
if (!conn)
@@ -1177,6 +1186,13 @@ MYLOG(DETAIL_LOG_LEVEL, "before increaseNtab\n");
}
*pti = wti;
}
+ /*
+ * The column info cache (conn->col_info, ntables and the refcnt of
+ * each entry) belongs to the connection, and statements of other
+ * threads look up, add, recycle and free its entries. It is read and
+ * changed only under the connection lock, up to the return.
+ */
+ ENTER_INNER_CONN_CS(conn, entered);
MYLOG(DETAIL_LOG_LEVEL, "fi=%p greloid=%d col_info=%p\n", wti, greloid, wti->col_info);
if (0 == greloid)
greloid = wti->table_oid;
@@ -1211,7 +1227,7 @@ MYLOG(DETAIL_LOG_LEVEL, "fi=%p greloid=%d col_info=%p\n", wti, greloid, wti->col
SC_set_error(stmt, STMT_EXEC_ERROR, "Table not found", func);
SC_reset_updatable(stmt);
}
- return FALSE;
+ goto leave;
}
else if (NULL != coli)
{
@@ -1253,6 +1269,8 @@ MYLOG(DETAIL_LOG_LEVEL, "#1 %p->table_name=%s(%u)\n", wti, PRINT_NAME(wti->table
}
else if (!colatt && stmt)
SC_set_parse_status(stmt, STMT_PARSE_FATAL);
+leave:
+ CLEANUP_FUNC_CONN_CS(entered, conn);
MYLOG(DETAIL_LOG_LEVEL, "leaving returns %d\n", found);
return found;
}
diff --git a/pgapi30.c b/pgapi30.c
index 72a43cb4..de643882 100644
--- a/pgapi30.c
+++ b/pgapi30.c
@@ -19,6 +19,9 @@
#include <stdio.h>
#include <string.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdint.h>
#include "environ.h"
@@ -31,6 +34,130 @@
#include "dlg_specific.h"
+/*
+ * SQLGetDiagRec and SQLGetDiagField read the errors a statement or a
+ * connection holds, which a call running on another thread may clear,
+ * free or replace. Take the handle's lock around them, as the other
+ * entry points do, but without clearing its errors. Environment and
+ * descriptor handles are not locked here.
+ */
+void
+DiagLockHandle(SQLSMALLINT HandleType, SQLHANDLE Handle)
+{
+ if (NULL == Handle)
+ return;
+ switch (HandleType)
+ {
+ case SQL_HANDLE_DBC:
+ ENTER_CONN_CS((ConnectionClass *) Handle);
+ break;
+ case SQL_HANDLE_STMT:
+ ENTER_STMT_CS((StatementClass *) Handle);
+ break;
+ }
+}
+
+void
+DiagUnlockHandle(SQLSMALLINT HandleType, SQLHANDLE Handle)
+{
+ if (NULL == Handle)
+ return;
+ switch (HandleType)
+ {
+ case SQL_HANDLE_DBC:
+ LEAVE_CONN_CS((ConnectionClass *) Handle);
+ break;
+ case SQL_HANDLE_STMT:
+ LEAVE_STMT_CS((StatementClass *) Handle);
+ break;
+ }
+}
+
+/*
+ * The statement an implicit descriptor (the ARD, APD, IRD or IPD that
+ * the driver allocates with a statement) belongs to, or NULL for an
+ * explicit descriptor, which may be attached to any number of statements.
+ */
+static StatementClass *
+desc_owner_stmt(SQLHDESC hdesc)
+{
+ DescriptorClass *desc = (DescriptorClass *) hdesc;
+ char *p = (char *) desc;
+
+ if (NULL == desc || !DC_get_embedded(desc))
+ return NULL;
+ switch (desc->deschd.desc_type)
+ {
+ case SQL_ATTR_APP_ROW_DESC:
+ return (StatementClass *) (p - offsetof(StatementClass, ardi));
+ case SQL_ATTR_APP_PARAM_DESC:
+ return (StatementClass *) (p - offsetof(StatementClass, apdi));
+ case SQL_ATTR_IMP_ROW_DESC:
+ return (StatementClass *) (p - offsetof(StatementClass, irdi));
+ case SQL_ATTR_IMP_PARAM_DESC:
+ return (StatementClass *) (p - offsetof(StatementClass, ipdi));
+ }
+ return NULL;
+}
+
+/* the owners of one or two descriptors, distinct, in address order */
+static void
+desc_owners(SQLHDESC a, SQLHDESC b, StatementClass **first, StatementClass **second)
+{
+ StatementClass *s1 = desc_owner_stmt(a), *s2 = desc_owner_stmt(b);
+
+ if (s1 == s2)
+ s2 = NULL;
+ if (NULL == s1)
+ {
+ s1 = s2;
+ s2 = NULL;
+ }
+ else if (NULL != s2 && (uintptr_t) s2 < (uintptr_t) s1)
+ {
+ StatementClass *t = s1;
+
+ s1 = s2;
+ s2 = t;
+ }
+ *first = s1;
+ *second = s2;
+}
+
+/*
+ * The descriptor exports change a statement's bindings, which a call on
+ * that statement running on another thread (SQLFetch, SQLExecute) may be
+ * reading. For an implicit descriptor, take its statement's lock around
+ * them. An explicit descriptor is not locked: it has no single owner,
+ * and the application must not change it while a statement it is
+ * attached to is in a call on another thread. hdesc2 is the second
+ * descriptor of SQLCopyDesc, or NULL; two statements are locked in
+ * address order.
+ */
+void
+DescLockHandle(SQLHDESC hdesc, SQLHDESC hdesc2)
+{
+ StatementClass *s1, *s2;
+
+ desc_owners(hdesc, hdesc2, &s1, &s2);
+ if (s1)
+ ENTER_STMT_CS(s1);
+ if (s2)
+ ENTER_STMT_CS(s2);
+}
+
+void
+DescUnlockHandle(SQLHDESC hdesc, SQLHDESC hdesc2)
+{
+ StatementClass *s1, *s2;
+
+ desc_owners(hdesc, hdesc2, &s1, &s2);
+ if (s2)
+ LEAVE_STMT_CS(s2);
+ if (s1)
+ LEAVE_STMT_CS(s1);
+}
+
/* SQLError -> SQLDiagRec */
RETCODE SQL_API
PGAPI_GetDiagRec(SQLSMALLINT HandleType, SQLHANDLE Handle,
@@ -637,6 +764,19 @@ ARDSetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
bookmark->used = Value;
break;
case SQL_DESC_OCTET_LENGTH:
+ /*
+ * For SQL_C_VARBOOKMARK this is also the row stride of
+ * column-wise binding, so a negative one would write
+ * rows before the buffer. PGAPI_BindCol refuses it, and
+ * this way in must refuse it too.
+ */
+ if (CAST_PTR(SQLLEN, Value) < 0)
+ {
+ DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER,
+ "invalid descriptor octet length");
+ ret = SQL_ERROR;
+ break;
+ }
bookmark->buflen = CAST_PTR(SQLLEN, Value);
break;
case SQL_DESC_PRECISION:
@@ -1214,6 +1354,7 @@ ARDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
ival = opts->allocated;
break;
case SQL_DESC_OCTET_LENGTH:
+ rettype = SQL_IS_LEN;
ival = opts->bindings[row_idx].buflen;
break;
case SQL_DESC_ALLOC_TYPE: /* read-only */
@@ -1240,9 +1381,14 @@ ARDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
ret = SQL_ERROR;
DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER,
"invalid descriptor identifier");
+ return ret;
}
switch (rettype)
{
+ case SQL_IS_LEN:
+ len = sizeof(SQLLEN);
+ *((SQLLEN *) Value) = ival;
+ break;
case 0:
case SQL_IS_INTEGER:
len = sizeof(SQLINTEGER);
@@ -1360,6 +1506,7 @@ APDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
ptr = opts->parameters[para_idx].indicator;
break;
case SQL_DESC_OCTET_LENGTH:
+ rettype = SQL_IS_LEN;
ival = opts->parameters[para_idx].buflen;
break;
case SQL_DESC_OCTET_LENGTH_PTR:
@@ -1393,6 +1540,7 @@ APDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
default:ret = SQL_ERROR;
DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER,
"invalid descriptor identifier");
+ return ret;
}
switch (rettype)
{
@@ -1446,18 +1594,12 @@ IRDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
rettype = SQL_IS_SMALLINT;
ival = SQL_DESC_ALLOC_AUTO;
break;
+ /* SQLSMALLINT fields */
case SQL_DESC_COUNT: /* read-only */
- case SQL_DESC_AUTO_UNIQUE_VALUE: /* read-only */
- case SQL_DESC_CASE_SENSITIVE: /* read-only */
case SQL_DESC_CONCISE_TYPE: /* read-only */
case SQL_DESC_DATETIME_INTERVAL_CODE: /* read-only */
- case SQL_DESC_DATETIME_INTERVAL_PRECISION: /* read-only */
- case SQL_DESC_DISPLAY_SIZE: /* read-only */
case SQL_DESC_FIXED_PREC_SCALE: /* read-only */
- case SQL_DESC_LENGTH: /* read-only */
case SQL_DESC_NULLABLE: /* read-only */
- case SQL_DESC_NUM_PREC_RADIX: /* read-only */
- case SQL_DESC_OCTET_LENGTH: /* read-only */
case SQL_DESC_PRECISION: /* read-only */
case SQL_DESC_ROWVER: /* read-only */
case SQL_DESC_SCALE: /* read-only */
@@ -1466,6 +1608,21 @@ IRDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
case SQL_DESC_UNNAMED: /* read-only */
case SQL_DESC_UNSIGNED: /* read-only */
case SQL_DESC_UPDATABLE: /* read-only */
+ rettype = SQL_IS_SMALLINT;
+ bCallColAtt = TRUE;
+ break;
+ /* pointer-sized fields: SQLULEN for LENGTH, SQLLEN for the rest */
+ case SQL_DESC_DISPLAY_SIZE: /* read-only */
+ case SQL_DESC_LENGTH: /* read-only */
+ case SQL_DESC_OCTET_LENGTH: /* read-only */
+ rettype = SQL_IS_LEN;
+ bCallColAtt = TRUE;
+ break;
+ /* SQLINTEGER fields */
+ case SQL_DESC_AUTO_UNIQUE_VALUE: /* read-only */
+ case SQL_DESC_CASE_SENSITIVE: /* read-only */
+ case SQL_DESC_DATETIME_INTERVAL_PRECISION: /* read-only */
+ case SQL_DESC_NUM_PREC_RADIX: /* read-only */
bCallColAtt = TRUE;
break;
case SQL_DESC_BASE_COLUMN_NAME: /* read-only */
@@ -1486,6 +1643,7 @@ IRDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
ret = SQL_ERROR;
DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER,
"invalid descriptor identifier");
+ return ret;
}
if (bCallColAtt)
{
@@ -1504,7 +1662,8 @@ IRDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
return SQL_ERROR;
}
ret = PGAPI_ColAttributes(stmt, RecNumber,
- FieldIdentifier, Value, (SQLSMALLINT) BufferLength,
+ FieldIdentifier, Value,
+ BufferLength > SHRT_MAX ? SHRT_MAX : (SQLSMALLINT) BufferLength,
&pcbL, &ival);
len = pcbL;
}
@@ -1523,6 +1682,10 @@ IRDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
len = sizeof(SQLSMALLINT);
*((SQLSMALLINT *) Value) = (SQLSMALLINT) ival;
break;
+ case SQL_IS_LEN:
+ len = sizeof(SQLLEN);
+ *((SQLLEN *) Value) = (SQLLEN) ival;
+ break;
case SQL_IS_POINTER:
len = sizeof(SQLPOINTER);
*((void **) Value) = ptr;
@@ -1651,6 +1814,7 @@ IPDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
}
break;
case SQL_DESC_OCTET_LENGTH:
+ rettype = SQL_IS_LEN;
break;
case SQL_DESC_ALLOC_TYPE: /* read-only */
rettype = SQL_IS_SMALLINT;
@@ -1689,9 +1853,14 @@ IPDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber,
default:ret = SQL_ERROR;
DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER,
"invalid descriptor identifier");
+ return ret;
}
switch (rettype)
{
+ case SQL_IS_LEN:
+ len = sizeof(SQLLEN);
+ *((SQLLEN *) Value) = ival;
+ break;
case 0:
case SQL_IS_INTEGER:
len = sizeof(SQLINTEGER);
@@ -2344,7 +2513,9 @@ PGAPI_GetDescRec(SQLHDESC DescriptorHandle,
RETCODE ret = SQL_SUCCESS;
DescriptorClass *desc = (DescriptorClass *) DescriptorHandle;
- SQLINTEGER strlen, typ, subtyp, len, prec, scal, null;
+ SQLINTEGER strlen;
+ SQLLEN len = 0;
+ SQLSMALLINT typ = 0, subtyp, prec, scal, null;
MYLOG(0, "entering h=%p(%d) rec=" FORMAT_SMALLI " name=%p blen=" FORMAT_SMALLI "\n", DescriptorHandle, DC_get_desc_type((DescriptorClass *) DescriptorHandle), RecNumber, Name, BufferLength);
MYLOG(0, "str=%p type=%p sub=%p len=%p prec=%p scale=%p null=%p\n", StringLength, Type, SubType, Length, Precision, Scale, Nullable);
@@ -2361,12 +2532,13 @@ PGAPI_GetDescRec(SQLHDESC DescriptorHandle,
- SQL_DESC_NAME
*/
- /* Retrieve SQL data type if requested */
- if (Type != NULL)
+ /* Retrieve SQL data type if requested (the subtype needs it too) */
+ if (Type != NULL || SubType != NULL)
{
ret = PGAPI_GetDescField(DescriptorHandle, RecNumber, SQL_DESC_TYPE, &typ, 0, NULL);
if (ret != SQL_SUCCESS) return ret;
- *Type = typ;
+ if (Type != NULL)
+ *Type = typ;
}
/* For datetime and interval types, retrieve the subtype code if requested */
@@ -2382,7 +2554,7 @@ PGAPI_GetDescRec(SQLHDESC DescriptorHandle,
{
ret = PGAPI_GetDescField(DescriptorHandle, RecNumber, SQL_DESC_OCTET_LENGTH, &len, 0, NULL);
if (ret != SQL_SUCCESS) return ret;
- *Length = (SQLLEN) len;
+ *Length = len;
}
/* Retrieve numeric precision if requested */
@@ -2411,13 +2583,27 @@ PGAPI_GetDescRec(SQLHDESC DescriptorHandle,
}
/* Retrieve column/parameter name if requested (only for implementation descriptors) */
- if (Name != NULL && (DC_get_desc_type((DescriptorClass *) DescriptorHandle) == SQL_ATTR_IMP_ROW_DESC
- || DC_get_desc_type((DescriptorClass *) DescriptorHandle) == SQL_ATTR_IMP_PARAM_DESC))
+ if (DC_get_desc_type((DescriptorClass *) DescriptorHandle) == SQL_ATTR_IMP_ROW_DESC
+ || DC_get_desc_type((DescriptorClass *) DescriptorHandle) == SQL_ATTR_IMP_PARAM_DESC)
{
- ret = PGAPI_GetDescField(DescriptorHandle, RecNumber, SQL_DESC_NAME, Name, BufferLength, (SQLINTEGER *) &strlen);
- if (ret != SQL_SUCCESS) return ret;
+ if (Name != NULL || StringLength != NULL)
+ {
+ strlen = 0;
+ ret = PGAPI_GetDescField(DescriptorHandle, RecNumber, SQL_DESC_NAME, Name, Name ? BufferLength : 0, &strlen);
+ if (!SQL_SUCCEEDED(ret)) return ret;
+ /* the full length is reported even when the name was truncated */
+ if (StringLength != NULL)
+ *StringLength = (SQLSMALLINT) strlen;
+ return ret;
+ }
+ }
+ else
+ {
+ /* application descriptors have no name */
+ if (Name != NULL && BufferLength > 0)
+ Name[0] = '\0';
if (StringLength != NULL)
- *StringLength = strlen;
+ *StringLength = 0;
}
return SQL_SUCCESS;
@@ -2445,6 +2631,35 @@ PGAPI_GetDescRec(SQLHDESC DescriptorHandle,
* For unsupported attributes, it returns an error.
* For backward compatibility with ODBC 2.0, it calls PGAPI_SetStmtOption for some attributes.
*/
+/*
+ * An application descriptor attached by SQLSetStmtAttr must be laid out
+ * as one: an explicit descriptor that SQLCopyDesc made an IRD or IPD
+ * holds different fields, and another statement's implicit descriptor
+ * goes away with that statement.
+ */
+static BOOL
+app_desc_usable(StatementClass *stmt, DescriptorClass *desc, DescriptorClass *own, const char *func)
+{
+ if (desc == own)
+ return TRUE;
+ /*
+ * The driver's own statements borrow the application statement's
+ * implicit ARD for the length of one call (SC_fetch_by_bookmark) and
+ * detach it before they are dropped.
+ */
+ if (!stmt->external)
+ return TRUE;
+ if (DC_get_embedded(desc) ||
+ (desc->deschd.type_defined &&
+ SQL_ATTR_APP_ROW_DESC != desc->deschd.desc_type &&
+ SQL_ATTR_APP_PARAM_DESC != desc->deschd.desc_type))
+ {
+ SC_set_error(stmt, STMT_INVALID_ARGUMENT_NO, "the descriptor can't be used as an application descriptor", func);
+ return FALSE;
+ }
+ return TRUE;
+}
+
RETCODE SQL_API
PGAPI_SetStmtAttr(HSTMT StatementHandle,
SQLINTEGER Attribute, PTR Value,
@@ -2490,6 +2705,8 @@ PGAPI_SetStmtAttr(HSTMT StatementHandle,
{
stmt->ard = &(stmt->ardi);
}
+ else if (!app_desc_usable(stmt, (DescriptorClass *) Value, &(stmt->ardi), func))
+ return SQL_ERROR;
else
{
stmt->ard = (DescriptorClass *) Value;
@@ -2502,6 +2719,8 @@ PGAPI_SetStmtAttr(HSTMT StatementHandle,
{
stmt->apd = &(stmt->apdi);
}
+ else if (!app_desc_usable(stmt, (DescriptorClass *) Value, &(stmt->apdi), func))
+ return SQL_ERROR;
else
{
stmt->apd = (DescriptorClass *) Value;
@@ -2609,7 +2828,7 @@ RETCODE bulk_ope_callback(RETCODE retcode, void *para)
if (SQL_ADD != s->operation)
{
pg_bm = SC_Resolve_bookmark(s->opts, s->idx);
- QR_get_last_bookmark(res, s->idx, &pg_bm.keys);
+ QR_get_last_bookmark(res, pg_bm.index, &pg_bm.keys);
global_idx = pg_bm.index;
}
/* Note opts->row_operation_ptr is ignored */
@@ -2642,8 +2861,14 @@ RETCODE bulk_ope_callback(RETCODE retcode, void *para)
s->processed++;
}
conn = SC_get_conn(s->stmt);
- if (s->auto_commit_needed)
- CC_set_autocommit(conn, TRUE);
+ if (s->auto_commit_needed &&
+ !CC_set_autocommit(conn, TRUE) &&
+ SQL_ERROR != ret)
+ {
+ /* the rows are gone with the transaction */
+ SC_set_error(s->stmt, STMT_EXEC_ERROR, "Could not commit the bulk operation", __FUNCTION__);
+ ret = SQL_ERROR;
+ }
irdflds = SC_get_IRDF(s->stmt);
if (irdflds->rowsFetched)
*(irdflds->rowsFetched) = s->processed;
@@ -2679,7 +2904,20 @@ PGAPI_BulkOperations(HSTMT hstmt, SQLSMALLINT operationX)
{
conn = SC_get_conn(s.stmt);
if (s.auto_commit_needed = (char) CC_does_autocommit(conn), s.auto_commit_needed)
- CC_set_autocommit(conn, FALSE);
+ {
+ /*
+ * see PGAPI_SetPos(): a failed commit takes the work with it,
+ * and the mode changes either way, so switch it back before
+ * leaving without the callback that would have done it
+ */
+ if (!CC_set_autocommit(conn, FALSE))
+ {
+ CC_set_autocommit(conn, TRUE);
+ s.auto_commit_needed = FALSE;
+ SC_set_error(s.stmt, STMT_EXEC_ERROR, "Could not commit before the bulk operation", func);
+ return SQL_ERROR;
+ }
+ }
}
if (SQL_ADD != s.operation)
{
diff --git a/pgapifunc.h b/pgapifunc.h
index d5146c80..d61727ee 100644
--- a/pgapifunc.h
+++ b/pgapifunc.h
@@ -284,6 +284,10 @@ RETCODE SQL_API PGAPI_SetScrollOptions(
SQLLEN crowKeyset,
SQLUSMALLINT crowRowset);
+void DescLockHandle(SQLHDESC hdesc, SQLHDESC hdesc2);
+void DescUnlockHandle(SQLHDESC hdesc, SQLHDESC hdesc2);
+void DiagLockHandle(SQLSMALLINT HandleType, SQLHANDLE Handle);
+void DiagUnlockHandle(SQLSMALLINT HandleType, SQLHANDLE Handle);
RETCODE SQL_API PGAPI_GetDiagRec(SQLSMALLINT HandleType, SQLHANDLE Handle,
SQLSMALLINT RecNumber, SQLCHAR *Sqlstate,
SQLINTEGER *NativeError, SQLCHAR *MessageText,
diff --git a/pgtypes.c b/pgtypes.c
index eaee5b8c..540044e8 100644
--- a/pgtypes.c
+++ b/pgtypes.c
@@ -227,7 +227,12 @@ get_interval_type(Int4 atttypmod, const char **name)
{
MYLOG(0, "entering atttypmod=%x\n", atttypmod);
if ((-1) == atttypmod)
+ {
+ /* no field restriction: a plain interval */
+ if (name)
+ *name = "interval";
return 0;
+ }
if (0 != (YEAR_BIT & atttypmod))
{
if (0 != (MONTH_BIT & atttypmod))
diff --git a/pgxalib.cpp b/pgxalib.cpp
index d972010d..87103dd0 100755
--- a/pgxalib.cpp
+++ b/pgxalib.cpp
@@ -427,6 +427,10 @@ static int TextToXid(XID &xid, const char *rtext)
if (glen > 2 * MAXGTRIDSIZE || blen > 2 * MAXBQUALSIZE ||
0 != glen % 2 || 0 != blen % 2)
return -1;
+ /* and holds only the hex digits it writes, around the one '-' */
+ if (strspn(rtext, "0123456789abcdefABCDEF") != (size_t) glen ||
+ strspn(sptr + 1, "0123456789abcdefABCDEF") != (size_t) blen)
+ return -1;
xid.gtrid_length = glen / 2;
xid.bqual_length = blen / 2;
pg_hex2bin((const UCHAR *) rtext, (UCHAR *) &xid.data[0], glen);
@@ -751,9 +755,15 @@ EXTERN_C static int __cdecl xa_recover(XID *xids, long count, int rmid, long fla
HSTMT stmt;
RETCODE ret;
char buf[512];
+ SQLLEN ind;
vec.clear();
- SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt);
+ ret = SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt);
+ if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
+ {
+ pos = -1;
+ goto onExit;
+ }
ret = SQLExecDirect(stmt, (SQLCHAR *) "select gid from pg_prepared_xacts", SQL_NTS);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
{
@@ -761,14 +771,30 @@ EXTERN_C static int __cdecl xa_recover(XID *xids, long count, int rmid, long fla
pos = -1;
goto onExit;
}
- SQLBindCol(stmt, 1, SQL_C_CHAR, buf, sizeof(buf), NULL);
- ret = SQLFetch(stmt);
- while (SQL_NO_DATA_FOUND != ret)
+ /*
+ * Take a row only when SQLFetch() succeeded and gave a gid. A NULL
+ * gid or a reply without the column leaves buf as it was, and a
+ * fetch that fails, for example once the connection is lost, fails
+ * again on every call, so the loop must stop on any return other
+ * than success, not only on SQL_NO_DATA.
+ */
+ SQLBindCol(stmt, 1, SQL_C_CHAR, buf, sizeof(buf), &ind);
+ for (;;)
{
- vec.push_back(buf);
+ ind = SQL_NULL_DATA; /* left as is if the reply has no column */
ret = SQLFetch(stmt);
+ if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
+ break;
+ if (SQL_NULL_DATA != ind)
+ vec.push_back(buf);
}
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+ if (SQL_NO_DATA_FOUND != ret)
+ {
+ vec.clear();
+ pos = -1;
+ goto onExit;
+ }
pos = 0;
}
rcount = (int) vec.size();
diff --git a/qresult.c b/qresult.c
index f73e7e84..ba30f8c8 100644
--- a/qresult.c
+++ b/qresult.c
@@ -295,7 +295,6 @@ QR_close_result(QResultClass *self, BOOL destroy)
{
ConnectionClass *conn;
QResultClass *res, *next;
- BOOL top = TRUE;
if (!self) return;
MYLOG(0, "entering\n");
@@ -333,11 +332,9 @@ QR_close_result(QResultClass *self, BOOL destroy)
{
/*
* Should have been freed in the close() but just in case...
- * QR_set_cursor clears the cursor name of all the chained results too,
- * so we only need to do this for the first result in the chain.
+ * Each result in the chain may own a cursor of its own.
*/
- if (top)
- QR_set_cursor(self, NULL);
+ QR_set_cursor(self, NULL);
/* Free up column info */
if (destroy)
@@ -372,7 +369,6 @@ QR_close_result(QResultClass *self, BOOL destroy)
/* Repeat for the next result in the chain */
self = next;
destroy = TRUE; /* always destroy chained results */
- top = FALSE;
}
MYLOG(0, "leaving\n");
@@ -417,6 +413,35 @@ QR_set_command(QResultClass *self, const char *msg)
self->command = msg ? strdup(msg) : NULL;
}
+/*
+ * Did any result of a reply end its transaction with ROLLBACK, as the
+ * server answers a COMMIT of a transaction that had already failed?
+ */
+BOOL
+QR_command_rolled_back(const QResultClass *self)
+{
+ for (; self; self = QR_nextr(self))
+ {
+ if (self->command && strnicmp(self->command, "ROLLBACK", 8) == 0)
+ return TRUE;
+ }
+ return FALSE;
+}
+
+/* Did every result of a reply succeed? */
+BOOL
+QR_chain_maybe_successful(const QResultClass *self)
+{
+ if (!self)
+ return FALSE;
+ for (; self; self = QR_nextr(self))
+ {
+ if (!QR_command_maybe_successful(self))
+ return FALSE;
+ }
+ return TRUE;
+}
+
void
QR_set_message(QResultClass *self, const char *msg)
@@ -887,13 +912,27 @@ QR_close(QResultClass *self)
{
BOOL does_commit = FALSE;
unsigned int flag = 0;
- char buf[64];
+ char *buf;
+ size_t buflen;
flag = READ_ONLY_QUERY;
if (QR_needs_survival_check(self))
flag |= (ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN);
- SPRINTF_FIXED(buf, "close \"%s\"", QR_get_cursor(self));
+ /*
+ * A refcursor's name comes from the server and has no length
+ * limit; a truncated name would make the close fail and abort
+ * the transaction.
+ */
+ buflen = strlen(QR_get_cursor(self)) + sizeof("close \"\";commit");
+ if (NULL == (buf = malloc(buflen)))
+ {
+ QR_set_rstatus(self, PORES_FATAL_ERROR);
+ QR_set_message(self, "Out of memory closing the cursor.");
+ QR_on_close_cursor(self);
+ return FALSE;
+ }
+ snprintf(buf, buflen, "close \"%s\"", QR_get_cursor(self));
/* End the transaction if there are no cursors left on this conn */
if (CC_is_in_trans(conn) &&
CC_does_autocommit(conn) &&
@@ -902,7 +941,7 @@ QR_close(QResultClass *self)
MYLOG(0, "End transaction on conn=%p\n", conn);
if ((ROLLBACK_ON_ERROR & flag) == 0)
{
- STRCAT_FIXED(buf, ";commit");
+ strlcat(buf, ";commit", buflen);
flag |= END_WITH_COMMIT;
QR_set_cursor(self, NULL);
}
@@ -912,6 +951,17 @@ QR_close(QResultClass *self)
MYLOG(DETAIL_LOG_LEVEL, " Case I CC_send_query %s flag=%x\n", buf, flag);
res = CC_send_query(conn, buf, NULL, flag, NULL);
+ free(buf);
+ /* the commit appended above ends the application's transaction */
+ if ((flag & END_WITH_COMMIT) != 0 &&
+ (!QR_chain_maybe_successful(res) || QR_command_rolled_back(res)))
+ {
+ /* on the connection too: most callers of QR_close() drop the result */
+ CC_set_error(conn, CONN_EXEC_ERROR, "Could not commit the transaction while closing a cursor", __FUNCTION__);
+ QR_set_rstatus(self, PORES_FATAL_ERROR);
+ QR_set_message(self, "Error ending transaction on autocommit.");
+ ret = FALSE;
+ }
QR_Destructor(res);
if (does_commit)
{
@@ -1403,8 +1453,12 @@ MYLOG(DETAIL_LOG_LEVEL, "will add " FORMAT_LEN " added_tuples from " FORMAT_LEN
/* and append the tuples info */
tuple = self->backend_tuples + num_fields * num_backend_rows;
pg_memset(tuple, 0, sizeof(TupleField) * num_fields * add_size);
- added_tuple = self->added_tuples + num_fields * start_idx;
- ReplaceCachedRows(tuple, added_tuple, num_fields, add_size);
+ /* a keyset-driven cursor keeps no added_tuples; its rows are reloaded by key */
+ if (self->added_tuples)
+ {
+ added_tuple = self->added_tuples + num_fields * start_idx;
+ ReplaceCachedRows(tuple, added_tuple, num_fields, add_size);
+ }
self->num_cached_rows += add_size;
self->num_cached_keys += add_size;
num_backend_rows = self->num_cached_rows;
diff --git a/qresult.h b/qresult.h
index 37e078f0..07c390dd 100644
--- a/qresult.h
+++ b/qresult.h
@@ -235,6 +235,8 @@ void QR_reset_for_re_execute(QResultClass *self);
BOOL QR_from_PGresult(QResultClass *self, StatementClass *stmt, ConnectionClass *conn, const char *cursor, PGresult **pgres);
void QR_free_memory(QResultClass *self);
void QR_set_command(QResultClass *self, const char *msg);
+BOOL QR_command_rolled_back(const QResultClass *self);
+BOOL QR_chain_maybe_successful(const QResultClass *self);
void QR_set_message(QResultClass *self, const char *msg);
void QR_add_message(QResultClass *self, const char *msg);
void QR_set_notice(QResultClass *self, const char *msg);
diff --git a/results.c b/results.c
index 382cca37..3fa1d053 100644
--- a/results.c
+++ b/results.c
@@ -431,7 +431,7 @@ MYLOG(DETAIL_LOG_LEVEL, "answering bookmark info\n");
len = col_name ? (int) strlen(col_name) : 0;
if (pcbColName)
- *pcbColName = len;
+ *pcbColName = (SQLSMALLINT) (len > SHRT_MAX ? SHRT_MAX : len); /* the name comes from the server */
if (szColName && cbColNameMax > 0)
{
@@ -950,7 +950,7 @@ MYLOG(DETAIL_LOG_LEVEL, "COLUMN_SCALE=" FORMAT_LEN "\n", value);
}
if (pcbDesc)
- *pcbDesc = (SQLSMALLINT) len;
+ *pcbDesc = (SQLSMALLINT) (len > SHRT_MAX ? SHRT_MAX : len); /* names come from the server */
}
else
{
@@ -1152,12 +1152,14 @@ MYLOG(DETAIL_LOG_LEVEL, "currT=" FORMAT_LEN " base=" FORMAT_LEN " rowset=" FORMA
if (get_bookmark)
{
BOOL contents_get = FALSE;
+ Int4 bookmark = SC_make_int4_bookmark(stmt->currTuple);
if (rgbValue)
{
- if (SQL_C_BOOKMARK == target_type || sizeof(UInt4) <= cbValueMax)
+ /* cbValueMax is signed: a negative one must not pass as large */
+ if (SQL_C_BOOKMARK == target_type ||
+ (SQLLEN) sizeof(UInt4) <= cbValueMax)
{
- Int4 bookmark = SC_make_int4_bookmark(stmt->currTuple);
contents_get = TRUE;
memcpy(rgbValue, &bookmark, sizeof(bookmark));
}
@@ -1926,7 +1928,8 @@ MYLOG(DETAIL_LOG_LEVEL, "num_tuples=" FORMAT_LEN "\n", num_tuples);
else
{ /* overlap with beginning of result set,
* so get first rowset */
- SC_set_rowset_start(stmt, 0, TRUE);
+ rowset_start = 0;
+ SC_set_rowset_start(stmt, rowset_start, TRUE);
}
should_set_rowset_start = FALSE;
}
@@ -2362,11 +2365,29 @@ ti_quote(StatementClass *stmt, OID tableoid, char *buf, int buf_size)
return SAFE_NAME(rNAME);
else
{
- char query[200];
+ char query[600];
QResultClass *res;
char *ret = "";
- SPRINTF_FIXED(query, "select relname, nspname from pg_catalog.pg_class c, pg_catalog.pg_namespace n where c.oid operator(pg_catalog.=) %u and c.relnamespace operator(pg_catalog.=) n.oid", tableoid);
+ /*
+ * tableoid was read from the fetched row. Accept it only when
+ * it names the cursor's table or one of its descendants, so a
+ * row from elsewhere can't steer a positioned UPDATE/DELETE to
+ * another table.
+ */
+ if (0 != ti->table_oid)
+ SPRINTF_FIXED(query,
+ "with recursive t(oid) as (select %u::pg_catalog.oid union"
+ " select i.inhrelid from pg_catalog.pg_inherits i, t"
+ " where i.inhparent operator(pg_catalog.=) t.oid)"
+ " select c.relname, n.nspname"
+ " from pg_catalog.pg_class c, pg_catalog.pg_namespace n, t"
+ " where c.oid operator(pg_catalog.=) %u"
+ " and c.oid operator(pg_catalog.=) t.oid"
+ " and c.relnamespace operator(pg_catalog.=) n.oid",
+ ti->table_oid, tableoid);
+ else
+ SPRINTF_FIXED(query, "select relname, nspname from pg_catalog.pg_class c, pg_catalog.pg_namespace n where c.oid operator(pg_catalog.=) %u and c.relnamespace operator(pg_catalog.=) n.oid", tableoid);
res = CC_send_query(SC_get_conn(stmt), query, NULL, READ_ONLY_QUERY, stmt);
if (QR_command_maybe_successful(res) &&
QR_get_num_cached_tuples(res) == 1)
@@ -2397,7 +2418,7 @@ static BOOL tupleExists(StatementClass *stmt, const KeySet *keyset)
"select 1 from %s where ctid = '(%u,%u)'",
ti_quote(stmt, keyset->oid, table_fqn, sizeof(table_fqn)),
keyset->blocknum, keyset->offset);
- if (NULL != bestqual && 0 != keyset->oid && !TI_has_subclass(ti))
+ if (NULL != bestqual && 0 != keyset->oid)
{
appendPQExpBuffer(&selstr, " and ");
appendPQExpBuffer(&selstr, bestqual, keyset->oid);
@@ -2523,13 +2544,16 @@ static void RemoveAdded(QResultClass *res, SQLLEN index)
if (rmidx >= res->ad_count)
return;
added_keyset = res->added_keyset + rmidx;
- added_tuples = res->added_tuples + num_fields * rmidx;
- ClearCachedRows(added_tuples, num_fields, 1);
+ /* a keyset-driven cursor keeps no added_tuples (see enlargeAdded) */
+ added_tuples = res->added_tuples ? res->added_tuples + num_fields * rmidx : NULL;
+ if (added_tuples)
+ ClearCachedRows(added_tuples, num_fields, 1);
mv_count = res->ad_count - rmidx - 1;
if (mv_count > 0)
{
memmove(added_keyset, added_keyset + 1, mv_count * sizeof(KeySet));
- memmove(added_tuples, added_tuples + num_fields, mv_count * num_fields * sizeof(TupleField));
+ if (added_tuples)
+ memmove(added_tuples, added_tuples + num_fields, mv_count * num_fields * sizeof(TupleField));
}
RemoveDeleted(res, index);
RemoveUpdated(res, index);
@@ -3269,9 +3293,10 @@ MYLOG(DETAIL_LOG_LEVEL, "entering bestitem=%s bestqual=%s\n", SAFE_NAME(ti->best
char *lit_table = identifierEscape((const SQLCHAR *) quoted_table, SQL_NTS, SC_get_conn(stmt), NULL, -1, FALSE);
printfPQExpBuffer(&selstr,
- "%.*sfrom %s where ctid = (select currtid2('%s', '%s'))",
+ "%.*sfrom %s where ctid = (select currtid2(%s'%s', '%s'))",
(int) from_pos, load_stmt,
quoted_table,
+ CC_literal_prefix(SC_get_conn(stmt)),
lit_table ? lit_table : "",
tidval);
if (lit_table)
@@ -3292,6 +3317,16 @@ MYLOG(DETAIL_LOG_LEVEL, "entering bestitem=%s bestqual=%s\n", SAFE_NAME(ti->best
SC_set_error(stmt,STMT_INTERNAL_ERROR, "can't find added and updating row because of the lack of oid", func);
goto cleanup;
}
+ /*
+ * The scan of the table includes its children and each of
+ * them has its own row at this ctid. tableoid is the other
+ * half of the key.
+ */
+ if (bestqual && 0 != tableoid)
+ {
+ appendPQExpBufferStr(&selstr, " and ");
+ appendPQExpBuffer(&selstr, bestqual, tableoid);
+ }
}
else
{
@@ -3307,8 +3342,9 @@ MYLOG(DETAIL_LOG_LEVEL, "entering bestitem=%s bestqual=%s\n", SAFE_NAME(ti->best
char *lit_table = identifierEscape((const SQLCHAR *) ti_quote(stmt, 0, table_fqn, sizeof(table_fqn)), SQL_NTS, SC_get_conn(stmt), NULL, -1, FALSE);
printfPQExpBuffer(&selstr,
- "%s where ctid = (select currtid2('%s', '%s'))",
+ "%s where ctid = (select currtid2(%s'%s', '%s'))",
load_stmt,
+ CC_literal_prefix(SC_get_conn(stmt)),
lit_table ? lit_table : "",
tidval);
if (lit_table)
@@ -4269,7 +4305,16 @@ SC_pos_update(StatementClass *stmt,
{
if (!(oid = getOid(s.res, kres_ridx)))
{
- if (!strcmp(SAFE_NAME(stmt->ti[0]->bestitem), OID_NAME))
+ /*
+ * An oid and a tableoid are never 0, so a 0 means the row's
+ * key is gone and bestqual cannot identify the row: without
+ * it the statement would match by ctid alone, which on a
+ * table with children is another table's row. A bestitem
+ * that names a key column is left alone, since 0 is a value
+ * such a column can hold.
+ */
+ if (!strcmp(SAFE_NAME(stmt->ti[0]->bestitem), OID_NAME) ||
+ !strcmp(SAFE_NAME(stmt->ti[0]->bestitem), TABLEOID_NAME))
{
SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the row was already deleted ?", func);
return SQL_ERROR;
@@ -4383,6 +4428,8 @@ SC_pos_update(StatementClass *stmt,
goto cleanup;
}
s.qstmt = (StatementClass *) hstmt;
+ /* the application's SQL_ATTR_QUERY_TIMEOUT applies to the UPDATE too */
+ s.qstmt->options.stmt_timeout = s.stmt->options.stmt_timeout;
apdopts = SC_get_APDF(s.qstmt);
apdopts->param_bind_type = opts->bind_size;
apdopts->param_offset_ptr = opts->row_offset_ptr;
@@ -4508,7 +4555,10 @@ SC_pos_delete(StatementClass *stmt,
{
if (!(oid = getOid(res, kres_ridx)))
{
- if (bestitem && !strcmp(bestitem, OID_NAME))
+ /* the reason is given in SC_pos_update() */
+ if (bestitem &&
+ (!strcmp(bestitem, OID_NAME) ||
+ !strcmp(bestitem, TABLEOID_NAME)))
{
SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the row was already deleted ?", func);
return SQL_ERROR;
@@ -4528,7 +4578,7 @@ SC_pos_delete(StatementClass *stmt,
printfPQExpBuffer(&dltstr,
"delete from %s where ctid = '(%u, %u)'",
ti_quote(stmt, oid, table_fqn, sizeof(table_fqn)), blocknum, offset);
- if (bestqual && !TI_has_subclass(ti))
+ if (bestqual)
{
appendPQExpBuffer(&dltstr, " and ");
appendPQExpBuffer(&dltstr, bestqual, oid);
@@ -4835,6 +4885,8 @@ SC_pos_add(StatementClass *stmt,
else
offset = 0;
s.qstmt = (StatementClass *) hstmt;
+ /* the application's SQL_ATTR_QUERY_TIMEOUT applies to the INSERT too */
+ s.qstmt->options.stmt_timeout = s.stmt->options.stmt_timeout;
apdopts = SC_get_APDF(s.qstmt);
apdopts->param_bind_type = opts->bind_size;
apdopts->param_offset_ptr = opts->row_offset_ptr;
@@ -5126,8 +5178,14 @@ RETCODE spos_callback(RETCODE retcode, void *para)
s->nrow++;
}
conn = SC_get_conn(s->stmt);
- if (s->auto_commit_needed)
- CC_set_autocommit(conn, TRUE);
+ if (s->auto_commit_needed &&
+ !CC_set_autocommit(conn, TRUE) &&
+ SQL_ERROR != ret)
+ {
+ /* the rows are gone with the transaction */
+ SC_set_error(s->stmt, STMT_EXEC_ERROR, "Could not commit the positioned operation", __FUNCTION__);
+ ret = SQL_ERROR;
+ }
if (s->irow > 0)
{
if (SQL_ADD != s->fOption && s->ridx >= 0) /* for SQLGetData */
@@ -5251,7 +5309,28 @@ MYLOG(0, "num_cols=%d gdatainfo=%d\n", QR_NumPublicResultCols(s.res), gdata_allo
case SQL_DELETE:
case SQL_ADD:
if (s.auto_commit_needed = CC_does_autocommit(conn), s.auto_commit_needed)
- CC_set_autocommit(conn, FALSE);
+ {
+ /*
+ * Switching autocommit off commits the open transaction.
+ * When that fails the transaction's work is gone, so the
+ * positioned write must not go on against the cursor it
+ * left behind; the callback checks the way back in the
+ * same way.
+ *
+ * CC_set_autocommit() changes the mode whether or not the
+ * commit succeeded, and returning here skips the callback
+ * that would switch it back, so put the connection into
+ * the mode the application believes it is in before
+ * leaving.
+ */
+ if (!CC_set_autocommit(conn, FALSE))
+ {
+ CC_set_autocommit(conn, TRUE);
+ s.auto_commit_needed = FALSE;
+ SC_set_error(s.stmt, STMT_EXEC_ERROR, "Could not commit before the positioned operation", func);
+ return SQL_ERROR;
+ }
+ }
break;
case SQL_POSITION:
break;
@@ -5399,8 +5478,9 @@ SC_fetch_by_bookmark(StatementClass *stmt)
ARDFields *opts = SC_get_ARDF(stmt);
SQLHDESC hdesc;
APDFields *apdf;
- const int tidbuflen = 20;
- char *tidbuf = NULL, *query = NULL;
+ const int tidbuflen = 20, oidbuflen = 12;
+ char *tidbuf = NULL, *oidbuf = NULL, *query = NULL;
+ CSTR oidqual = " and \"" TABLEOID_NAME "\" = ?";
int i, lodlen;
BindInfoClass *bookmark_orig = opts->bookmark;
TupleField *otuple, *ituple;
@@ -5426,8 +5506,13 @@ SC_fetch_by_bookmark(StatementClass *stmt)
SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "internal AllocStmt error", __FUNCTION__);
return ret;
}
+ /* the application's SQL_ATTR_QUERY_TIMEOUT applies to the SELECT too */
+ ((StatementClass *) hstmt)->options.stmt_timeout = stmt->options.stmt_timeout;
size_of_rowset = opts->size_of_rowset;
SC_MALLOC_gexit_with_error(tidbuf, char, size_of_rowset * tidbuflen, stmt, "Couldn't allocate memory for tidbuf bind.", (ret = SQL_ERROR));
+ /* the children of the table have their own rows at the same ctids */
+ if (TI_has_subclass(stmt->ti[0]))
+ SC_MALLOC_gexit_with_error(oidbuf, char, size_of_rowset * oidbuflen, stmt, "Couldn't allocate memory for oidbuf bind.", (ret = SQL_ERROR));
for (i = 0; i < size_of_rowset; i++)
{
PG_BM pg_bm;
@@ -5468,23 +5553,35 @@ MYLOG(0, "i=%d bidx=" FORMAT_LEN " cached=" FORMAT_ULEN "\n", i, bidx, res->num_
}
snprintf(tidbuf + i * tidbuflen, tidbuflen, "(%u,%u)", blocknum, offset);
MYLOG(0, "!!!! tidbuf=%s\n", tidbuf + i * tidbuflen);
+ if (NULL != oidbuf)
+ snprintf(oidbuf + i * oidbuflen, oidbuflen, "%u", oidint);
}
if (!SQL_SUCCEEDED(PGAPI_BindParameter(hstmt, 1, SQL_PARAM_INPUT,
SQL_C_CHAR, SQL_CHAR, tidbuflen, 0,
tidbuf, tidbuflen, NULL)))
- goto cleanup;
+ goto internal_error;
+ if (NULL != oidbuf &&
+ !SQL_SUCCEEDED(PGAPI_BindParameter(hstmt, 2, SQL_PARAM_INPUT,
+ SQL_C_CHAR, SQL_CHAR, oidbuflen, 0,
+ oidbuf, oidbuflen, NULL)))
+ goto internal_error;
apdf = SC_get_APDF((StatementClass *) hstmt);
apdf->paramset_size = size_of_rowset;
if (!SQL_SUCCEEDED(PGAPI_GetStmtAttr(stmt, SQL_ATTR_APP_ROW_DESC, (SQLPOINTER) &hdesc, SQL_IS_POINTER, NULL)))
- goto cleanup;
+ goto internal_error;
if (!SQL_SUCCEEDED(PGAPI_SetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, (SQLPOINTER) hdesc, SQL_IS_POINTER)))
- goto cleanup;
+ goto internal_error;
lodlen = strlen(stmt->load_statement) + 15;
+ if (NULL != oidbuf)
+ lodlen += strlen(oidqual);
SC_MALLOC_gexit_with_error(query, char, lodlen, stmt, "Couldn't allocate memory for query buf.", (ret = SQL_ERROR));
- snprintf(query, lodlen, "%s where ctid=?", stmt->load_statement);
+ snprintf(query, lodlen, "%s where ctid=?%s", stmt->load_statement, NULL != oidbuf ? oidqual : "");
if (!SQL_SUCCEEDED(ret = PGAPI_ExecDirect(hstmt, (SQLCHAR *) query, SQL_NTS, PODBC_RDONLY)))
+ {
+ SC_error_copy(stmt, (StatementClass *) hstmt, TRUE);
goto cleanup;
+ }
/*
* Combine multiple results into one
*/
@@ -5543,7 +5640,14 @@ MYLOG(0, "i=%d bidx=" FORMAT_LEN " cached=" FORMAT_ULEN "\n", i, bidx, res->num_
ret = PGAPI_ExtendedFetch(fstmt, SQL_FETCH_NEXT, 0,
&cRow, NULL, 0, size_of_rowset);
MYLOG(0, "cRow=" FORMAT_ULEN "\n", cRow);
-
+ goto cleanup;
+
+internal_error:
+ /* a step on the internal statement failed: don't report success */
+ SC_error_copy(stmt, (StatementClass *) hstmt, TRUE);
+ if (0 == SC_get_errornumber(stmt))
+ SC_set_error(stmt, STMT_INTERNAL_ERROR, "could not set up the fetch by bookmark", __FUNCTION__);
+ ret = SQL_ERROR;
cleanup:
if (NULL != hstmt)
{
@@ -5553,6 +5657,8 @@ cleanup:
opts->bookmark = bookmark_orig;
if (NULL != tidbuf)
free(tidbuf);
+ if (NULL != oidbuf)
+ free(oidbuf);
if (NULL != query)
free(query);
diff --git a/secure_sscanf.c b/secure_sscanf.c
index 2d09adb2..5490b4a6 100644
--- a/secure_sscanf.c
+++ b/secure_sscanf.c
@@ -102,7 +102,7 @@
ALWAYS_INLINE char *
skip_spaces(const char *pInputString)
{
- while (isspace(*pInputString)) {
+ while (isspace((unsigned char) *pInputString)) {
++pInputString;
}
@@ -536,9 +536,18 @@ parse_arg(int *pError, const char *pFmt, const char *pInputString, va_list *args
}
if (cbSize) {
- memset(pOutput, '\0', useTrim ? uWidth : cbSize);
+ /*
+ * Clear the whole destination, not just uWidth bytes:
+ * a token of uWidth characters or more would otherwise
+ * fill the cleared bytes and leave the string
+ * unterminated, and a width larger than the buffer
+ * would make the memset itself overrun it. At most
+ * cbSize - 1 bytes are stored below, so the result is
+ * always NUL terminated.
+ */
+ memset(pOutput, '\0', cbSize);
cbSize--;
- while (pCurrent[0] != '\0' && !isspace(pCurrent[0]) && cbSize != 0 && (useTrim ? uWidth-- > 0 : 1)) {
+ while (pCurrent[0] != '\0' && !isspace((unsigned char) pCurrent[0]) && cbSize != 0 && (useTrim ? uWidth-- > 0 : 1)) {
#ifdef _MSC_VER
*((char*)pOutput)++ = *pCurrent++;
#else
@@ -549,7 +558,7 @@ parse_arg(int *pError, const char *pFmt, const char *pInputString, va_list *args
if (cbSize == 0) {
/* Truncated ... Should this condition be propogated ? */
- while (pCurrent[0] != '\0' && !isspace(pCurrent[0]))
+ while (pCurrent[0] != '\0' && !isspace((unsigned char) pCurrent[0]))
pCurrent++;
}
}
@@ -611,7 +620,7 @@ secure_sscanf(const char *pInputString, int *pStatus, const char *pFmt, ... )
++pFmt;
pInputString = tmp;
- } else if (isspace(pFmt[0])) {
+ } else if (isspace((unsigned char) pFmt[0])) {
++pFmt;
pInputString = skip_spaces(pInputString);
} else if (pFmt[0] == pInputString[0]) {
diff --git a/setup.c b/setup.c
index 94a28db7..25f4bb37 100644
--- a/setup.c
+++ b/setup.c
@@ -613,7 +613,7 @@ ParseAttributes(LPCSTR lpszAttributes, LPSETUPDLG lpsetupdlg)
LPCSTR lpsz;
LPCSTR lpszStart;
char aszKey[MAXKEYLEN];
- size_t cbKey;
+ size_t cbKey, cbValue;
char value[MAXPGPATH];
for (lpsz = lpszAttributes; *lpsz; lpsz++)
@@ -630,21 +630,37 @@ ParseAttributes(LPCSTR lpszAttributes, LPSETUPDLG lpsetupdlg)
else if (*lpsz == '=')
break; /* Valid key found */
}
- /* Determine the key's index in the key table (-1 if not found) */
+ /*
+ * Skip a pair whose key or value does not fit. Keeping it means
+ * leaving aszKey as it is, which gives the value to the previous
+ * key, and copying a value of MAXPGPATH bytes or more without its
+ * NUL. Truncating is no better: a cut password or host is
+ * silently wrong.
+ */
cbKey = lpsz - lpszStart;
- if (cbKey < sizeof(aszKey))
+ if (cbKey >= sizeof(aszKey))
{
- memcpy(aszKey, lpszStart, cbKey);
- aszKey[cbKey] = '\0';
+ MYLOG(0, "skipping an attribute whose key is " FORMAT_SIZE_T " bytes long\n", cbKey);
+ for (; *lpsz; lpsz++)
+ ;
+ continue;
}
+ memcpy(aszKey, lpszStart, cbKey);
+ aszKey[cbKey] = '\0';
/* Locate end of key value */
lpszStart = ++lpsz;
for (; *lpsz; lpsz++)
;
+ cbValue = lpsz - lpszStart;
+ if (cbValue >= sizeof(value))
+ {
+ MYLOG(0, "skipping aszKey='%s': its value is " FORMAT_SIZE_T " bytes long\n", aszKey, cbValue);
+ continue;
+ }
/* lpsetupdlg->aAttr[iElement].fSupplied = TRUE; */
- memcpy(value, lpszStart, MIN(lpsz - lpszStart + 1, MAXPGPATH));
+ memcpy(value, lpszStart, cbValue + 1);
/*
* Not the value: it may be a password. copyConnAttributes() logs
diff --git a/statement.c b/statement.c
index 6a713537..90e26f22 100644
--- a/statement.c
+++ b/statement.c
@@ -176,6 +176,7 @@ static const struct
static QResultClass *libpq_bind_and_exec(StatementClass *stmt);
static void SC_set_errorinfo(StatementClass *self, QResultClass *res, int errkind);
static void SC_set_error_if_not_set(StatementClass *self, int errornumber, const char *errmsg, const char *func);
+static void SC_abandon_lo(StatementClass *self);
RETCODE SQL_API
@@ -293,6 +294,7 @@ PGAPI_FreeStmt(HSTMT hstmt,
res = SC_get_Result(stmt);
QR_Destructor(res);
SC_init_Result(stmt);
+ SC_abandon_lo(stmt);
if (!CC_remove_statement(conn, stmt))
{
SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Statement is currently executing a transaction.", func);
@@ -473,6 +475,7 @@ SC_Constructor(ConnectionClass *conn)
rv->stmt_time = 0;
rv->execute_delegate = NULL;
rv->execute_parent = NULL;
+ rv->delegate_executing = FALSE;
rv->allocated_callbacks = 0;
rv->num_callbacks = 0;
rv->callbacks = NULL;
@@ -963,6 +966,28 @@ SC_finish_catalog_names(StatementClass *self, RETCODE ret,
return ret;
}
+/*
+ * Free the list of processed statements (the SQL fragments built by
+ * prepareParametersNoDesc()) of the statement.
+ */
+void
+SC_free_processed_statements(StatementClass *self)
+{
+ ProcessedStmt *pstmt;
+ ProcessedStmt *next_pstmt;
+
+ pstmt = self->processed_statements;
+ while (pstmt)
+ {
+ if (pstmt->query)
+ free(pstmt->query);
+ next_pstmt = pstmt->next;
+ free(pstmt);
+ pstmt = next_pstmt;
+ }
+ self->processed_statements = NULL;
+}
+
/*
* Initialize stmt_with_params and load_statement member pointer
* deallocating corresponding prepared plan. Also initialize
@@ -971,8 +996,6 @@ SC_finish_catalog_names(StatementClass *self, RETCODE ret,
RETCODE
SC_initialize_stmts(StatementClass *self, BOOL initializeOriginal)
{
- ProcessedStmt *pstmt;
- ProcessedStmt *next_pstmt;
ConnectionClass *conn = SC_get_conn(self);
if (self->lock_CC_for_rb)
@@ -990,16 +1013,7 @@ SC_initialize_stmts(StatementClass *self, BOOL initializeOriginal)
}
SC_clear_described_ctype(self);
- pstmt = self->processed_statements;
- while (pstmt)
- {
- if (pstmt->query)
- free(pstmt->query);
- next_pstmt = pstmt->next;
- free(pstmt);
- pstmt = next_pstmt;
- }
- self->processed_statements = NULL;
+ SC_free_processed_statements(self);
/*
* The parsed table/field information (ti, parse_status,
@@ -1128,6 +1142,34 @@ SC_reset_result_for_rerun(StatementClass *self)
}
}
+/*
+ * Give up the large object the statement is reading or writing.
+ * convert_lo() (and PGAPI_PutData()) begin an in-line transaction
+ * for it in autocommit mode and end that transaction only after the
+ * last piece has been read (or SQLParamData() is called). If the
+ * application abandons the statement before that, end the transaction
+ * here in the same way, otherwise the connection stays in a transaction
+ * nobody commits. Don't lo_close() the descriptor: the COMMIT closes it
+ * and, if another statement has ended the transaction in the meantime,
+ * it is already gone.
+ */
+static void
+SC_abandon_lo(StatementClass *self)
+{
+ ConnectionClass *conn = SC_get_conn(self);
+
+ if (self->lobj_fd < 0)
+ return;
+ MYLOG(0, "self=%p lobj_fd=%d\n", self, self->lobj_fd);
+ self->lobj_fd = -1;
+ if (!conn)
+ return;
+
+ /* commit transaction if needed */
+ if (!conn->connInfo.drivers.use_declarefetch && CC_does_autocommit(conn))
+ CC_commit(conn);
+}
+
/*
* Called from SQLPrepare if STMT_PREMATURE, or
* from SQLExecute if STMT_FINISHED, or
@@ -1218,7 +1260,7 @@ MYLOG(DETAIL_LOG_LEVEL, "statement=%p ommitted=0\n", self);
self->__error_message = NULL;
self->__error_number = 0;
- self->lobj_fd = -1;
+ SC_abandon_lo(self);
SC_free_params(self, STMT_FREE_PARAMS_DATA_AT_EXEC_ONLY);
SC_initialize_stmts(self, FALSE);
@@ -1598,7 +1640,14 @@ static const struct
{ STMT_COUNT_FIELD_INCORRECT, "07002", "07002" },
{ STMT_INVALID_NULL_ARG, "HY009", "S1009" },
{ STMT_NO_RESPONSE, "08S01", "08S01" },
- { STMT_COMMUNICATION_ERROR, "08S01", "08S01" }
+ { STMT_COMMUNICATION_ERROR, "08S01", "08S01" },
+ /*
+ * The table is indexed by the error number, so every number up to the
+ * last one needs an entry. HY000 is what a number past the end of the
+ * table falls back to.
+ */
+ { STMT_STRING_CONVERSION_ERROR, "HY000", "S1000" },
+ { STMT_INVALID_BUFFER_LENGTH, "HY090", "S1090" }
};
static PG_ErrorInfo *
@@ -2021,8 +2070,13 @@ MYLOG(DETAIL_LOG_LEVEL, "entering statement=%p res=%p ommitted=0\n", self, res);
MYLOG(0, "**** : end_tuples\n");
if (QR_get_cursor(res) &&
SQL_CURSOR_FORWARD_ONLY == self->options.cursor_type &&
- QR_once_reached_eof(res))
- QR_close(res);
+ QR_once_reached_eof(res) &&
+ !QR_close(res))
+ {
+ /* closing the cursor also ended the transaction, and that failed */
+ SC_set_errorinfo(self, res, 1);
+ return SQL_ERROR;
+ }
return SQL_NO_DATA_FOUND;
}
else if (retval > 0)
@@ -2079,11 +2133,18 @@ MYLOG(DETAIL_LOG_LEVEL, "stmt=%p ommitted++\n", self);
if ((bookmark = opts->bookmark) && bookmark->buffer)
{
SC_set_current_col(self, -1);
- SC_Create_bookmark(self, bookmark, self->bind_row, self->currTuple, keyset);
+ if (COPY_RESULT_TRUNCATED ==
+ SC_Create_bookmark(self, bookmark, self->bind_row,
+ self->currTuple, keyset))
+ {
+ SC_set_error(self, STMT_TRUNCATED,
+ "Fetched bookmark was truncated.", func);
+ result = SQL_SUCCESS_WITH_INFO;
+ }
}
if (self->options.retrieve_data == SQL_RD_OFF) /* data isn't required */
- return SQL_SUCCESS;
+ return result;
/* The following adjustment would be needed after SQLMoreResults() */
if (opts->allocated < num_cols)
extend_column_bindings(opts, num_cols);
@@ -2192,7 +2253,7 @@ SC_execute(StatementClass *self)
QueryInfo qi;
ConnInfo *ci;
unsigned int qflag = 0;
- BOOL is_in_trans, issue_begin, has_out_para;
+ BOOL is_in_trans, issue_begin, has_out_para, commit_failed = FALSE;
BOOL use_extended_protocol;
int func_cs_count = 0, i;
BOOL useCursor, isSelectType;
@@ -2248,7 +2309,12 @@ SC_execute(StatementClass *self)
if (STMT_TYPE_START == self->statement_type &&
CC_does_autocommit(conn))
{
- CC_commit(conn);
+ if (!CC_commit(conn))
+ {
+ /* the work of the open transaction is gone */
+ SC_set_error(self, STMT_EXEC_ERROR, "Could not commit the open transaction", func);
+ goto cleanup;
+ }
is_in_trans = CC_is_in_trans(conn);
}
}
@@ -2294,7 +2360,19 @@ SC_execute(StatementClass *self)
(int) stmt_timeout * 1000);
res = CC_send_query(conn, query, NULL, 0, NULL);
if (QR_command_maybe_successful(res))
+ {
+ /*
+ * SET is transactional. When it is issued inside a
+ * transaction, a ROLLBACK brings back the value the
+ * session had before, so remember it (see CC_on_abort()).
+ */
+ if (CC_is_in_trans(conn) && !conn->stmt_timeout_set_in_trans)
+ {
+ conn->stmt_timeout_before_trans = conn->stmt_timeout_in_effect;
+ conn->stmt_timeout_set_in_trans = 1;
+ }
conn->stmt_timeout_in_effect = stmt_timeout;
+ }
QR_Destructor(res);
}
@@ -2437,8 +2515,9 @@ SC_execute(StatementClass *self)
{
if (!is_in_trans)
CC_set_in_manual_trans(conn);
- if (self->external && CC_does_autocommit(conn))
- CC_commit(conn);
+ if (self->external && CC_does_autocommit(conn) &&
+ !CC_commit(conn))
+ commit_failed = TRUE;
}
}
@@ -2472,6 +2551,13 @@ MYLOG(0, "set %p STMT_FINISHED\n", self);
}
else
SC_set_errorinfo(self, first, 0);
+ /*
+ * The statement succeeded, but committing it did not (a deferred
+ * constraint, say), so its work is gone.
+ */
+ if (commit_failed &&
+ (STMT_OK == SC_get_errornumber(self) || STMT_INFO_ONLY == SC_get_errornumber(self)))
+ SC_set_error(self, STMT_EXEC_ERROR, "Could not commit the statement's transaction", func);
/*
* The statement failed and left the transaction aborted, and it is
* a transaction this statement opened: the application is in
@@ -2934,12 +3020,21 @@ RequestStart(StatementClass *stmt, ConnectionClass *conn, const char *func)
if (NULL == conn->pqconn)
{
SC_set_error(stmt, STMT_COMMUNICATION_ERROR, "The connection has been lost", __FUNCTION__);
- return SQL_ERROR;
+ return FALSE;
}
- if (CC_started_rbpoint(conn))
- return TRUE;
if (SC_is_readonly(stmt))
svpopt |= SVPOPT_RDONLY;
+ if (CC_started_rbpoint(conn))
+ {
+ /*
+ * The rollback point of this call is already set, but still
+ * record what kind of query follows it, so that a call which
+ * read first and writes now is not remembered as read-only
+ * (see CC_send_query_append).
+ */
+ conn->opt_in_progress &= svpopt;
+ return TRUE;
+ }
if (SQL_ERROR == SetStatementSvp(stmt, svpopt))
{
char emsg[128];
@@ -3246,17 +3341,11 @@ ParseWithLibpq(StatementClass *stmt, const char *plan_name,
SC_param_next(stmt, &pidx, NULL, NULL);
if (pidx > end_pidx)
break;
- else if (pidx < end_pidx)
- {
- if (0 == num_params)
- sta_pidx = pidx;
- num_params++;
- }
- else
- {
- num_params++;
+ if (0 == num_params)
+ sta_pidx = pidx;
+ num_params++;
+ if (pidx == end_pidx)
break;
- }
}
MYLOG(0, "sta_pidx=%d end_pidx=%d num_p=%d\n", sta_pidx, end_pidx, num_params);
}
@@ -3540,9 +3629,26 @@ BOOL SC_IsExecuting(const StatementClass *self)
LEAVE_COMMON_CS;
return ret;
}
+/*
+ * Whether this statement, or a delegate executing on its behalf, is
+ * executing a query. For a thread that does not hold the statement lock
+ * this is the only safe form of the question: following
+ * execute_delegate needs the statement lock, which the executing thread
+ * holds. See delegate_executing in statement.h.
+ */
+BOOL SC_ExecutionInProgress(const StatementClass *self)
+{
+ BOOL ret;
+ ENTER_COMMON_CS; /* short time blocking */
+ ret = (STMT_EXECUTING == self->status || self->delegate_executing);
+ LEAVE_COMMON_CS;
+ return ret;
+}
BOOL SC_SetExecuting(StatementClass *self, BOOL on)
{
BOOL exeSet = FALSE;
+ StatementClass *parent;
+
ENTER_COMMON_CS; /* short time blocking */
if (on)
{
@@ -3559,6 +3665,17 @@ BOOL SC_SetExecuting(StatementClass *self, BOOL on)
MYLOG(0, "set %p STMT_FINISHED\n", self);
exeSet = TRUE;
}
+ if (exeSet)
+ {
+ /*
+ * PGAPI_Cancel() is given the handle the application holds,
+ * which when self is a delegate is a statement further up the
+ * execute_parent chain, so each statement on the chain must
+ * show the execution. See delegate_executing in statement.h.
+ */
+ for (parent = self->execute_parent; parent; parent = parent->execute_parent)
+ parent->delegate_executing = on;
+ }
LEAVE_COMMON_CS;
return exeSet;
}
@@ -3667,6 +3784,8 @@ SC_set_errorinfo(StatementClass *self, QResultClass *res, int errkind)
* Now the driver offers more verbose bookmarks which contain KeySet informations
* (CTID (+ OID)). Though they consume 12bytes(row number + CTID) or 16bytes
* (row number + CTID + OID), they are useful in declare/fetch mode.
+ * A fixed-length bookmark (SQL_C_BOOKMARK) is the 4-byte row number, and
+ * that is the distance between two rows of a column-wise bound array.
*/
PG_BM SC_Resolve_bookmark(const ARDFields *opts, Int4 idx)
@@ -3682,19 +3801,29 @@ PG_BM SC_Resolve_bookmark(const ARDFields *opts, Int4 idx)
offset = opts->row_offset_ptr ? *(opts->row_offset_ptr) : 0;
bind_size = opts->bind_size;
pg_memset(&pg_bm, 0, sizeof(pg_bm));
- if (used = bookmark->used, used != NULL)
+ /*
+ * A SQL_C_BOOKMARK buffer holds 4 bytes, whatever the indicator says.
+ * A SQL_C_VARBOOKMARK buffer holds at most buflen bytes; the indicator
+ * is signed, so a negative one (SQL_NULL_DATA, SQL_NTS) must not
+ * compare as a large length.
+ */
+ if (SQL_C_BOOKMARK != bookmark->returntype &&
+ (used = bookmark->used, used != NULL))
{
used = LENADDR_SHIFT(used, offset);
if (bind_size > 0)
used = LENADDR_SHIFT(used, idx * bind_size);
else
used = LENADDR_SHIFT(used, idx * sizeof(SQLLEN));
- if (*used >= sizeof(pg_bm))
+ if (*used >= (SQLLEN) sizeof(pg_bm))
cpylen = sizeof(pg_bm);
else if (*used >= 12)
cpylen = 12;
MYLOG(0, "used=" FORMAT_LEN " cpylen=" FORMAT_SIZE_T "\n", *used, cpylen);
}
+ if (SQL_C_VARBOOKMARK == bookmark->returntype &&
+ bookmark->buflen < (SQLLEN) cpylen)
+ cpylen = bookmark->buflen > 0 ? (size_t) bookmark->buflen : 0;
memcpy(&pg_bm, CALC_BOOKMARK_ADDR(bookmark, offset, bind_size, idx), cpylen);
MYLOG(0, "index=%d block=%d off=%d\n", pg_bm.index, pg_bm.keys.blocknum, pg_bm.keys.offset);
pg_bm.index = SC_resolve_int4_bookmark(pg_bm.index);
@@ -3708,20 +3837,31 @@ int SC_Create_bookmark(StatementClass *self, BindInfoClass *bookmark, Int4 bind_
SQLUINTEGER bind_size = opts->bind_size;
SQLULEN offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0;
size_t cvtlen = sizeof(Int4);
+ size_t copylen;
PG_BM pg_bm;
MYLOG(0, "entering type=%d buflen=" FORMAT_LEN " buf=%p\n", bookmark->returntype, bookmark->buflen, bookmark->buffer);
pg_memset(&pg_bm, 0, sizeof(pg_bm));
if (SQL_C_BOOKMARK == bookmark->returntype)
;
- else if (bookmark->buflen >= sizeof(pg_bm))
+ else if (bookmark->buflen >= (SQLLEN) sizeof(pg_bm))
cvtlen = sizeof(pg_bm);
else if (bookmark->buflen >= 12)
cvtlen = 12;
pg_bm.index = SC_make_int4_bookmark(currTuple);
if (keyset)
pg_bm.keys = *keyset;
- memcpy(CALC_BOOKMARK_ADDR(bookmark, offset, bind_size, bind_row), &pg_bm, cvtlen);
+ /*
+ * A SQL_C_VARBOOKMARK buffer shorter than the 4-byte bookmark gets
+ * buflen bytes of it; the indicator still reports the whole length.
+ * PGAPI_BindCol refuses a negative buflen.
+ */
+ copylen = cvtlen;
+ if (SQL_C_VARBOOKMARK == bookmark->returntype &&
+ bookmark->buflen < (SQLLEN) cvtlen)
+ copylen = bookmark->buflen > 0 ? (size_t) bookmark->buflen : 0;
+ memcpy(CALC_BOOKMARK_ADDR(bookmark, offset, bind_size, bind_row), &pg_bm,
+ copylen);
if (bookmark->used)
{
SQLLEN *used = LENADDR_SHIFT(bookmark->used, offset);
@@ -3734,5 +3874,5 @@ MYLOG(0, "entering type=%d buflen=" FORMAT_LEN " buf=%p\n", bookmark->returntype
}
MYLOG(0, "leaving cvtlen=" FORMAT_SIZE_T " ix(bl,of)=%d(%d,%d)\n", cvtlen, pg_bm.index, pg_bm.keys.blocknum, pg_bm.keys.offset);
- return COPY_OK;
+ return copylen < cvtlen ? COPY_RESULT_TRUNCATED : COPY_OK;
}
diff --git a/statement.h b/statement.h
index 1098c3b9..2c5650d3 100644
--- a/statement.h
+++ b/statement.h
@@ -98,6 +98,7 @@ enum {
,STMT_NO_RESPONSE
,STMT_COMMUNICATION_ERROR
,STMT_STRING_CONVERSION_ERROR
+ ,STMT_INVALID_BUFFER_LENGTH
};
/* statement types */
@@ -317,6 +318,15 @@ struct StatementClass_
/* SQL_NEED_DATA Callback list */
StatementClass *execute_delegate;
StatementClass *execute_parent;
+ /*
+ * TRUE while a statement in the execute_delegate chain under this
+ * one is STMT_EXECUTING. Written by SC_SetExecuting() and read by
+ * PGAPI_Cancel() under the common lock: the canceling thread cannot
+ * take the statement lock or follow execute_delegate (the executing
+ * thread owns both), and this statement's own status does not show
+ * a delegate's execution.
+ */
+ char delegate_executing;
UInt2 allocated_callbacks;
UInt2 num_callbacks;
NeedDataCallback *callbacks;
@@ -493,7 +503,8 @@ enum
#define LEAVE_STMT_CS(x) LeaveCriticalSection(&((x)->cs))
#define DELETE_STMT_CS(x) DeleteCriticalSection(&((x)->cs))
#elif defined(POSIX_THREADMUTEX_SUPPORT)
-#define INIT_STMT_CS(x) pthread_mutex_init(&((x)->cs),0)
+/* recursive where available, like the connection's, so re-entry can't deadlock */
+#define INIT_STMT_CS(x) pthread_mutex_init(&((x)->cs), getMutexAttr())
#define ENTER_STMT_CS(x) pthread_mutex_lock(&((x)->cs))
#define TRY_ENTER_STMT_CS(x) (0 == pthread_mutex_trylock(&((x)->cs)))
#define LEAVE_STMT_CS(x) pthread_mutex_unlock(&((x)->cs))
@@ -548,6 +559,7 @@ void SC_set_prepared(StatementClass *self, int);
void SC_set_planname(StatementClass *self, const char *plan_name);
void SC_set_rowset_start(StatementClass *self, SQLLEN, BOOL);
void SC_inc_rowset_start(StatementClass *self, SQLLEN);
+void SC_free_processed_statements(StatementClass *self);
RETCODE SC_initialize_stmts(StatementClass *self, BOOL);
RETCODE SC_execute(StatementClass *self);
RETCODE SC_fetch(StatementClass *self);
@@ -572,6 +584,7 @@ void SC_scanQueryAndCountParams(const char *, const ConnectionClass *,
po_ind_t *multi, po_ind_t *proc_return);
BOOL SC_IsExecuting(const StatementClass *self);
+BOOL SC_ExecutionInProgress(const StatementClass *self);
BOOL SC_SetExecuting(StatementClass *self, BOOL on);
BOOL SC_SetCancelRequest(StatementClass *self);
BOOL SC_AcceptedCancelRequest(const StatementClass *self);
diff --git a/test/expected/arraybinding.out b/test/expected/arraybinding.out
index 5eebcd2b..27a41bef 100644
--- a/test/expected/arraybinding.out
+++ b/test/expected/arraybinding.out
@@ -26,4 +26,10 @@ Result set:
0 columnwise 0
1 columnwise 1
9999 columnwise 9999
+Parameter Status
+Number of rows in table:
+Result set:
+9993
+Result set:
+0 columnwise 0
disconnecting
diff --git a/test/expected/bookmark-buffer-length.out b/test/expected/bookmark-buffer-length.out
new file mode 100644
index 00000000..163a2302
--- /dev/null
+++ b/test/expected/bookmark-buffer-length.out
@@ -0,0 +1,5 @@
+connected
+BufferLength 16: SQL_SUCCESS, indicator 16, bytes after the buffer untouched
+BufferLength 2: SQL_SUCCESS_WITH_INFO 01004, indicator 4, bytes after the buffer untouched
+BufferLength 0: SQL_SUCCESS_WITH_INFO 01004, indicator 4, bytes after the buffer untouched
+disconnecting
diff --git a/test/expected/bulk-bookmark-declare-fetch.out b/test/expected/bulk-bookmark-declare-fetch.out
new file mode 100644
index 00000000..b4f96e00
--- /dev/null
+++ b/test/expected/bulk-bookmark-declare-fetch.out
@@ -0,0 +1,6 @@
+connected
+edit row 2, then delete by the bookmark of row 301 (id 301): SQL_SUCCESS, changed rows: 2=edited, 301=DELETED
+edit row 1, then delete by the bookmark of row 301 (id 301): SQL_SUCCESS, changed rows: 1=edited, 301=DELETED
+edit row 2, then update by the bookmark of row 301 (id 301): SQL_SUCCESS, changed rows: 2=edited, 301=updated by bookmark
+edit row 1, then update by the bookmark of row 301 (id 301): SQL_SUCCESS, changed rows: 1=edited, 301=updated by bookmark
+disconnecting
diff --git a/test/expected/catalog-error-rollback.out b/test/expected/catalog-error-rollback.out
new file mode 100644
index 00000000..0889ad15
--- /dev/null
+++ b/test/expected/catalog-error-rollback.out
@@ -0,0 +1,10 @@
+connected
+SQLSpecialColumns existing table: succeeded, committed rows: 1 2 3
+SQLProcedures rejected name: SQLSTATE=HY000, committed rows: 1 2 3
+SQLSpecialColumns missing table: SQLSTATE=07009, committed rows: 1 2 3
+SQLTables rejected name: SQLSTATE=HY000, committed rows: 1 2 3
+SQLColumns rejected name: SQLSTATE=HY000, committed rows: 1 2 3
+SQLStatistics rejected name: SQLSTATE=HY000, committed rows: 1 2 3
+SQLPrimaryKeys rejected name: SQLSTATE=HY000, committed rows: 1 2 3
+SQLSpecialColumns rejected name: SQLSTATE=HY000, committed rows: 1 2 3
+disconnecting
diff --git a/test/expected/catalog-error-rollback_1.out b/test/expected/catalog-error-rollback_1.out
new file mode 100644
index 00000000..fe434015
--- /dev/null
+++ b/test/expected/catalog-error-rollback_1.out
@@ -0,0 +1,10 @@
+connected
+SQLSpecialColumns existing table: succeeded, committed rows: 1 2 3
+SQLProcedures rejected name: succeeded, committed rows: 1 2 3
+SQLSpecialColumns missing table: SQLSTATE=07009, committed rows: 1 2 3
+SQLTables rejected name: succeeded, committed rows: 1 2 3
+SQLColumns rejected name: succeeded, committed rows: 1 2 3
+SQLStatistics rejected name: succeeded, committed rows: 1 2 3
+SQLPrimaryKeys rejected name: succeeded, committed rows: 1 2 3
+SQLSpecialColumns rejected name: SQLSTATE=07009, committed rows: 1 2 3
+disconnecting
diff --git a/test/expected/commit-failure.out b/test/expected/commit-failure.out
new file mode 100644
index 00000000..ab532596
--- /dev/null
+++ b/test/expected/commit-failure.out
@@ -0,0 +1,9 @@
+connected
+SQLEndTran with a deferred violation: reported an error
+autocommit on with a deferred violation: reported an error
+rows in commitfail_c: 0
+disconnecting
+connected
+failing statement: reported an error
+SQLEndTran of a failed transaction: reported an error
+disconnecting
diff --git a/test/expected/copydesc-param-name.out b/test/expected/copydesc-param-name.out
new file mode 100644
index 00000000..b7a239d4
--- /dev/null
+++ b/test/expected/copydesc-param-name.out
@@ -0,0 +1,5 @@
+connected
+copied the IPD
+the copy's parameter name after the source is freed: param_one
+freed both statements
+disconnecting
diff --git a/test/expected/desc-threads.out b/test/expected/desc-threads.out
new file mode 100644
index 00000000..18fad7b8
--- /dev/null
+++ b/test/expected/desc-threads.out
@@ -0,0 +1,4 @@
+connected
+fetch while rebinding: 20000 of 20000 rows, 0 descriptor errors
+copies in both directions: 0 errors
+disconnecting
diff --git a/test/expected/descrec.out b/test/expected/descrec.out
index 9b5785af..d616bbd5 100644
--- a/test/expected/descrec.out
+++ b/test/expected/descrec.out
@@ -35,4 +35,12 @@ SQL_DESC_NULLABLE: 0
-- SQLSetDescRec ARD binding --
VALUE: 42
INDICATOR: 2
+
+-- length fields as SQLLEN --
+ARD SQL_DESC_OCTET_LENGTH: 16
+APD SQL_DESC_OCTET_LENGTH: 16
+IPD SQL_DESC_OCTET_LENGTH: 0
+IRD SQL_DESC_OCTET_LENGTH: 0
+IRD SQL_DESC_LENGTH: 4
+IRD SQL_DESC_DISPLAY_SIZE: 11
disconnecting
diff --git a/test/expected/descrec_1.out b/test/expected/descrec_1.out
index 156e7e43..48bea452 100644
--- a/test/expected/descrec_1.out
+++ b/test/expected/descrec_1.out
@@ -35,4 +35,12 @@ SQL_DESC_NULLABLE: 0
-- SQLSetDescRec ARD binding --
VALUE: 42
INDICATOR: 2
+
+-- length fields as SQLLEN --
+ARD SQL_DESC_OCTET_LENGTH: 16
+APD SQL_DESC_OCTET_LENGTH: 16
+IPD SQL_DESC_OCTET_LENGTH: 0
+IRD SQL_DESC_OCTET_LENGTH: 0
+IRD SQL_DESC_LENGTH: 4
+IRD SQL_DESC_DISPLAY_SIZE: 11
disconnecting
diff --git a/test/expected/descrec_2.out b/test/expected/descrec_2.out
index b0c85a7c..b3a18488 100644
--- a/test/expected/descrec_2.out
+++ b/test/expected/descrec_2.out
@@ -35,4 +35,12 @@ SQL_DESC_NULLABLE: 0
-- SQLSetDescRec ARD binding --
VALUE: 42
INDICATOR: 2
+
+-- length fields as SQLLEN --
+ARD SQL_DESC_OCTET_LENGTH: 16
+APD SQL_DESC_OCTET_LENGTH: 16
+IPD SQL_DESC_OCTET_LENGTH: 0
+IRD SQL_DESC_OCTET_LENGTH: 0
+IRD SQL_DESC_LENGTH: 4
+IRD SQL_DESC_DISPLAY_SIZE: 11
disconnecting
diff --git a/test/expected/diag-threads.out b/test/expected/diag-threads.out
new file mode 100644
index 00000000..c913bf68
--- /dev/null
+++ b/test/expected/diag-threads.out
@@ -0,0 +1,4 @@
+connected
+statement: 2000 of 2000 calls failed as expected, 0 unexpected diagnostics
+connection: 2000 of 2000 calls failed as expected, 0 unexpected diagnostics
+disconnecting
diff --git a/test/expected/diagnostic-w.out b/test/expected/diagnostic-w.out
new file mode 100644
index 00000000..5a33c837
--- /dev/null
+++ b/test/expected/diagnostic-w.out
@@ -0,0 +1,11 @@
+connected
+SQLExecDirectW: SQL_ERROR
+SQLGetDiagFieldW(256): SQL_SUCCESS_WITH_INFO, StringLength positive
+ERROR: invalid input syntax for type integer: "ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸
+SQLGetDiagFieldW(4000): SQL_SUCCESS, StringLength 962
+ERROR: invalid input syntax for type integer: "ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸";
+Error while executing the query
+SQLGetDiagRecW(128): SQL_SUCCESS, TextLength 73
+22P02
+ERROR: invalid input syntax for type integer: "ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸ä¸
+disconnecting
diff --git a/test/expected/error-rollback-readonly.out b/test/expected/error-rollback-readonly.out
new file mode 100644
index 00000000..54149ffb
--- /dev/null
+++ b/test/expected/error-rollback-readonly.out
@@ -0,0 +1,26 @@
+connected
+Transaction 1: insert, failing insert, insert
+ insert 1: ok
+ insert -1: SQLSTATE=23514
+ insert 2: ok
+ committed rows: 1 2
+Transaction 2: insert, SQLProcedureColumns, failing insert, insert
+ insert 1: ok
+ SQLProcedureColumns: ok
+ insert -1: SQLSTATE=23514
+ insert 2: ok
+ committed rows: 1 2
+Transaction 3: insert, fetch, SQLSetPos update, failing insert, insert
+ insert 1: ok
+ fetch: 1
+ SQLSetPos update to 5: ok
+ insert -1: SQLSTATE=23514
+ insert 2: ok
+ committed rows: 2 5
+Transaction 4: insert, fetch, failing SQLBulkOperations add, insert
+ insert 1: ok
+ fetch: 1
+ SQLBulkOperations add -1: SQLSTATE=23514
+ insert 2: ok
+ committed rows: 1 2
+disconnecting
diff --git a/test/expected/extendedfetch-rowcount.out b/test/expected/extendedfetch-rowcount.out
new file mode 100644
index 00000000..1fb48cc7
--- /dev/null
+++ b/test/expected/extendedfetch-rowcount.out
@@ -0,0 +1,26 @@
+connected
+SELECT id FROM generate_series(1, 10) AS id
+next: SQLExtendedFetch returned 0, rows in page: 3
+ 1
+ 2
+ 3
+next: SQLExtendedFetch returned 0, rows in page: 3
+ 4
+ 5
+ 6
+prev: SQLExtendedFetch returned 0, rows in page: 3
+ 1
+ 2
+ 3
+WITH ids AS (SELECT generate_series(1, 10) AS id) SELECT id FROM ids
+next: SQLExtendedFetch returned 0, rows in page: 3
+ 1
+ 2
+ 3
+next: SQLExtendedFetch returned 0, rows in page: 3
+ 4
+ 5
+ 6
+prev: SQLExtendedFetch returned -1, rows in page: 0
+HY106=The fetch type for PGAPI_ExtendedFetch isn't allowed with ForwardOnly cursor.
+disconnecting
diff --git a/test/expected/fetch-before-first.out b/test/expected/fetch-before-first.out
new file mode 100644
index 00000000..0298be26
--- /dev/null
+++ b/test/expected/fetch-before-first.out
@@ -0,0 +1,9 @@
+connected
+SQLFetchScroll(SQL_FETCH_ABSOLUTE, 1): ids 1 2 3
+SQLSetPos(1, SQL_DELETE): ok
+SQLFetchScroll(SQL_FETCH_ABSOLUTE, 0): no data
+SQLFetchScroll(SQL_FETCH_RELATIVE, 0): ids 2 3 4
+SQLFetchScroll(SQL_FETCH_FIRST, 0): ids 2 3 4
+SQLFetchScroll(SQL_FETCH_RELATIVE, -3): no data
+SQLFetchScroll(SQL_FETCH_RELATIVE, 0): ids 2 3 4
+disconnecting
diff --git a/test/expected/fetch-refcursors.out b/test/expected/fetch-refcursors.out
index a594d4d1..32226d6e 100644
--- a/test/expected/fetch-refcursors.out
+++ b/test/expected/fetch-refcursors.out
@@ -54,3 +54,12 @@ foobar 3
bar 2
foo 1
disconnecting
+
+-- TEST closing a statement with refcursor results after a commit
+connected
+--1 Result set:
+1 foo
+2 bar
+3 foobar
+rows committed: 1
+disconnecting
diff --git a/test/expected/getdata-binary-nodata.out b/test/expected/getdata-binary-nodata.out
new file mode 100644
index 00000000..13cb235f
--- /dev/null
+++ b/test/expected/getdata-binary-nodata.out
@@ -0,0 +1,8 @@
+connected
+SELECT '\x00112233'::bytea, buflen 64: SQL_SUCCESS(4) SQL_NO_DATA
+SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid, buflen 64: SQL_SUCCESS(16) SQL_NO_DATA
+SELECT 123456::int4, buflen 64: SQL_SUCCESS(4) SQL_NO_DATA
+SELECT '\x00112233'::bytea, buflen 3: SQL_SUCCESS_WITH_INFO(4) SQL_SUCCESS(1) SQL_NO_DATA
+SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid, buflen 3: SQL_SUCCESS_WITH_INFO(16) SQL_NO_DATA
+SELECT 123456::int4, buflen 3: SQL_SUCCESS_WITH_INFO(4) SQL_NO_DATA
+disconnecting
diff --git a/test/expected/identity.out b/test/expected/identity.out
index ee0b189f..c94a1359 100644
--- a/test/expected/identity.out
+++ b/test/expected/identity.out
@@ -29,4 +29,9 @@ Result set:
1 case-sensitive name
Result set:
NULL
+# of result cols: 1
+Result set:
+NULL
+Result set:
+NULL
disconnecting
diff --git a/test/expected/inheritance-keyset.out b/test/expected/inheritance-keyset.out
new file mode 100644
index 00000000..c4e24210
--- /dev/null
+++ b/test/expected/inheritance-keyset.out
@@ -0,0 +1,29 @@
+connected
+Opening a keyset-driven cursor on the parent's rows
+row 1: 1 p1
+row 2: 2 p2
+row 3: 3 p3
+
+Another session updates row 1 and deletes row 2
+
+Re-fetching the rows of the cursor
+row 3: 3 p3
+row 2: deleted
+row 1: 1 p1 updated (updated)
+
+Deleting row 3 through the cursor
+row 3: 3 p3
+row 3: no data
+
+Fetching rows 1 and 2 by bookmark
+row 1: 1 p1 updated
+row 2: NULL NULL
+
+Querying the tables again
+Result set:
+inh_parent (0,4) 1 p1 updated
+inh_child (0,1) 11 c1
+inh_child (0,2) 12 c2
+inh_child (0,3) 13 c3
+inh_child (0,4) 14 c4
+disconnecting
diff --git a/test/expected/interval-type-name.out b/test/expected/interval-type-name.out
new file mode 100644
index 00000000..94dde2a4
--- /dev/null
+++ b/test/expected/interval-type-name.out
@@ -0,0 +1,10 @@
+connected
+plain_interval: SQL_DESC_TYPE_NAME: interval (length 8)
+plain_interval: SQL_DESC_LOCAL_TYPE_NAME: interval (length 8)
+interval_day: SQL_DESC_TYPE_NAME: interval day (length 12)
+interval_day: SQL_DESC_LOCAL_TYPE_NAME: interval day (length 12)
+interval_year_to_month: SQL_DESC_TYPE_NAME: interval year to month (length 22)
+interval_year_to_month: SQL_DESC_LOCAL_TYPE_NAME: interval year to month (length 22)
+interval_second: SQL_DESC_TYPE_NAME: interval second (length 15)
+interval_second: SQL_DESC_LOCAL_TYPE_NAME: interval second (length 15)
+disconnecting
diff --git a/test/expected/ird-smallint-fields.out b/test/expected/ird-smallint-fields.out
new file mode 100644
index 00000000..bdcac89d
--- /dev/null
+++ b/test/expected/ird-smallint-fields.out
@@ -0,0 +1,29 @@
+connected
+
+-- Header --
+SQL_DESC_COUNT: 2 (length 2)
+
+-- Column 1 --
+SQL_DESC_CONCISE_TYPE: 4 (length 2)
+SQL_DESC_FIXED_PREC_SCALE: 0 (length 2)
+SQL_DESC_NULLABLE: 1 (length 2)
+SQL_DESC_PRECISION: 0 (length 2)
+SQL_DESC_SCALE: 0 (length 2)
+SQL_DESC_SEARCHABLE: 2 (length 2)
+SQL_DESC_TYPE: 4 (length 2)
+SQL_DESC_UNNAMED: 0 (length 2)
+SQL_DESC_UNSIGNED: 0 (length 2)
+SQL_DESC_UPDATABLE: 0 (length 2)
+
+-- Column 2 --
+SQL_DESC_CONCISE_TYPE: -1 (length 2)
+SQL_DESC_FIXED_PREC_SCALE: 0 (length 2)
+SQL_DESC_NULLABLE: 1 (length 2)
+SQL_DESC_PRECISION: 0 (length 2)
+SQL_DESC_SCALE: 0 (length 2)
+SQL_DESC_SEARCHABLE: 3 (length 2)
+SQL_DESC_TYPE: -1 (length 2)
+SQL_DESC_UNNAMED: 0 (length 2)
+SQL_DESC_UNSIGNED: 1 (length 2)
+SQL_DESC_UPDATABLE: 0 (length 2)
+disconnecting
diff --git a/test/expected/large-object-open-error.out b/test/expected/large-object-open-error.out
new file mode 100644
index 00000000..cc22e6af
--- /dev/null
+++ b/test/expected/large-object-open-error.out
@@ -0,0 +1,7 @@
+connected
+row 1: first
+row 2: failed
+HY000=Couldnt open large object for reading.
+row 3: third
+update ok
+disconnecting
diff --git a/test/expected/large-object.out b/test/expected/large-object.out
index 1223fe78..be006085 100644
--- a/test/expected/large-object.out
+++ b/test/expected/large-object.out
@@ -2,6 +2,9 @@ connected
inserting large object...
reading it back...
hex: 0102030405060708
+reading back a part of it and closing the cursor...
+hex: 01020304
+vacuum succeeded
inserting large object from hex string...
reading it back...
hex: 0A0B0C0D0E0F
diff --git a/test/expected/lost-connection-commit.out b/test/expected/lost-connection-commit.out
new file mode 100644
index 00000000..a17a52ad
--- /dev/null
+++ b/test/expected/lost-connection-commit.out
@@ -0,0 +1,9 @@
+connected
+killing connection...
+SQLFreeHandle: succeeded
+SQLEndTran(SQL_COMMIT) failed
+08S01=Could not commit, the connection was lost
+SQLSetConnectAttr(SQL_AUTOCOMMIT_ON) failed
+08S01=Could not commit, the connection was lost
+SQLEndTran(SQL_ROLLBACK) succeeded
+disconnecting
diff --git a/test/expected/lost-connection-commit_1.out b/test/expected/lost-connection-commit_1.out
new file mode 100644
index 00000000..211433ac
--- /dev/null
+++ b/test/expected/lost-connection-commit_1.out
@@ -0,0 +1,9 @@
+connected
+killing connection...
+SQLFreeHandle: succeeded
+SQLEndTran(SQL_COMMIT) failed
+57P01=FATAL: terminating connection due to administrator command
+SQLSetConnectAttr(SQL_AUTOCOMMIT_ON) failed
+08S01=Could not commit, the connection was lost
+SQLEndTran(SQL_ROLLBACK) succeeded
+disconnecting
diff --git a/test/expected/odbc-escapes.out b/test/expected/odbc-escapes.out
index 63b742ac..f533791f 100644
--- a/test/expected/odbc-escapes.out
+++ b/test/expected/odbc-escapes.out
@@ -41,6 +41,13 @@ Result set:
OUT param: 3
+Query: { ? = call length(?) }
+Param 1 is an OUT parameter
+Param 2: foobar
+Result set:
+
+OUT param: 6
+
Query: { ? = call concat(?::text, ?::text) }
Param 1 is an OUT parameter
Param 2: foo
@@ -136,6 +143,13 @@ Result set:
OUT param: 3
+Query: { ? = call length(?) }
+Param 1 is an OUT parameter
+Param 2: foobar
+Result set:
+
+OUT param: 6
+
Query: { ? = call concat(?::text, ?::text) }
Param 1 is an OUT parameter
Param 2: foo
diff --git a/test/expected/odbc-escapes_1.out b/test/expected/odbc-escapes_1.out
index b3b84414..9d3cda74 100644
--- a/test/expected/odbc-escapes_1.out
+++ b/test/expected/odbc-escapes_1.out
@@ -41,6 +41,13 @@ Result set:
OUT param: 3
+Query: { ? = call length(?) }
+Param 1 is an OUT parameter
+Param 2: foobar
+Result set:
+
+OUT param: 6
+
Query: { ? = call concat(?::text, ?::text) }
Param 1 is an OUT parameter
Param 2: foo
@@ -136,6 +143,13 @@ Result set:
OUT param: 3
+Query: { ? = call length(?) }
+Param 1 is an OUT parameter
+Param 2: foobar
+Result set:
+
+OUT param: 6
+
Query: { ? = call concat(?::text, ?::text) }
Param 1 is an OUT parameter
Param 2: foo
diff --git a/test/expected/param-negative-length.out b/test/expected/param-negative-length.out
new file mode 100644
index 00000000..a6af64ac
--- /dev/null
+++ b/test/expected/param-negative-length.out
@@ -0,0 +1,12 @@
+connected
+SQL_C_CHAR -> SQL_INTEGER
+length 3: 123
+length -3: 123
+length -10: SQLExecDirect failed
+HY024=Invalid string or buffer length
+SQL_C_BINARY -> SQL_VARBINARY
+length 3: 010203
+length -1: NULL
+length -4: SQLExecDirect failed
+HY024=Invalid string or buffer length
+disconnecting
diff --git a/test/expected/positioned-delete-rollback.out b/test/expected/positioned-delete-rollback.out
new file mode 100644
index 00000000..91b78230
--- /dev/null
+++ b/test/expected/positioned-delete-rollback.out
@@ -0,0 +1,14 @@
+connected
+Case 1: partitioned table, the INSERT after the delete succeeds
+ order 1 deleted with SQLSetPos
+ note 8 inserted
+ orders left after commit: 2
+Case 2: plain table, the INSERT after the delete fails
+ order 1 deleted with SQLSetPos
+ note 7 refused, SQLSTATE=23505
+ orders left after commit: 2
+Case 3: partitioned table, the INSERT after the delete fails
+ order 1 deleted with SQLSetPos
+ note 7 refused, SQLSTATE=23505
+ orders left after commit: 2
+disconnecting
diff --git a/test/expected/pqopt-many.out b/test/expected/pqopt-many.out
new file mode 100644
index 00000000..ee388ea7
--- /dev/null
+++ b/test/expected/pqopt-many.out
@@ -0,0 +1,4 @@
+target_session_attrs=any: connected
+application_name: pqopt_many
+work_mem: 4MB
+target_session_attrs=read-only: refused
diff --git a/test/expected/putdata-descriptor-params.out b/test/expected/putdata-descriptor-params.out
new file mode 100644
index 00000000..2d1668cb
--- /dev/null
+++ b/test/expected/putdata-descriptor-params.out
@@ -0,0 +1,12 @@
+connected
+SELECT 'got ' || ?::text, data for parameter 1
+SQLExecute: SQL_NEED_DATA
+SQLParamData: SQL_NEED_DATA
+SQLPutData succeeded
+result: got abc
+SELECT 'got ' || ?::text || ?::text, data for parameter 2
+SQLExecute: SQL_NEED_DATA
+SQLParamData: SQL_NEED_DATA
+SQLPutData succeeded
+result: got xabc
+disconnecting
diff --git a/test/expected/query-timeout.out b/test/expected/query-timeout.out
new file mode 100644
index 00000000..82a7c3b5
--- /dev/null
+++ b/test/expected/query-timeout.out
@@ -0,0 +1,21 @@
+connected
+-- SET statement_timeout = 1s inside a transaction, then ROLLBACK
+timeout 1 before rollback: cancelled with SQLSTATE 57014
+timeout 1 after rollback: cancelled with SQLSTATE 57014
+SHOW statement_timeout: Result set:
+1s
+-- SET statement_timeout = 0 inside a transaction, then ROLLBACK
+no timeout after rollback: not cancelled
+SHOW statement_timeout: Result set:
+0
+-- SET statement_timeout = 1s after a SAVEPOINT, then ROLLBACK TO it
+SHOW statement_timeout: Result set:
+1s
+timeout 1 after rollback to savepoint: cancelled with SQLSTATE 57014
+SHOW statement_timeout: Result set:
+1s
+-- SET statement_timeout = 1s inside a transaction, then COMMIT
+no timeout after commit: not cancelled
+SHOW statement_timeout: Result set:
+0
+disconnecting
diff --git a/test/expected/query-timeout_1.out b/test/expected/query-timeout_1.out
new file mode 100644
index 00000000..d09d5ba0
--- /dev/null
+++ b/test/expected/query-timeout_1.out
@@ -0,0 +1,19 @@
+connected
+-- SET statement_timeout = 1s inside a transaction, then ROLLBACK
+timeout 1 before rollback: cancelled with SQLSTATE 57014
+timeout 1 after rollback: cancelled with SQLSTATE 57014
+SHOW statement_timeout: not readable, SQLSTATE 25P02
+-- SET statement_timeout = 0 inside a transaction, then ROLLBACK
+no timeout after rollback: not cancelled
+SHOW statement_timeout: Result set:
+0
+-- SET statement_timeout = 1s after a SAVEPOINT, then ROLLBACK TO it
+SHOW statement_timeout: Result set:
+1s
+timeout 1 after rollback to savepoint: cancelled with SQLSTATE 57014
+SHOW statement_timeout: not readable, SQLSTATE 25P02
+-- SET statement_timeout = 1s inside a transaction, then COMMIT
+no timeout after commit: not cancelled
+SHOW statement_timeout: Result set:
+0
+disconnecting
diff --git a/test/runsuite.c b/test/runsuite.c
index 6610e68e..00f733be 100644
--- a/test/runsuite.c
+++ b/test/runsuite.c
@@ -416,9 +416,9 @@ rundiff(const char *testname, const char *inputdir, int server_version)
{
/*
* Diff only against expected files that exist. A missing
- * one (most tests have none in the version directory) makes
- * diff write nothing to tmpdiff, which would otherwise be
- * taken as "no difference" and pass the test.
+ * one (most tests have none in the version directory)
+ * leaves tmpdiff empty, which would otherwise be taken
+ * as "no difference" and pass the test.
*/
if (0 == i)
snprintf(filename, sizeof(filename), "%s%s%s.out", inputdir, dirs[d], testname);
diff --git a/test/src/arraybinding-test.c b/test/src/arraybinding-test.c
index d9204a81..99555101 100644
--- a/test/src/arraybinding-test.c
+++ b/test/src/arraybinding-test.c
@@ -224,6 +224,89 @@ int main(int argc, char **argv)
rc = SQLFreeStmt(hstmt, SQL_CLOSE);
CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ /****
+ * 3. Test column-wise binding of a fixed-length type as SQL_C_DEFAULT.
+ * BufferLength is ignored for fixed-length types, so the rows of the
+ * array must be found sizeof(SQLINTEGER) apart, not BufferLength apart.
+ */
+ int_array[0] = 1;
+ int_array[1] = 9999;
+ int_ind_array[0] = int_ind_array[1] = 0;
+
+ SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_BIND_TYPE, SQL_PARAM_BIND_BY_COLUMN, 0);
+ SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_STATUS_PTR, status_array, 0);
+ SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMS_PROCESSED_PTR, &nprocessed, 0);
+ SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER) 2, 0);
+
+ /* Bind the parameter array. */
+ SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_DEFAULT, SQL_INTEGER, 5, 0,
+ int_array, 0, int_ind_array);
+
+ /* Execute */
+ sql = "DELETE FROM tmptable WHERE i = ?";
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ /* Fetch results */
+ printf("Parameter Status\n");
+ for (i = 0; i < nprocessed; i++)
+ {
+ switch (status_array[i])
+ {
+ case SQL_PARAM_SUCCESS:
+ case SQL_PARAM_SUCCESS_WITH_INFO:
+ break;
+
+ case SQL_PARAM_ERROR:
+ printf("%d\tError\n", i);
+ break;
+
+ case SQL_PARAM_UNUSED:
+ printf("%d\tUnused\n", i);
+ break;
+
+ case SQL_PARAM_DIAG_UNAVAILABLE:
+ printf("%d\tDiag unavailable\n", i);
+ break;
+ }
+ }
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ /*
+ * Free and allocate a new handle for the next SELECT statement, as we don't
+ * want to array bind that one. The parameters set with SQLSetStmtAttr
+ * survive SQLFreeStmt.
+ */
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ /* Check that both rows were deleted */
+ printf("Number of rows in table:\n");
+ sql = "SELECT COUNT(*) FROM tmptable";
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ print_result(hstmt);
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ sql = "SELECT * FROM tmptable WHERE i IN (0, 1, 9999) ORDER BY i";
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ print_result(hstmt);
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
/* Clean up */
test_disconnect();
diff --git a/test/src/bookmark-buffer-length-test.c b/test/src/bookmark-buffer-length-test.c
new file mode 100644
index 00000000..ee50f49f
--- /dev/null
+++ b/test/src/bookmark-buffer-length-test.c
@@ -0,0 +1,93 @@
+/*
+ * Test a bookmark column (column 0) bound as SQL_C_VARBOOKMARK with a
+ * buffer shorter than the 4-byte row number bookmark.
+ *
+ * The driver must not write more than BufferLength bytes into the buffer.
+ * A bookmark that does not fit is truncated: the fetch returns 01004 and
+ * the indicator holds the length of the whole bookmark.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+#define BUF_SIZE 24
+#define GUARD 0x5a
+
+static void
+fetch_with_buffer_length(HSTMT hstmt, SQLLEN buflen)
+{
+ SQLRETURN rc;
+ unsigned char buf[BUF_SIZE];
+ SQLLEN ind = 0;
+ SQLLEN i;
+ int touched = 0;
+
+ memset(buf, GUARD, sizeof(buf));
+ rc = SQLBindCol(hstmt, 0, SQL_C_VARBOOKMARK, buf, buflen, &ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *)
+ "SELECT g FROM generate_series(1, 3) g", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ rc = SQLFetch(hstmt);
+ printf("BufferLength %d: ", (int) buflen);
+ if (SQL_SUCCESS == rc)
+ printf("SQL_SUCCESS");
+ else if (SQL_SUCCESS_WITH_INFO == rc)
+ {
+ SQLCHAR state[6] = "";
+ SQLINTEGER native;
+ SQLCHAR msg[256];
+ SQLSMALLINT len;
+
+ SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, state, &native,
+ msg, sizeof(msg), &len);
+ printf("SQL_SUCCESS_WITH_INFO %s", (char *) state);
+ }
+ else
+ {
+ print_diag("SQLFetch failed", SQL_HANDLE_STMT, hstmt);
+ exit(1);
+ }
+
+ for (i = buflen; i < BUF_SIZE; i++)
+ if (buf[i] != GUARD)
+ touched = 1;
+ printf(", indicator %d, bytes after the buffer %s\n", (int) ind,
+ touched ? "overwritten" : "untouched");
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_UNBIND);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER) SQL_CURSOR_STATIC, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_USE_BOOKMARKS,
+ (SQLPOINTER) SQL_UB_VARIABLE, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+
+ /* room for the whole bookmark */
+ fetch_with_buffer_length(hstmt, 16);
+ /* shorter than the 4-byte row number bookmark */
+ fetch_with_buffer_length(hstmt, 2);
+ fetch_with_buffer_length(hstmt, 0);
+
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ test_disconnect();
+ return 0;
+}
diff --git a/test/src/bulk-bookmark-declare-fetch-test.c b/test/src/bulk-bookmark-declare-fetch-test.c
new file mode 100644
index 00000000..e55a44d5
--- /dev/null
+++ b/test/src/bulk-bookmark-declare-fetch-test.c
@@ -0,0 +1,140 @@
+/*
+ * Test SQLBulkOperations() by bookmark in declare/fetch mode, on a row that
+ * is no longer in the row cache, after another row was updated through the
+ * same cursor.
+ */
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+#define BOOKMARKED_ROW 301
+#define BOOKMARK_SIZE 16
+
+/* Print the rows of the table that differ from what was inserted. */
+static void
+printChangedRows(void)
+{
+ int rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ char changed[200];
+ SQLLEN ind;
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *)
+ "SELECT string_agg(g || '=' || coalesce(note, 'DELETED'), ', ' ORDER BY g) "
+ "FROM generate_series(1, 400) g LEFT JOIN bulkbookmark_test ON id = g "
+ "WHERE note IS DISTINCT FROM 'original'", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLGetData(hstmt, 1, SQL_C_CHAR, changed, sizeof(changed), &ind);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ printf("changed rows: %s\n", changed);
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+}
+
+/*
+ * Update row_to_edit with SQLSetPos(SQL_UPDATE), save the bookmark of
+ * BOOKMARKED_ROW, scroll away from it, then pass the saved bookmark to
+ * SQLBulkOperations(operation).
+ */
+static void
+editThenBulkOperation(int row_to_edit, SQLSMALLINT operation)
+{
+ int rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLINTEGER id;
+ SQLLEN id_ind;
+ char note[40];
+ SQLLEN note_ind;
+ char bookmark[BOOKMARK_SIZE];
+ SQLLEN bookmark_ind;
+ char saved_bookmark[BOOKMARK_SIZE];
+ SQLLEN saved_bookmark_ind;
+ SQLINTEGER saved_bookmark_id;
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "DROP TABLE IF EXISTS bulkbookmark_test", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "CREATE TEMPORARY TABLE bulkbookmark_test(id int4 primary key, note text)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "INSERT INTO bulkbookmark_test SELECT g, 'original' FROM generate_series(1, 400) g", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CONCURRENCY, (SQLPOINTER) SQL_CONCUR_ROWVER, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_TYPE, (SQLPOINTER) SQL_CURSOR_STATIC, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_USE_BOOKMARKS, (SQLPOINTER) SQL_UB_VARIABLE, SQL_IS_UINTEGER);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+
+ rc = SQLBindCol(hstmt, 0, SQL_C_VARBOOKMARK, bookmark, sizeof(bookmark), &bookmark_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_LONG, &id, 0, &id_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, note, sizeof(note), ¬e_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT id, note FROM bulkbookmark_test ORDER BY id", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_ABSOLUTE, row_to_edit);
+ CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", hstmt);
+ strcpy(note, "edited");
+ note_ind = SQL_NTS;
+ rc = SQLSetPos(hstmt, 1, SQL_UPDATE, SQL_LOCK_NO_CHANGE);
+ CHECK_STMT_RESULT(rc, "SQLSetPos failed", hstmt);
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_ABSOLUTE, BOOKMARKED_ROW);
+ CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", hstmt);
+ memcpy(saved_bookmark, bookmark, sizeof(bookmark));
+ saved_bookmark_ind = bookmark_ind;
+ saved_bookmark_id = id;
+
+ /* 150 rows back: more than Fetch, so the bookmarked row leaves the cache */
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_ABSOLUTE, BOOKMARKED_ROW - 150);
+ CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", hstmt);
+
+ /* One-row bookmark array; for the update, only note gets a new value */
+ memcpy(bookmark, saved_bookmark, sizeof(bookmark));
+ bookmark_ind = saved_bookmark_ind;
+ id_ind = SQL_COLUMN_IGNORE;
+ strcpy(note, "updated by bookmark");
+ note_ind = SQL_NTS;
+ rc = SQLBulkOperations(hstmt, operation);
+ CHECK_STMT_RESULT(rc, "SQLBulkOperations failed", hstmt);
+ printf("edit row %d, then %s by the bookmark of row %d (id %d): %s, ",
+ row_to_edit,
+ operation == SQL_DELETE_BY_BOOKMARK ? "delete" : "update",
+ BOOKMARKED_ROW, (int) saved_bookmark_id,
+ rc == SQL_SUCCESS ? "SQL_SUCCESS" : "SQL_SUCCESS_WITH_INFO");
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+
+ printChangedRows();
+}
+
+int main(int argc, char **argv)
+{
+ /* Fetch=100 is the default: the driver caches 100 rows at a time */
+ test_connect_ext("UseDeclareFetch=1;Fetch=100");
+
+ editThenBulkOperation(2, SQL_DELETE_BY_BOOKMARK);
+ editThenBulkOperation(1, SQL_DELETE_BY_BOOKMARK);
+ editThenBulkOperation(2, SQL_UPDATE_BY_BOOKMARK);
+ editThenBulkOperation(1, SQL_UPDATE_BY_BOOKMARK);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/catalog-error-rollback-test.c b/test/src/catalog-error-rollback-test.c
new file mode 100644
index 00000000..7399a7a5
--- /dev/null
+++ b/test/src/catalog-error-rollback-test.c
@@ -0,0 +1,150 @@
+/*
+ * Under statement-level rollback a failed catalog call must undo its own
+ * work only. Each case inserts rows 1 and 2, makes one catalog call, inserts
+ * row 3 and commits; all three rows must be committed.
+ *
+ * catalog-error-rollback_1.out is the output on Windows: there the ANSI
+ * entry points convert the name from the ANSI code page, where 0xe9 is a
+ * valid character, so the "rejected name" calls succeed instead. The
+ * missing table case still fails there and still checks the rollback.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+static HSTMT hstmt = SQL_NULL_HSTMT;
+
+/* a lone 0xe9 is not valid UTF-8, so the server rejects a query containing it */
+static SQLCHAR rejected_name[] = "caf\xe9";
+
+static void
+exec_sql(const char *sql)
+{
+ SQLRETURN rc;
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+}
+
+static void
+commit(void)
+{
+ SQLRETURN rc;
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+}
+
+static void
+begin_case(void)
+{
+ exec_sql("INSERT INTO rollbacktab VALUES (1)");
+ exec_sql("INSERT INTO rollbacktab VALUES (2)");
+}
+
+static void
+end_case(const char *label, SQLRETURN catalog_rc)
+{
+ SQLRETURN rc;
+ SQLCHAR sqlstate[6] = "";
+ SQLCHAR row[16];
+
+ if (SQL_SUCCEEDED(catalog_rc))
+ printf("%s: succeeded", label);
+ else
+ {
+ SQLGetDiagField(SQL_HANDLE_STMT, hstmt, 1, SQL_DIAG_SQLSTATE,
+ sqlstate, sizeof(sqlstate), NULL);
+ printf("%s: SQLSTATE=%s", label, (char *) sqlstate);
+ }
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+
+ exec_sql("INSERT INTO rollbacktab VALUES (3)");
+ commit();
+
+ printf(", committed rows:");
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT i FROM rollbacktab ORDER BY i", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ while (SQL_SUCCEEDED(SQLFetch(hstmt)))
+ {
+ SQLGetData(hstmt, 1, SQL_C_CHAR, row, sizeof(row), NULL);
+ printf(" %s", (char *) row);
+ }
+ printf("\n");
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+
+ exec_sql("DELETE FROM rollbacktab");
+ commit();
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+
+ /* the default; installcheck-all also runs the suite with 7.4-1 and 7.4-0 */
+ test_connect_ext("Protocol=7.4-2");
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+
+ exec_sql("CREATE TEMPORARY TABLE rollbacktab (i int4)");
+ commit();
+
+ /* a catalog call that succeeds */
+ begin_case();
+ rc = SQLSpecialColumns(hstmt, SQL_BEST_ROWID, NULL, 0, NULL, 0,
+ (SQLCHAR *) "testtab1", SQL_NTS,
+ SQL_SCOPE_SESSION, SQL_NULLABLE);
+ end_case("SQLSpecialColumns existing table", rc);
+
+ /* a catalog call that fails on the application's own statement */
+ begin_case();
+ rc = SQLProcedures(hstmt, NULL, 0, NULL, 0, rejected_name, SQL_NTS);
+ end_case("SQLProcedures rejected name", rc);
+
+ /* the driver reports the missing table itself; the server raises no error */
+ begin_case();
+ rc = SQLSpecialColumns(hstmt, SQL_BEST_ROWID, NULL, 0, NULL, 0,
+ (SQLCHAR *) "no_such_table", SQL_NTS,
+ SQL_SCOPE_SESSION, SQL_NULLABLE);
+ end_case("SQLSpecialColumns missing table", rc);
+
+ /* the server rejects the catalog query */
+ begin_case();
+ rc = SQLTables(hstmt, NULL, 0, NULL, 0, rejected_name, SQL_NTS, NULL, 0);
+ end_case("SQLTables rejected name", rc);
+
+ begin_case();
+ rc = SQLColumns(hstmt, NULL, 0, NULL, 0, rejected_name, SQL_NTS, NULL, 0);
+ end_case("SQLColumns rejected name", rc);
+
+ begin_case();
+ rc = SQLStatistics(hstmt, NULL, 0, NULL, 0, rejected_name, SQL_NTS,
+ SQL_INDEX_ALL, SQL_QUICK);
+ end_case("SQLStatistics rejected name", rc);
+
+ begin_case();
+ rc = SQLPrimaryKeys(hstmt, NULL, 0, NULL, 0, rejected_name, SQL_NTS);
+ end_case("SQLPrimaryKeys rejected name", rc);
+
+ begin_case();
+ rc = SQLSpecialColumns(hstmt, SQL_BEST_ROWID, NULL, 0, NULL, 0,
+ rejected_name, SQL_NTS,
+ SQL_SCOPE_SESSION, SQL_NULLABLE);
+ end_case("SQLSpecialColumns rejected name", rc);
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/commit-failure-test.c b/test/src/commit-failure-test.c
new file mode 100644
index 00000000..b13e9aea
--- /dev/null
+++ b/test/src/commit-failure-test.c
@@ -0,0 +1,110 @@
+/*
+ * A COMMIT that fails must be reported, not taken for success: the
+ * transaction's work is gone. Covers a deferred constraint failing at
+ * COMMIT through SQLEndTran, SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT) and
+ * SQLSetPos, and a COMMIT of a transaction that had already failed, which
+ * the server answers with the tag ROLLBACK.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+static HSTMT hstmt = SQL_NULL_HSTMT;
+
+static void
+exec_ok(const char *sql)
+{
+ SQLRETURN rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+}
+
+static void
+set_autocommit(SQLULEN on, const char *what)
+{
+ SQLRETURN rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) on, SQL_IS_UINTEGER);
+
+ if (what)
+ printf("%s: %s\n", what, SQL_SUCCEEDED(rc) ? "reported success" : "reported an error");
+ else
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+}
+
+static void
+count_children(void)
+{
+ SQLRETURN rc;
+ SQLINTEGER n = -1;
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT count(*) FROM commitfail_c", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLGetData(hstmt, 1, SQL_C_SLONG, &n, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ printf("rows in commitfail_c: %d\n", (int) n);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+}
+
+static void
+setup(const char *options)
+{
+ SQLRETURN rc;
+
+ test_connect_ext((char *) options);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+}
+
+static void
+teardown(void)
+{
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ hstmt = SQL_NULL_HSTMT;
+ test_disconnect();
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+
+ setup("");
+ exec_ok("DROP TABLE IF EXISTS commitfail_c");
+ exec_ok("DROP TABLE IF EXISTS commitfail_p");
+ exec_ok("CREATE TABLE commitfail_p (id int PRIMARY KEY)");
+ exec_ok("CREATE TABLE commitfail_c (id int PRIMARY KEY, pid int REFERENCES commitfail_p DEFERRABLE INITIALLY DEFERRED)");
+
+ /* 1. SQLEndTran */
+ set_autocommit(SQL_AUTOCOMMIT_OFF, NULL);
+ exec_ok("INSERT INTO commitfail_c VALUES (1, 42)");
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ printf("SQLEndTran with a deferred violation: %s\n", SQL_SUCCEEDED(rc) ? "reported success" : "reported an error");
+
+ /* 2. turning autocommit on commits the open transaction */
+ exec_ok("INSERT INTO commitfail_c VALUES (2, 42)");
+ set_autocommit(SQL_AUTOCOMMIT_ON, "autocommit on with a deferred violation");
+ count_children();
+ teardown();
+
+ /* 3. COMMIT of a failed transaction; the driver doesn't roll back statements */
+ setup("Protocol=7.4-0");
+ set_autocommit(SQL_AUTOCOMMIT_OFF, NULL);
+ exec_ok("INSERT INTO commitfail_p VALUES (1)");
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT 1/0", SQL_NTS);
+ printf("failing statement: %s\n", SQL_SUCCEEDED(rc) ? "reported success" : "reported an error");
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ printf("SQLEndTran of a failed transaction: %s\n", SQL_SUCCEEDED(rc) ? "reported success" : "reported an error");
+ set_autocommit(SQL_AUTOCOMMIT_ON, NULL);
+
+ exec_ok("DROP TABLE commitfail_c");
+ exec_ok("DROP TABLE commitfail_p");
+ teardown();
+
+ return 0;
+}
diff --git a/test/src/copydesc-param-name-test.c b/test/src/copydesc-param-name-test.c
new file mode 100644
index 00000000..874740d3
--- /dev/null
+++ b/test/src/copydesc-param-name-test.c
@@ -0,0 +1,56 @@
+/*
+ * Test SQLCopyDesc from an IPD that has a parameter name.
+ *
+ * The name is an allocated string. Each descriptor frees its own, so the
+ * copy must get a string of its own: it must still have the name after
+ * the source's statement is freed, and freeing both statements must not
+ * free the same string twice.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT source = SQL_NULL_HSTMT, target = SQL_NULL_HSTMT;
+ SQLHDESC source_ipd = NULL, target_ipd = NULL;
+ char name[32] = "";
+ SQLINTEGER len = 0;
+
+ test_connect();
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &source);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &target);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLGetStmtAttr(source, SQL_ATTR_IMP_PARAM_DESC, &source_ipd, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", source);
+ rc = SQLGetStmtAttr(target, SQL_ATTR_IMP_PARAM_DESC, &target_ipd, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", target);
+
+ rc = SQLSetDescField(source_ipd, 1, SQL_DESC_NAME,
+ (SQLPOINTER) "param_one", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLSetDescField failed", source);
+ rc = SQLCopyDesc(source_ipd, target_ipd);
+ CHECK_STMT_RESULT(rc, "SQLCopyDesc failed", target);
+ printf("copied the IPD\n");
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, source);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", source);
+ rc = SQLGetDescField(target_ipd, 1, SQL_DESC_NAME, name, sizeof(name),
+ &len);
+ CHECK_STMT_RESULT(rc, "SQLGetDescField failed", target);
+ printf("the copy's parameter name after the source is freed: %s\n", name);
+
+ /* a second free of the same string must not lose this line */
+ fflush(stdout);
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, target);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", target);
+ printf("freed both statements\n");
+
+ test_disconnect();
+ return 0;
+}
diff --git a/test/src/desc-threads-test.c b/test/src/desc-threads-test.c
new file mode 100644
index 00000000..8eb12a66
--- /dev/null
+++ b/test/src/desc-threads-test.c
@@ -0,0 +1,204 @@
+/*
+ * Change a statement's implicit descriptors on one thread while another
+ * thread is in calls on that statement.
+ *
+ * The descriptor functions used to take no lock, so SQLSetDescField on a
+ * statement's ARD could free or reallocate the column bindings that a
+ * SQLFetch on another thread was walking. For an implicit descriptor
+ * they now take the owning statement's lock; SQLCopyDesc between two
+ * statements' descriptors takes both, in a fixed order.
+ *
+ * A race can't be shown deterministically: this is a stress test that
+ * checks the calls work, the fetches return every row, and two SQLCopyDesc
+ * calls in opposite directions don't deadlock.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+#ifdef WIN32
+typedef HANDLE thread_t;
+#define THREAD_FUNC DWORD WINAPI
+typedef DWORD (WINAPI *thread_func_t)(void *);
+#define THREAD_RETURN return 0
+#else
+#include <pthread.h>
+typedef pthread_t thread_t;
+#define THREAD_FUNC void *
+typedef void *(*thread_func_t)(void *);
+#define THREAD_RETURN return NULL
+#endif
+
+#define QUERIES 200
+#define ROWS 100
+#define COPIES 5000
+
+static HSTMT hstmt1 = SQL_NULL_HSTMT;
+static HSTMT hstmt2 = SQL_NULL_HSTMT;
+static HSTMT hstmt3 = SQL_NULL_HSTMT;
+static SQLHDESC ard1, ard2, ard3;
+static volatile int done;
+static int rows_fetched;
+static int binder_errors;
+static int copy_errors;
+static int fetch_failed;
+
+static SQLINTEGER fetch_buf, binder_buf;
+static SQLLEN fetch_ind, binder_ind;
+
+static void
+start_thread(thread_t *t, thread_func_t func, void *arg)
+{
+#ifdef WIN32
+ *t = CreateThread(NULL, 0, func, arg, 0, NULL);
+ if (NULL == *t)
+#else
+ if (0 != pthread_create(t, NULL, func, arg))
+#endif
+ {
+ printf("could not start a thread\n");
+ exit(1);
+ }
+}
+
+static void
+join_thread(thread_t t)
+{
+#ifdef WIN32
+ WaitForSingleObject(t, INFINITE);
+ CloseHandle(t);
+#else
+ pthread_join(t, NULL);
+#endif
+}
+
+/* run a query over and over and fetch every row through the ARD */
+static THREAD_FUNC
+fetcher(void *arg)
+{
+ int i;
+ SQLRETURN rc;
+
+ for (i = 0; i < QUERIES; i++)
+ {
+ rc = SQLExecDirect(hstmt1, (SQLCHAR *) "SELECT g FROM generate_series(1, 100) g", SQL_NTS);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("SQLExecDirect failed", SQL_HANDLE_STMT, hstmt1);
+ break;
+ }
+ while (SQL_SUCCEEDED(rc = SQLFetch(hstmt1)))
+ rows_fetched++;
+ if (SQL_NO_DATA != rc && !fetch_failed++)
+ print_diag("SQLFetch failed", SQL_HANDLE_STMT, hstmt1);
+ SQLFreeStmt(hstmt1, SQL_CLOSE);
+ }
+ done = 1;
+ THREAD_RETURN;
+}
+
+/*
+ * Grow the ARD's binding array and shrink it again, which reallocates it,
+ * and bind its column to another buffer. (A count of 0 would free the
+ * array, and the driver then refuses to fetch.)
+ */
+static THREAD_FUNC
+binder(void *arg)
+{
+ SQLRETURN rc;
+ SQLINTEGER count;
+
+ while (!done)
+ {
+ rc = SQLSetDescField(ard1, 0, SQL_DESC_COUNT, (SQLPOINTER) 3, 0);
+ if (!SQL_SUCCEEDED(rc))
+ binder_errors++;
+ rc = SQLSetDescField(ard1, 0, SQL_DESC_COUNT, (SQLPOINTER) 1, 0);
+ if (!SQL_SUCCEEDED(rc))
+ binder_errors++;
+ rc = SQLSetDescRec(ard1, 1, SQL_C_LONG, 0, sizeof(binder_buf), 0, 0,
+ &binder_buf, &binder_ind, &binder_ind);
+ if (!SQL_SUCCEEDED(rc))
+ binder_errors++;
+ rc = SQLGetDescField(ard1, 0, SQL_DESC_COUNT, &count, sizeof(count), NULL);
+ if (!SQL_SUCCEEDED(rc))
+ binder_errors++;
+ }
+ THREAD_RETURN;
+}
+
+/* copy one statement's ARD to the other's, COPIES times */
+static THREAD_FUNC
+copier(void *arg)
+{
+ int forward = *(int *) arg;
+ int i;
+
+ for (i = 0; i < COPIES; i++)
+ {
+ if (!SQL_SUCCEEDED(forward ? SQLCopyDesc(ard2, ard3) : SQLCopyDesc(ard3, ard2)))
+ copy_errors++;
+ }
+ THREAD_RETURN;
+}
+
+static SQLHDESC
+get_ard(HSTMT hstmt)
+{
+ SQLHDESC ard;
+ SQLRETURN rc;
+
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, &ard, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+ return ard;
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ thread_t t1, t2;
+ int forward = 1, backward = 0;
+
+ test_connect();
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt1);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt2);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt3);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ ard1 = get_ard(hstmt1);
+ ard2 = get_ard(hstmt2);
+ ard3 = get_ard(hstmt3);
+
+ /* fetch on one thread, rebind the same statement's ARD on another */
+ rc = SQLBindCol(hstmt1, 1, SQL_C_LONG, &fetch_buf, sizeof(fetch_buf), &fetch_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt1);
+ start_thread(&t2, binder, NULL);
+ start_thread(&t1, fetcher, NULL);
+ join_thread(t1);
+ join_thread(t2);
+ printf("fetch while rebinding: %d of %d rows, %d descriptor errors\n",
+ rows_fetched, QUERIES * ROWS, binder_errors);
+
+ /* copy between two statements' ARDs in both directions at once */
+ rc = SQLBindCol(hstmt2, 1, SQL_C_LONG, &fetch_buf, sizeof(fetch_buf), &fetch_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt2);
+ rc = SQLBindCol(hstmt3, 1, SQL_C_LONG, &binder_buf, sizeof(binder_buf), &binder_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt3);
+ start_thread(&t1, copier, &forward);
+ start_thread(&t2, copier, &backward);
+ join_thread(t1);
+ join_thread(t2);
+ printf("copies in both directions: %d errors\n", copy_errors);
+
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt3);
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt2);
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt1);
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/descrec-test.c b/test/src/descrec-test.c
index 7504c672..f2ac1f07 100644
--- a/test/src/descrec-test.c
+++ b/test/src/descrec-test.c
@@ -51,6 +51,70 @@ test_setdescrec_ard_binding(void)
CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
}
+/*
+ * The length fields are SQLLEN in ODBC. Start each variable with every bit
+ * set, so that a driver writing only four bytes of it shows up as a wrong
+ * value here, and not just as stack corruption a build may not detect.
+ */
+static void
+print_len_field(const char *label, SQLHDESC hDesc, SQLSMALLINT field)
+{
+ SQLRETURN rc;
+ SQLLEN v = -1;
+
+ rc = SQLGetDescField(hDesc, 1, field, &v, sizeof(v), NULL);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("SQLGetDescField failed", SQL_HANDLE_DESC, hDesc);
+ exit(1);
+ }
+ printf("%s: %lld\n", label, (long long) v);
+}
+
+static void
+test_len_field_width(void)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLHDESC hDesc;
+ char col[16], param[16] = "1";
+ SQLLEN colind = 0, paramind = SQL_NTS;
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ rc = SQLBindCol(hstmt, 1, SQL_C_CHAR, col, sizeof(col), &colind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_INTEGER,
+ 0, 0, param, sizeof(param), ¶mind);
+ CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT ?::int4", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ printf("\n-- length fields as SQLLEN --\n");
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, &hDesc, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+ print_len_field("ARD SQL_DESC_OCTET_LENGTH", hDesc, SQL_DESC_OCTET_LENGTH);
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_PARAM_DESC, &hDesc, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+ print_len_field("APD SQL_DESC_OCTET_LENGTH", hDesc, SQL_DESC_OCTET_LENGTH);
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_IMP_PARAM_DESC, &hDesc, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+ print_len_field("IPD SQL_DESC_OCTET_LENGTH", hDesc, SQL_DESC_OCTET_LENGTH);
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_IMP_ROW_DESC, &hDesc, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+ print_len_field("IRD SQL_DESC_OCTET_LENGTH", hDesc, SQL_DESC_OCTET_LENGTH);
+ print_len_field("IRD SQL_DESC_LENGTH", hDesc, SQL_DESC_LENGTH);
+ print_len_field("IRD SQL_DESC_DISPLAY_SIZE", hDesc, SQL_DESC_DISPLAY_SIZE);
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+}
+
int main(int argc, char **argv)
{
SQLRETURN rc;
@@ -116,6 +180,7 @@ int main(int argc, char **argv)
CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
test_setdescrec_ard_binding();
+ test_len_field_width();
/* Clean up */
test_disconnect();
diff --git a/test/src/diag-threads-test.c b/test/src/diag-threads-test.c
new file mode 100644
index 00000000..b43be96c
--- /dev/null
+++ b/test/src/diag-threads-test.c
@@ -0,0 +1,203 @@
+/*
+ * Read a handle's diagnostics on one thread while another thread keeps
+ * making calls on the same handle that clear and set its errors.
+ *
+ * SQLGetDiagRec and SQLGetDiagField used to take no lock, so they could
+ * read an error object that the other thread's call had just freed. They
+ * now take the statement's or the connection's lock. A race can't be
+ * shown deterministically: this is a stress test that checks the calls
+ * work and agree while they contend for the handle. The old code passes
+ * it too unless the freed memory is trapped (a sanitizer or page heap).
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+#ifdef WIN32
+typedef HANDLE thread_t;
+#define THREAD_FUNC DWORD WINAPI
+typedef DWORD (WINAPI *thread_func_t)(void *);
+#define THREAD_RETURN return 0
+#else
+#include <pthread.h>
+typedef pthread_t thread_t;
+#define THREAD_FUNC void *
+typedef void *(*thread_func_t)(void *);
+#define THREAD_RETURN return NULL
+#endif
+
+#define ITERATIONS 2000
+
+static HSTMT hstmt = SQL_NULL_HSTMT;
+static volatile int done;
+static int worker_errors;
+static int reader_bad;
+static char first_bad[16];
+
+static void
+start_thread(thread_t *t, thread_func_t func, void *arg)
+{
+#ifdef WIN32
+ *t = CreateThread(NULL, 0, func, arg, 0, NULL);
+ if (NULL == *t)
+#else
+ if (0 != pthread_create(t, NULL, func, arg))
+#endif
+ {
+ printf("could not start a thread\n");
+ exit(1);
+ }
+}
+
+static void
+join_thread(thread_t t)
+{
+#ifdef WIN32
+ WaitForSingleObject(t, INFINITE);
+ CloseHandle(t);
+#else
+ pthread_join(t, NULL);
+#endif
+}
+
+/* fail a statement over and over: each call clears and sets its errors */
+static THREAD_FUNC
+stmt_worker(void *arg)
+{
+ int i;
+
+ for (i = 0; i < ITERATIONS; i++)
+ {
+ if (SQL_ERROR == SQLExecDirect(hstmt, (SQLCHAR *) "SELECT 1/0", SQL_NTS))
+ worker_errors++;
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+ }
+ done = 1;
+ THREAD_RETURN;
+}
+
+/* ask for an attribute that doesn't exist: each call sets a connection error */
+static THREAD_FUNC
+conn_worker(void *arg)
+{
+ int i;
+ SQLINTEGER value;
+
+ for (i = 0; i < ITERATIONS; i++)
+ {
+ if (SQL_ERROR == SQLGetConnectAttr(conn, 99999, &value, sizeof(value), NULL))
+ worker_errors++;
+ }
+ done = 1;
+ THREAD_RETURN;
+}
+
+/*
+ * Does this SQLSTATE belong to the worker?
+ *
+ * The statement worker's own failure is the division error, but when the
+ * driver is set not to roll back on an error (Protocol=7.4-0) and a
+ * transaction is open for the cursor, the first failure leaves the
+ * transaction aborted and every call after it fails with 25P02 instead.
+ * Both are the worker's own SQLSTATE, and how many of each there are
+ * depends on where the two threads are. A torn or stale record, which is
+ * what this test looks for, matches neither.
+ */
+static int
+worker_sqlstate(SQLSMALLINT htype, const char *sqlstate)
+{
+ if (SQL_HANDLE_STMT == htype)
+ return 0 == strcmp(sqlstate, "22012") ||
+ 0 == strcmp(sqlstate, "25P02");
+ return 0 == strcmp(sqlstate, "HYC00");
+}
+
+/*
+ * Read the handle's first diagnostic record until the worker is done. It
+ * may be there or not, depending on where the worker is; when it is there,
+ * its SQLSTATE must be the worker's one.
+ */
+static THREAD_FUNC
+reader(void *arg)
+{
+ SQLSMALLINT htype = *(SQLSMALLINT *) arg;
+ SQLHANDLE handle = (SQL_HANDLE_STMT == htype) ? (SQLHANDLE) hstmt : (SQLHANDLE) conn;
+ SQLCHAR sqlstate[6];
+ SQLCHAR msg[256];
+ SQLINTEGER native;
+ SQLSMALLINT len;
+ SQLRETURN rc;
+
+ while (!done)
+ {
+ rc = SQLGetDiagRec(htype, handle, 1, sqlstate, &native, msg, sizeof(msg), &len);
+ if (SQL_SUCCEEDED(rc) && !worker_sqlstate(htype, (char *) sqlstate))
+ {
+ if (0 == reader_bad++)
+ snprintf(first_bad, sizeof(first_bad), "rec %d %.5s", rc, (char *) sqlstate);
+ }
+ rc = SQLGetDiagField(htype, handle, 1, SQL_DIAG_SQLSTATE, sqlstate, sizeof(sqlstate), &len);
+ if (SQL_SUCCEEDED(rc) && !worker_sqlstate(htype, (char *) sqlstate))
+ {
+ if (0 == reader_bad++)
+ snprintf(first_bad, sizeof(first_bad), "field %d %.5s", rc, (char *) sqlstate);
+ }
+ }
+ THREAD_RETURN;
+}
+
+static void
+run(const char *label, SQLSMALLINT htype, thread_func_t worker)
+{
+ thread_t tw, tr;
+
+ done = 0;
+ worker_errors = 0;
+ reader_bad = 0;
+ first_bad[0] = '\0';
+
+ /*
+ * Start from the error the worker sets: the connection may still hold
+ * the statement's error (under unixODBC it does), and the reader runs
+ * before the worker's first call replaces it.
+ */
+ if (SQL_HANDLE_STMT == htype)
+ {
+ SQLExecDirect(hstmt, (SQLCHAR *) "SELECT 1/0", SQL_NTS);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+ }
+ else
+ {
+ SQLINTEGER value;
+
+ SQLGetConnectAttr(conn, 99999, &value, sizeof(value), NULL);
+ }
+ start_thread(&tr, reader, &htype);
+ start_thread(&tw, worker, NULL);
+ join_thread(tw);
+ join_thread(tr);
+ printf("%s: %d of %d calls failed as expected, %d unexpected diagnostics\n",
+ label, worker_errors, ITERATIONS, reader_bad);
+ if (reader_bad)
+ printf("first unexpected: %s\n", first_bad);
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+
+ test_connect();
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ run("statement", SQL_HANDLE_STMT, stmt_worker);
+ run("connection", SQL_HANDLE_DBC, conn_worker);
+
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/diagnostic-w-test.c b/test/src/diagnostic-w-test.c
new file mode 100644
index 00000000..06fb3e07
--- /dev/null
+++ b/test/src/diagnostic-w-test.c
@@ -0,0 +1,158 @@
+/*
+ * Tests for error diagnostics through the Unicode entry points
+ * (SQLGetDiagRecW, SQLGetDiagFieldW).
+ *
+ * The driver divides a long message text into pieces by byte count,
+ * so a piece handed to the UTF-8 to UTF-16 conversion may end in the
+ * middle of a multibyte character. SQLGetDiagFieldW used to return
+ * SQL_SUCCESS_WITH_INFO with StringLength -2 and an empty buffer in
+ * that case, and SQLGetDiagRecW replaced the text with its sqlstate.
+ */
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+#include <sqlucode.h>
+
+static void
+ascii_to_wchar(SQLWCHAR *dst, const char *src)
+{
+ while (*src)
+ *dst++ = (SQLWCHAR) (unsigned char) *src++;
+ *dst = 0;
+}
+
+/* Print a UTF-16 string as UTF-8 (BMP characters only) */
+static void
+print_wchar(const SQLWCHAR *str, int len)
+{
+ int i;
+
+ for (i = 0; i < len && str[i] != 0; i++)
+ {
+ unsigned int c = str[i];
+
+ if (c < 0x80)
+ putchar(c);
+ else if (c < 0x800)
+ printf("%c%c", 0xc0 | (c >> 6), 0x80 | (c & 0x3f));
+ else
+ printf("%c%c%c", 0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
+ }
+ printf("\n");
+}
+
+static const char *
+retcode_str(SQLRETURN rc)
+{
+ switch (rc)
+ {
+ case SQL_SUCCESS:
+ return "SQL_SUCCESS";
+ case SQL_SUCCESS_WITH_INFO:
+ return "SQL_SUCCESS_WITH_INFO";
+ case SQL_NO_DATA:
+ return "SQL_NO_DATA";
+ case SQL_ERROR:
+ return "SQL_ERROR";
+ default:
+ return "unexpected return code";
+ }
+}
+
+int main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ char dsn[1024];
+ SQLWCHAR wdsn[1024];
+ SQLWCHAR wquery[500];
+ SQLWCHAR *wp;
+ int i;
+ SQLWCHAR sqlstate[6];
+ SQLWCHAR msg[2000];
+ SQLSMALLINT len;
+ SQLINTEGER nativeerror;
+ char *envvar;
+
+ /*
+ * Connect with SQLDriverConnectW, as a Unicode application does, so
+ * that the driver manager calls the driver's Unicode entry points.
+ */
+ if ((envvar = getenv("COMMON_CONNECTION_STRING_FOR_REGRESSION_TEST")) != NULL && envvar[0] != '\0')
+ snprintf(dsn, sizeof(dsn), "DSN=%s;%s", get_test_dsn(), envvar);
+ else
+ snprintf(dsn, sizeof(dsn), "DSN=%s;", get_test_dsn());
+ ascii_to_wchar(wdsn, dsn);
+
+ SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
+ SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
+ SQLAllocHandle(SQL_HANDLE_DBC, env, &conn);
+ rc = SQLDriverConnectW(conn, NULL, wdsn, SQL_NTS, NULL, 0, NULL,
+ SQL_DRIVER_COMPLETE);
+ if (SQL_SUCCEEDED(rc))
+ printf("connected\n");
+ else
+ {
+ print_diag("SQLDriverConnectW failed.", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ /*
+ * An error message quoting 400 three-byte characters (U+4E2D). The
+ * literal comes from the client, so that a database that isn't UTF-8
+ * (SQL_ASCII) passes the bytes through as they are.
+ */
+ ascii_to_wchar(wquery, "SELECT CAST('");
+ wp = wquery + 13;
+ for (i = 0; i < 400; i++)
+ *wp++ = 0x4e2d;
+ ascii_to_wchar(wp, "' AS integer)");
+ rc = SQLExecDirectW(hstmt, wquery, SQL_NTS);
+ printf("SQLExecDirectW: %s\n", retcode_str(rc));
+
+ /*
+ * A 256-byte buffer gets 384 bytes of the message, which ends in the
+ * middle of a character.
+ */
+ memset(msg, 0, sizeof(msg));
+ rc = SQLGetDiagFieldW(SQL_HANDLE_STMT, hstmt, 1, SQL_DIAG_MESSAGE_TEXT,
+ msg, 256, &len);
+ printf("SQLGetDiagFieldW(256): %s, StringLength %s\n", retcode_str(rc),
+ len < 0 ? "negative" : len == 0 ? "zero" : "positive");
+ print_wchar(msg, 128);
+
+ /* The whole message */
+ memset(msg, 0, sizeof(msg));
+ rc = SQLGetDiagFieldW(SQL_HANDLE_STMT, hstmt, 1, SQL_DIAG_MESSAGE_TEXT,
+ msg, sizeof(msg), &len);
+ printf("SQLGetDiagFieldW(%d): %s, StringLength %d\n", (int) sizeof(msg),
+ retcode_str(rc), len);
+ print_wchar(msg, sizeof(msg) / sizeof(msg[0]));
+
+ /* SQLGetDiagRecW with a small buffer: the piece that fits, not a substitute */
+ memset(msg, 0, sizeof(msg));
+ rc = SQLGetDiagRecW(SQL_HANDLE_STMT, hstmt, 1, sqlstate, &nativeerror,
+ msg, 128, &len);
+ printf("SQLGetDiagRecW(128): %s, TextLength %d\n", retcode_str(rc), len);
+ print_wchar(sqlstate, 5);
+ print_wchar(msg, 128);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_ROLLBACK);
+ CHECK_STMT_RESULT(rc, "SQLEndTran failed", hstmt);
+
+ rc = SQLFreeStmt(hstmt, SQL_DROP);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/error-rollback-readonly-test.c b/test/src/error-rollback-readonly-test.c
new file mode 100644
index 00000000..8055029e
--- /dev/null
+++ b/test/src/error-rollback-readonly-test.c
@@ -0,0 +1,204 @@
+/*
+ * Statement-level rollback (Protocol 7.4-2) when the ODBC call just before the
+ * failing statement was read-only, here SQLProcedureColumns.
+ *
+ * The driver used to skip the SAVEPOINT after a read-only call, and then
+ * forgot that a savepoint was available, so a failing statement in that
+ * position rolled back the whole transaction instead of just itself, silently
+ * discarding earlier work. It now sets a savepoint there as anywhere else.
+ * Only the failing statement may be rolled back.
+ *
+ * Transactions 3 and 4 follow a fetch on a keyset-driven cursor, another
+ * read-only call: a positioned update that succeeds must survive a later
+ * failing INSERT, and a failing SQLBulkOperations(SQL_ADD) must not undo the
+ * INSERT before it.
+ */
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+static HSTMT hstmt = SQL_NULL_HSTMT;
+static HSTMT hcursor = SQL_NULL_HSTMT;
+static SQLINTEGER cursor_value;
+static SQLLEN cursor_ind;
+
+static void
+insert_value(SQLINTEGER value)
+{
+ SQLRETURN rc;
+ SQLCHAR sqlstate[6];
+
+ rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER,
+ 0, 0, &value, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "INSERT INTO rbtab VALUES (?)", SQL_NTS);
+ if (SQL_SUCCEEDED(rc))
+ printf(" insert %d: ok\n", (int) value);
+ else
+ {
+ SQLGetDiagField(SQL_HANDLE_STMT, hstmt, 1, SQL_DIAG_SQLSTATE,
+ sqlstate, sizeof(sqlstate), NULL);
+ printf(" insert %d: SQLSTATE=%s\n", (int) value, sqlstate);
+ }
+ SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
+}
+
+static void
+look_up_procedure_columns(void)
+{
+ SQLRETURN rc;
+
+ rc = SQLProcedureColumns(hstmt, NULL, 0, NULL, 0,
+ (SQLCHAR *) "abs", SQL_NTS, NULL, 0);
+ CHECK_STMT_RESULT(rc, "SQLProcedureColumns failed", hstmt);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+ printf(" SQLProcedureColumns: ok\n");
+}
+
+/* open a keyset-driven cursor on rbtab and fetch its first row */
+static void
+fetch_with_cursor(void)
+{
+ SQLRETURN rc;
+
+ rc = SQLExecDirect(hcursor, (SQLCHAR *) "SELECT i FROM rbtab ORDER BY i", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hcursor);
+ rc = SQLFetch(hcursor);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hcursor);
+ printf(" fetch: %d\n", (int) cursor_value);
+}
+
+static void
+setpos_update(SQLINTEGER value)
+{
+ SQLRETURN rc;
+
+ cursor_value = value;
+ cursor_ind = sizeof(cursor_value);
+ rc = SQLSetPos(hcursor, 1, SQL_UPDATE, SQL_LOCK_NO_CHANGE);
+ CHECK_STMT_RESULT(rc, "SQLSetPos failed", hcursor);
+ printf(" SQLSetPos update to %d: ok\n", (int) value);
+ SQLFreeStmt(hcursor, SQL_CLOSE);
+}
+
+static void
+bulk_add(SQLINTEGER value)
+{
+ SQLRETURN rc;
+ SQLCHAR sqlstate[6];
+
+ cursor_value = value;
+ cursor_ind = sizeof(cursor_value);
+ rc = SQLBulkOperations(hcursor, SQL_ADD);
+ if (SQL_SUCCEEDED(rc))
+ printf(" SQLBulkOperations add %d: ok\n", (int) value);
+ else
+ {
+ SQLGetDiagField(SQL_HANDLE_STMT, hcursor, 1, SQL_DIAG_SQLSTATE,
+ sqlstate, sizeof(sqlstate), NULL);
+ printf(" SQLBulkOperations add %d: SQLSTATE=%s\n", (int) value, sqlstate);
+ }
+ SQLFreeStmt(hcursor, SQL_CLOSE);
+}
+
+static void
+commit(void)
+{
+ SQLRETURN rc;
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+}
+
+static void
+print_committed_rows(void)
+{
+ SQLRETURN rc;
+ SQLCHAR rows[32];
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *)
+ "SELECT coalesce(string_agg(i::text, ' ' ORDER BY i), '') FROM rbtab",
+ SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLGetData(hstmt, 1, SQL_C_CHAR, rows, sizeof(rows), NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+ printf(" committed rows: %s\n", rows);
+}
+
+static void
+run_transaction(const char *label, int variant)
+{
+ SQLRETURN rc;
+
+ printf("%s\n", label);
+ insert_value(1);
+ switch (variant)
+ {
+ case 1:
+ look_up_procedure_columns();
+ break;
+ case 2:
+ fetch_with_cursor();
+ setpos_update(5);
+ break;
+ case 3:
+ fetch_with_cursor();
+ bulk_add(-1); /* refused by CHECK (i > 0) */
+ break;
+ }
+ if (variant != 3)
+ insert_value(-1); /* the end user's value, refused by CHECK (i > 0) */
+ insert_value(2);
+ commit();
+ print_committed_rows();
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "DELETE FROM rbtab", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ commit();
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+
+ test_connect_ext("Protocol=7.4-2;UpdatableCursors=1");
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *)
+ "CREATE TEMPORARY TABLE rbtab (i int4 CHECK (i > 0))",
+ SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ commit();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hcursor);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLSetStmtAttr(hcursor, SQL_ATTR_CONCURRENCY,
+ (SQLPOINTER) SQL_CONCUR_ROWVER, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hcursor);
+ rc = SQLSetStmtAttr(hcursor, SQL_ATTR_CURSOR_TYPE,
+ (SQLPOINTER) SQL_CURSOR_KEYSET_DRIVEN, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hcursor);
+ rc = SQLBindCol(hcursor, 1, SQL_C_SLONG, &cursor_value, 0, &cursor_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hcursor);
+
+ run_transaction("Transaction 1: insert, failing insert, insert", 0);
+ run_transaction("Transaction 2: insert, SQLProcedureColumns, failing insert, insert", 1);
+ run_transaction("Transaction 3: insert, fetch, SQLSetPos update, failing insert, insert", 2);
+ run_transaction("Transaction 4: insert, fetch, failing SQLBulkOperations add, insert", 3);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/extendedfetch-rowcount-test.c b/test/src/extendedfetch-rowcount-test.c
new file mode 100644
index 00000000..40bb1023
--- /dev/null
+++ b/test/src/extendedfetch-rowcount-test.c
@@ -0,0 +1,77 @@
+/*
+ * A result browser: shows a query's result in pages of three rows on a
+ * static cursor, going forward twice and then back once with
+ * SQLExtendedFetch(). Before every call the row count is set to 0, so a
+ * call that fails must leave it at 0.
+ */
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+#define PAGE_SIZE 3
+
+static void
+browse(const char *query)
+{
+ static const SQLUSMALLINT directions[] = {SQL_FETCH_NEXT, SQL_FETCH_NEXT, SQL_FETCH_PRIOR};
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLRETURN rc;
+ SQLCHAR ids[PAGE_SIZE][32];
+ SQLLEN id_lengths[PAGE_SIZE];
+ SQLUSMALLINT row_status[PAGE_SIZE];
+ SQLULEN rows_in_page;
+ SQLULEN row;
+ int i;
+
+ printf("%s\n", query);
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "SQLAllocHandle failed", conn);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_TYPE, (SQLPOINTER) SQL_CURSOR_STATIC, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr(SQL_ATTR_CURSOR_TYPE) failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ROWSET_SIZE, (SQLPOINTER) PAGE_SIZE, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr(SQL_ROWSET_SIZE) failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_CHAR, ids, sizeof(ids[0]), id_lengths);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) query, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ for (i = 0; i < 3; i++)
+ {
+ rows_in_page = 0;
+ rc = SQLExtendedFetch(hstmt, directions[i], 0, &rows_in_page, row_status);
+ printf("%s: SQLExtendedFetch returned %d, rows in page: %lu\n",
+ directions[i] == SQL_FETCH_PRIOR ? "prev" : "next",
+ rc, (unsigned long) rows_in_page);
+ if (SQL_SUCCEEDED(rc))
+ {
+ for (row = 0; row < rows_in_page; row++)
+ printf(" %s\n", ids[row]);
+ }
+ else
+ print_diag(NULL, SQL_HANDLE_STMT, hstmt);
+ }
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+}
+
+int
+main(int argc, char **argv)
+{
+ test_connect();
+
+ /* keeps its static cursor: "prev" shows rows 1-3 again */
+ browse("SELECT id FROM generate_series(1, 10) AS id");
+
+ /*
+ * Not classified as SELECT, so the driver turns the static cursor into a
+ * forward-only one and "prev" fails with HY106.
+ */
+ browse("WITH ids AS (SELECT generate_series(1, 10) AS id) SELECT id FROM ids");
+
+ test_disconnect();
+ return 0;
+}
diff --git a/test/src/fetch-before-first-test.c b/test/src/fetch-before-first-test.c
new file mode 100644
index 00000000..3f0a9295
--- /dev/null
+++ b/test/src/fetch-before-first-test.c
@@ -0,0 +1,104 @@
+/*
+ * Test fetching a rowset that overlaps the beginning of the result set
+ * with an updatable block cursor, after a row has been deleted through
+ * the cursor.
+ *
+ * PGAPI_ExtendedFetch() used to scan the keyset from row -1 in this case.
+ * The rows returned are the same either way, so the defect only shows up
+ * under valgrind or AddressSanitizer.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+#define ROWSET_SIZE 3
+
+static void
+print_rowset(const char *call, SQLRETURN rc, HSTMT hstmt, SQLINTEGER *id, SQLULEN rows_fetched)
+{
+ SQLULEN i;
+
+ printf("%s: ", call);
+ if (rc == SQL_NO_DATA)
+ printf("no data");
+ else
+ {
+ CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", hstmt);
+ printf("ids");
+ for (i = 0; i < rows_fetched; i++)
+ printf(" %d", (int) id[i]);
+ }
+ printf("\n");
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLINTEGER id[ROWSET_SIZE];
+ SQLULEN rows_fetched = 0;
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *)
+ "CREATE TEMPORARY TABLE items AS "
+ "SELECT g AS id FROM generate_series(1, 8) g", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "CREATE TABLE failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_TYPE, (SQLPOINTER) SQL_CURSOR_STATIC, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr CURSOR_TYPE failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CONCURRENCY, (SQLPOINTER) SQL_CONCUR_ROWVER, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr CONCURRENCY failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER) ROWSET_SIZE, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr ROW_ARRAY_SIZE failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROWS_FETCHED_PTR, &rows_fetched, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr ROWS_FETCHED_PTR failed", hstmt);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT id FROM items ORDER BY id", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SELECT failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_SLONG, id, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_ABSOLUTE, 1);
+ print_rowset("SQLFetchScroll(SQL_FETCH_ABSOLUTE, 1)", rc, hstmt, id, rows_fetched);
+
+ rc = SQLSetPos(hstmt, 1, SQL_DELETE, SQL_LOCK_NO_CHANGE);
+ CHECK_STMT_RESULT(rc, "SQLSetPos SQL_DELETE failed", hstmt);
+ printf("SQLSetPos(1, SQL_DELETE): ok\n");
+
+ /* Position before the first row, then refresh the rowset */
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_ABSOLUTE, 0);
+ print_rowset("SQLFetchScroll(SQL_FETCH_ABSOLUTE, 0)", rc, hstmt, id, rows_fetched);
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_RELATIVE, 0);
+ print_rowset("SQLFetchScroll(SQL_FETCH_RELATIVE, 0)", rc, hstmt, id, rows_fetched);
+
+ /* The same from the first rowset, scrolling back past the beginning */
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_FIRST, 0);
+ print_rowset("SQLFetchScroll(SQL_FETCH_FIRST, 0)", rc, hstmt, id, rows_fetched);
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_RELATIVE, -ROWSET_SIZE);
+ print_rowset("SQLFetchScroll(SQL_FETCH_RELATIVE, -3)", rc, hstmt, id, rows_fetched);
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_RELATIVE, 0);
+ print_rowset("SQLFetchScroll(SQL_FETCH_RELATIVE, 0)", rc, hstmt, id, rows_fetched);
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ /* Clean up */
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/fetch-refcursors-test.c b/test/src/fetch-refcursors-test.c
index 94539494..22e31349 100644
--- a/test/src/fetch-refcursors-test.c
+++ b/test/src/fetch-refcursors-test.c
@@ -104,6 +104,80 @@ static void refcursor_test(char* connectparams, SQLUINTEGER autocommit, int numr
test_disconnect();
}
+/*
+ * Leave a statement with several refcursor results open across a COMMIT,
+ * then close it in the next transaction. The cursors were closed by the
+ * COMMIT, so the driver must not try to close them again and break the
+ * next transaction.
+ */
+static void refcursor_close_after_commit_test(void)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ HSTMT hstmt2 = SQL_NULL_HSTMT;
+ int num_cursor = 2;
+ SQLINTEGER count;
+
+ printf("\n-- TEST closing a statement with refcursor results after a commit\n");
+
+ test_connect_ext("Fetch=1;FetchRefcursors=1");
+
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt2);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ rc = SQLExecDirect(hstmt2, "CREATE TEMPORARY TABLE refcursor_commit_tab (id int4)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt2);
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ rc = SQLPrepare(hstmt, "CALL refproc(?)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);
+ rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT_OUTPUT,
+ SQL_C_LONG, SQL_INTEGER, 0, 0,
+ &num_cursor, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);
+ rc = SQLExecute(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);
+
+ /* Read only the first result set, leaving the second one untouched */
+ printf("--1 ");
+ print_result(hstmt);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ /* Next transaction: do some work, then close the old statement */
+ rc = SQLExecDirect(hstmt2, "INSERT INTO refcursor_commit_tab VALUES (1)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt2);
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ /* The INSERT must have been committed */
+ rc = SQLExecDirect(hstmt2, "SELECT count(*) FROM refcursor_commit_tab", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt2);
+ rc = SQLFetch(hstmt2);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt2);
+ rc = SQLGetData(hstmt2, 1, SQL_C_LONG, &count, sizeof(count), NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt2);
+ printf("rows committed: %d\n", (int) count);
+
+ rc = SQLFreeStmt(hstmt2, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt2);
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ test_disconnect();
+}
+
int main(int argc, char **argv)
{
setup_procedure();
@@ -116,5 +190,7 @@ int main(int argc, char **argv)
refcursor_test("Fetch=1;FetchRefcursors=1", SQL_AUTOCOMMIT_OFF, 2);
refcursor_test("Fetch=1;FetchRefcursors=1", SQL_AUTOCOMMIT_OFF, 3);
+ refcursor_close_after_commit_test();
+
return 0;
}
diff --git a/test/src/getdata-binary-nodata-test.c b/test/src/getdata-binary-nodata-test.c
new file mode 100644
index 00000000..776f53b5
--- /dev/null
+++ b/test/src/getdata-binary-nodata-test.c
@@ -0,0 +1,74 @@
+/*
+ * Test that SQLGetData(SQL_C_BINARY) on a uuid or int4 column reports
+ * SQL_NO_DATA once the value has been returned, like it does for bytea,
+ * so that an application reading a binary column in pieces until
+ * SQL_NO_DATA does not loop forever.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+static void
+read_until_no_data(const char *sql, SQLLEN buflen)
+{
+ SQLRETURN rc;
+ SQLHSTMT hstmt = SQL_NULL_HSTMT;
+ char buf[64];
+ SQLLEN ind;
+ int i;
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "SQLAllocHandle failed", conn);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+
+ printf("%s, buflen %d:", sql, (int) buflen);
+ /* a few calls are enough: a correct column ends in SQL_NO_DATA */
+ for (i = 0; i < 4; i++)
+ {
+ ind = -99;
+ rc = SQLGetData(hstmt, 1, SQL_C_BINARY, buf, buflen, &ind);
+ if (rc == SQL_NO_DATA)
+ {
+ printf(" SQL_NO_DATA\n");
+ break;
+ }
+ if (rc == SQL_SUCCESS)
+ printf(" SQL_SUCCESS(%ld)", (long) ind);
+ else if (rc == SQL_SUCCESS_WITH_INFO)
+ printf(" SQL_SUCCESS_WITH_INFO(%ld)", (long) ind);
+ else
+ {
+ printf("\n");
+ print_diag("SQLGetData failed", SQL_HANDLE_STMT, hstmt);
+ exit(1);
+ }
+ }
+ if (rc != SQL_NO_DATA)
+ printf(" ... no SQL_NO_DATA after %d calls\n", i);
+
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+}
+
+int
+main(int argc, char **argv)
+{
+ test_connect();
+
+ /* buffer large enough for the value */
+ read_until_no_data("SELECT '\\x00112233'::bytea", 64);
+ read_until_no_data("SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid", 64);
+ read_until_no_data("SELECT 123456::int4", 64);
+ /* buffer too small for the value */
+ read_until_no_data("SELECT '\\x00112233'::bytea", 3);
+ read_until_no_data("SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid", 3);
+ read_until_no_data("SELECT 123456::int4", 3);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/identity-test.c b/test/src/identity-test.c
index cf4a4f5a..7a33bef7 100644
--- a/test/src/identity-test.c
+++ b/test/src/identity-test.c
@@ -97,6 +97,7 @@ test_no_identity_col(void)
int main(int argc, char **argv)
{
SQLRETURN rc;
+ SQLSMALLINT colcount;
char server_version[32], v10 = 0;
test_connect();
@@ -168,6 +169,29 @@ int main(int argc, char **argv)
test_no_identity_col();
+ /*
+ * The character following @@IDENTITY used to be dropped by the rewrite,
+ * gluing the two commands together. Describe before executing, as that
+ * is the path which split the rewritten query into commands.
+ */
+ rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT @@IDENTITY;SELECT @@IDENTITY AS second", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);
+
+ rc = SQLNumResultCols(hstmt, &colcount);
+ CHECK_STMT_RESULT(rc, "SQLNumResultCols failed", hstmt);
+ printf("# of result cols: %d\n", colcount);
+
+ rc = SQLExecute(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);
+ print_result(hstmt);
+
+ rc = SQLMoreResults(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLMoreResults failed", hstmt);
+ print_result(hstmt);
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
/* Clean up */
test_disconnect();
diff --git a/test/src/inheritance-keyset-test.c b/test/src/inheritance-keyset-test.c
new file mode 100644
index 00000000..b7bd6664
--- /dev/null
+++ b/test/src/inheritance-keyset-test.c
@@ -0,0 +1,237 @@
+/*
+ * Test a keyset-driven cursor on a table with an inheritance child.
+ *
+ * Each table in an inheritance tree has its own ctids, so the key of a
+ * row is (ctid, tableoid). When the driver re-reads, deletes or fetches a
+ * row by its key, it must not take the child's row at the same ctid for
+ * the parent's row.
+ */
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+#define BOOKMARK_SIZE 14
+
+static SQLINTEGER id;
+static char t[32];
+static SQLLEN id_ind, t_ind;
+static char bookmark[BOOKMARK_SIZE];
+static SQLLEN bookmark_ind;
+static SQLUSMALLINT row_status;
+
+static void
+exec_sql(HSTMT hstmt, const char *sql)
+{
+ SQLRETURN rc;
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+static void
+exec_sql_in_other_session(const char *sql)
+{
+ SQLRETURN rc;
+ SQLHDBC other_conn = SQL_NULL_HDBC;
+ HSTMT other_hstmt = SQL_NULL_HSTMT;
+ char connstr[256];
+
+ rc = SQLAllocHandle(SQL_HANDLE_DBC, env, &other_conn);
+ CHECK_CONN_RESULT(rc, "failed to allocate conn handle", other_conn);
+ snprintf(connstr, sizeof(connstr), "DSN=%s", get_test_dsn());
+ rc = SQLDriverConnect(other_conn, NULL, (SQLCHAR *) connstr, SQL_NTS,
+ NULL, 0, NULL, SQL_DRIVER_NOPROMPT);
+ CHECK_CONN_RESULT(rc, "SQLDriverConnect failed", other_conn);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, other_conn, &other_hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", other_conn);
+ exec_sql(other_hstmt, sql);
+ SQLFreeHandle(SQL_HANDLE_STMT, other_hstmt);
+ SQLDisconnect(other_conn);
+ SQLFreeHandle(SQL_HANDLE_DBC, other_conn);
+}
+
+static const char *
+row_status_str(SQLUSMALLINT status)
+{
+ switch (status)
+ {
+ case SQL_ROW_SUCCESS:
+ return "";
+ case SQL_ROW_UPDATED:
+ return " (updated)";
+ case SQL_ROW_DELETED:
+ return " (deleted)";
+ default:
+ return " (other status)";
+ }
+}
+
+static void
+print_row(const char *label, SQLUSMALLINT status, SQLINTEGER rid, const char *rt)
+{
+ if (status == SQL_ROW_DELETED)
+ printf("%s: deleted\n", label);
+ else
+ printf("%s: %d\t%s%s\n", label, (int) rid, rt, row_status_str(status));
+}
+
+static void
+fetch_row(HSTMT hstmt, int rownum)
+{
+ SQLRETURN rc;
+ char label[16];
+
+ rc = SQLFetchScroll(hstmt, SQL_FETCH_ABSOLUTE, rownum);
+ if (rc == SQL_NO_DATA)
+ {
+ printf("row %d: no data\n", rownum);
+ return;
+ }
+ CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", hstmt);
+ snprintf(label, sizeof(label), "row %d", rownum);
+ print_row(label, row_status, id, t);
+}
+
+static void
+print_tables(HSTMT hstmt)
+{
+ SQLRETURN rc;
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT tableoid::regclass, ctid, id, t FROM inh_parent ORDER BY id", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ print_result(hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ char saved_bookmarks[2][BOOKMARK_SIZE];
+ SQLLEN saved_bookmark_inds[2];
+ SQLINTEGER ids[2];
+ char ts[2][32];
+ SQLLEN id_inds[2], t_inds[2];
+ SQLUSMALLINT row_statuses[2];
+ int i;
+
+ /* the default; with UseDeclareFetch=1 a fetch does not re-read by key */
+ test_connect_ext("UseDeclareFetch=0");
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ /*
+ * The parent's rows are at ctids (0,1) to (0,3) of inh_parent, the
+ * child's rows at ctids (0,1) to (0,4) of inh_child.
+ */
+ exec_sql(hstmt, "DROP TABLE IF EXISTS inh_child, inh_parent");
+ exec_sql(hstmt, "CREATE TABLE inh_parent (id int PRIMARY KEY, t text)");
+ exec_sql(hstmt, "CREATE TABLE inh_child () INHERITS (inh_parent)");
+ exec_sql(hstmt, "INSERT INTO inh_parent VALUES (1, 'p1'), (2, 'p2'), (3, 'p3')");
+ exec_sql(hstmt, "INSERT INTO inh_child VALUES (11, 'c1'), (12, 'c2'), (13, 'c3'), (14, 'c4')");
+
+ printf("Opening a keyset-driven cursor on the parent's rows\n");
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CONCURRENCY, (SQLPOINTER) SQL_CONCUR_ROWVER, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_TYPE, (SQLPOINTER) SQL_CURSOR_KEYSET_DRIVEN, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_USE_BOOKMARKS, (SQLPOINTER) SQL_UB_VARIABLE, SQL_IS_UINTEGER);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_STATUS_PTR, &row_status, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLBindCol(hstmt, 0, SQL_C_VARBOOKMARK, bookmark, sizeof(bookmark), &bookmark_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_SLONG, &id, 0, &id_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, t, sizeof(t), &t_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT id, t FROM inh_parent WHERE id < 10 ORDER BY id", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ for (i = 1; i <= 3; i++)
+ {
+ fetch_row(hstmt, i);
+ if (i <= 2)
+ {
+ memcpy(saved_bookmarks[i - 1], bookmark, bookmark_ind);
+ saved_bookmark_inds[i - 1] = bookmark_ind;
+ }
+ }
+
+ /*
+ * Row 1 moves to (0,4) of inh_parent, where inh_child also has a row.
+ * Row 2 is gone but inh_child still has a row at (0,2).
+ */
+ printf("\nAnother session updates row 1 and deletes row 2\n");
+ exec_sql_in_other_session("UPDATE inh_parent SET t = 'p1 updated' WHERE id = 1");
+ exec_sql_in_other_session("DELETE FROM inh_parent WHERE id = 2");
+
+ printf("\nRe-fetching the rows of the cursor\n");
+ fetch_row(hstmt, 3);
+ fetch_row(hstmt, 2);
+ fetch_row(hstmt, 1);
+
+ /* inh_child's row at (0,3) must survive the positioned delete of row 3 */
+ printf("\nDeleting row 3 through the cursor\n");
+ fetch_row(hstmt, 3);
+ rc = SQLSetPos(hstmt, 1, SQL_DELETE, SQL_LOCK_NO_CHANGE);
+ CHECK_STMT_RESULT(rc, "SQLSetPos DELETE failed", hstmt);
+ fetch_row(hstmt, 3);
+
+ printf("\nFetching rows 1 and 2 by bookmark\n");
+ rc = SQLBindCol(hstmt, 0, SQL_C_VARBOOKMARK, saved_bookmarks, BOOKMARK_SIZE, saved_bookmark_inds);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_SLONG, ids, 0, id_inds);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, ts, sizeof(ts[0]), t_inds);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_STATUS_PTR, row_statuses, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER) 2, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLBulkOperations(hstmt, SQL_FETCH_BY_BOOKMARK);
+ CHECK_STMT_RESULT(rc, "SQLBulkOperations failed", hstmt);
+ /* a row that is gone comes back as NULLs */
+ for (i = 0; i < 2; i++)
+ {
+ printf("row %d: ", i + 1);
+ if (id_inds[i] == SQL_NULL_DATA)
+ printf("NULL\t");
+ else
+ printf("%d\t", (int) ids[i]);
+ if (t_inds[i] == SQL_NULL_DATA)
+ printf("NULL\n");
+ else
+ printf("%s\n", ts[i]);
+ }
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_UNBIND);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_STATUS_PTR, NULL, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER) 1, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_USE_BOOKMARKS, (SQLPOINTER) SQL_UB_OFF, SQL_IS_UINTEGER);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CONCURRENCY, (SQLPOINTER) SQL_CONCUR_READ_ONLY, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+ rc = SQLSetStmtAttr(hstmt, SQL_ATTR_CURSOR_TYPE, (SQLPOINTER) SQL_CURSOR_FORWARD_ONLY, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt);
+
+ printf("\nQuerying the tables again\n");
+ print_tables(hstmt);
+
+ exec_sql(hstmt, "DROP TABLE inh_child, inh_parent");
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/interval-type-name-test.c b/test/src/interval-type-name-test.c
new file mode 100644
index 00000000..94fb9cde
--- /dev/null
+++ b/test/src/interval-type-name-test.c
@@ -0,0 +1,66 @@
+/*
+ * Test SQL_DESC_TYPE_NAME of interval columns.
+ *
+ * A plain interval column (type modifier -1) used to return SQL_SUCCESS
+ * without writing the type name into the application's buffer.
+ */
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+int main(int argc, char **argv)
+{
+ int rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLUSMALLINT i;
+ SQLSMALLINT numcols;
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ rc = SQLExecDirect(hstmt,
+ (SQLCHAR *) "SELECT '1 day'::interval AS plain_interval, '1 day'::interval day AS interval_day, '1 year'::interval year to month AS interval_year_to_month, '1 second'::interval second AS interval_second",
+ SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ rc = SQLNumResultCols(hstmt, &numcols);
+ CHECK_STMT_RESULT(rc, "SQLNumResultCols failed", hstmt);
+
+ for (i = 1 ; i <= numcols; i++)
+ {
+ char label[64];
+ char buffer[64];
+ SQLSMALLINT len;
+
+ rc = SQLColAttribute(hstmt, i, SQL_DESC_LABEL, label, sizeof(label), NULL, NULL);
+ CHECK_STMT_RESULT(rc, "SQLColAttribute failed", hstmt);
+
+ /* a successful call must always write the buffer */
+ strcpy(buffer, "(buffer not written)");
+ rc = SQLColAttribute(hstmt, i, SQL_DESC_TYPE_NAME, buffer, sizeof(buffer), &len, NULL);
+ CHECK_STMT_RESULT(rc, "SQLColAttribute failed", hstmt);
+ printf("%s: SQL_DESC_TYPE_NAME: %s (length %d)\n", label, buffer, (int) len);
+
+ strcpy(buffer, "(buffer not written)");
+ rc = SQLColAttribute(hstmt, i, SQL_DESC_LOCAL_TYPE_NAME, buffer, sizeof(buffer), &len, NULL);
+ CHECK_STMT_RESULT(rc, "SQLColAttribute failed", hstmt);
+ printf("%s: SQL_DESC_LOCAL_TYPE_NAME: %s (length %d)\n", label, buffer, (int) len);
+ }
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ /* Clean up */
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/ird-smallint-fields-test.c b/test/src/ird-smallint-fields-test.c
new file mode 100644
index 00000000..9d514f95
--- /dev/null
+++ b/test/src/ird-smallint-fields-test.c
@@ -0,0 +1,116 @@
+/*
+ * Test that SQLGetDescField() on the IRD stores exactly a SQLSMALLINT for
+ * the descriptor fields that ODBC defines as SQLSMALLINT, and leaves the
+ * bytes beyond it alone.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+#define GUARD 0x5A5A
+
+static const struct
+{
+ SQLSMALLINT field;
+ const char *name;
+} smallint_fields[] =
+{
+ { SQL_DESC_CONCISE_TYPE, "SQL_DESC_CONCISE_TYPE" },
+ { SQL_DESC_FIXED_PREC_SCALE, "SQL_DESC_FIXED_PREC_SCALE" },
+ { SQL_DESC_NULLABLE, "SQL_DESC_NULLABLE" },
+ { SQL_DESC_PRECISION, "SQL_DESC_PRECISION" },
+ { SQL_DESC_SCALE, "SQL_DESC_SCALE" },
+ { SQL_DESC_SEARCHABLE, "SQL_DESC_SEARCHABLE" },
+ { SQL_DESC_TYPE, "SQL_DESC_TYPE" },
+ { SQL_DESC_UNNAMED, "SQL_DESC_UNNAMED" },
+ { SQL_DESC_UNSIGNED, "SQL_DESC_UNSIGNED" },
+ { SQL_DESC_UPDATABLE, "SQL_DESC_UPDATABLE" },
+};
+
+/*
+ * The field is read into 'value'; 'guard' sits right behind it and must
+ * not be touched.
+ */
+struct guarded_smallint
+{
+ SQLSMALLINT value;
+ SQLSMALLINT guard;
+};
+
+static void
+get_smallint_field(SQLHDESC ird, SQLSMALLINT recno, SQLSMALLINT field,
+ const char *fieldname)
+{
+ SQLRETURN rc;
+ SQLINTEGER strlen = -1;
+ struct guarded_smallint *buf;
+
+ /* a heap block, so that a store past 'guard' leaves the block */
+ buf = malloc(sizeof(*buf));
+ buf->value = 0;
+ buf->guard = GUARD;
+
+ rc = SQLGetDescField(ird, recno, field, &buf->value, SQL_IS_SMALLINT, &strlen);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("SQLGetDescField failed", SQL_HANDLE_DESC, ird);
+ exit(1);
+ }
+ printf("%s: %d (length %d)\n", fieldname, (int) buf->value, (int) strlen);
+ if (buf->guard != GUARD)
+ {
+ printf("ERROR: SQLGetDescField wrote past the SQLSMALLINT for %s\n", fieldname);
+ exit(1);
+ }
+ free(buf);
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLHDESC ird;
+ SQLSMALLINT colcount;
+ int i,
+ col;
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT 1::int4 AS number, 'x'::text AS label", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+
+ rc = SQLNumResultCols(hstmt, &colcount);
+ CHECK_STMT_RESULT(rc, "SQLNumResultCols failed", hstmt);
+
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_IMP_ROW_DESC, &ird, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+
+ /* header field */
+ printf("\n-- Header --\n");
+ get_smallint_field(ird, 0, SQL_DESC_COUNT, "SQL_DESC_COUNT");
+
+ /* record fields */
+ for (col = 1; col <= colcount; col++)
+ {
+ printf("\n-- Column %d --\n", col);
+ for (i = 0; i < sizeof(smallint_fields) / sizeof(smallint_fields[0]); i++)
+ get_smallint_field(ird, col, smallint_fields[i].field, smallint_fields[i].name);
+ }
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/large-object-open-error-test.c b/test/src/large-object-open-error-test.c
new file mode 100644
index 00000000..8c46e0c4
--- /dev/null
+++ b/test/src/large-object-open-error-test.c
@@ -0,0 +1,93 @@
+/*
+ * Test reading a large object column whose value names no large object.
+ *
+ * In autocommit mode the driver begins a transaction of its own to read
+ * the large object. When lo_open fails, that transaction must be ended
+ * by the driver, or the connection stays in the aborted transaction
+ * and every later query fails with 25P02.
+ */
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+static void
+read_row(HSTMT hstmt, int id)
+{
+ SQLRETURN rc;
+ char sql[100];
+ char buf[100];
+ SQLLEN ind;
+
+ snprintf(sql, sizeof(sql),
+ "SELECT large_data FROM lo_open_error_tab WHERE id = %d", id);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ if (SQL_SUCCEEDED(rc))
+ rc = SQLFetch(hstmt);
+ if (SQL_SUCCEEDED(rc))
+ rc = SQLGetData(hstmt, 1, SQL_C_BINARY, buf, sizeof(buf), &ind);
+
+ if (SQL_SUCCEEDED(rc))
+ printf("row %d: %.*s\n", id, (int) ind, buf);
+ else
+ {
+ printf("row %d: failed\n", id);
+ print_diag(NULL, SQL_HANDLE_STMT, hstmt);
+ }
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+int main(int argc, char **argv)
+{
+ int rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+
+ /*
+ * Three rows with a large object each. The large object of the
+ * second row is then unlinked, so the row keeps an OID that names
+ * no large object.
+ */
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "CREATE TEMPORARY TABLE lo_open_error_tab (id int4, large_data lo)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "INSERT INTO lo_open_error_tab VALUES (1, lo_from_bytea(0, 'first')), (2, lo_from_bytea(0, 'second')), (3, lo_from_bytea(0, 'third'))", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT lo_unlink(large_data) FROM lo_open_error_tab WHERE id = 2", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ /*
+ * Read the rows one by one in autocommit mode. Reading row 2 fails,
+ * but the rows after it must still be readable.
+ */
+ read_row(hstmt, 1);
+ read_row(hstmt, 2);
+ read_row(hstmt, 3);
+
+ /* A non-query statement must work too */
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "UPDATE lo_open_error_tab SET id = id WHERE id = 3", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ printf("update ok\n");
+
+ /* Clean up */
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/large-object-test.c b/test/src/large-object-test.c
index fda7b364..3d4e9ce8 100644
--- a/test/src/large-object-test.c
+++ b/test/src/large-object-test.c
@@ -72,6 +72,34 @@ int main(int argc, char **argv)
rc = SQLFreeStmt(hstmt, SQL_CLOSE);
CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ /**** Read only a part of it and abandon the rest ****/
+ printf("reading back a part of it and closing the cursor...\n");
+ SQLExecDirect(hstmt, (SQLCHAR *) "SELECT id, large_data FROM lo_test_tab WHERE id = 1", SQL_NTS);
+
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+
+ rc = SQLGetData(hstmt, 2, SQL_C_BINARY, buf, 4, &ind);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ if (rc != SQL_SUCCESS_WITH_INFO)
+ printf("SQLGetData did not return SQL_SUCCESS_WITH_INFO\n");
+ printhex(buf, 4);
+ printf("\n");
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ /*
+ * The driver began a transaction to read the large object. Since we
+ * are in autocommit mode, it must have ended that transaction when the
+ * cursor was closed. VACUUM fails inside a transaction block.
+ */
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "VACUUM lo_test_tab", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "VACUUM after an abandoned large object read failed", hstmt);
+ printf("vacuum succeeded\n");
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
/**** Insert a Large Object given as a hex string (SQL_C_CHAR) ****/
printf("inserting large object from hex string...\n");
rc = SQLPrepare(hstmt, (SQLCHAR *) "INSERT INTO lo_test_tab VALUES (2, ?)", SQL_NTS);
diff --git a/test/src/lost-connection-commit-test.c b/test/src/lost-connection-commit-test.c
new file mode 100644
index 00000000..ac0d977f
--- /dev/null
+++ b/test/src/lost-connection-commit-test.c
@@ -0,0 +1,108 @@
+/*
+ * Test that a commit is not reported as successful after the connection
+ * was lost inside a manual-commit transaction.
+ *
+ * When the driver notices that the connection is gone, it clears its
+ * in-transaction flag. If that happens in a call that discards the error
+ * (here: SQLFreeHandle of a prepared statement, which sends DEALLOCATE),
+ * SQLEndTran(SQL_COMMIT) used to find no open transaction and return
+ * SQL_SUCCESS, although the server had rolled the transaction back.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+int main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ HSTMT hstmt2 = SQL_NULL_HSTMT;
+ SQLHDBC conn2 = SQL_NULL_HDBC;
+ SQLCHAR dsn[1024];
+ SQLCHAR str[1024];
+ SQLSMALLINT strl;
+ SQLINTEGER pid;
+ SQLLEN ind;
+ char sql[100];
+
+ test_connect();
+
+ /* A second connection, used to terminate the first one's backend. */
+ snprintf(dsn, sizeof(dsn), "DSN=%s", get_test_dsn());
+ SQLAllocHandle(SQL_HANDLE_DBC, env, &conn2);
+ rc = SQLDriverConnect(conn2, NULL, dsn, SQL_NTS,
+ str, sizeof(str), &strl, SQL_DRIVER_COMPLETE);
+ CHECK_CONN_RESULT(rc, "SQLDriverConnect failed", conn2);
+
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_OFF, 0);
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT pg_backend_pid()", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_SLONG, &pid, 0, &ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+
+ /* Do some work in the transaction, with a prepared statement. */
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "CREATE TEMP TABLE lost_conn_tab (id int4)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLPrepare(hstmt, (SQLCHAR *) "INSERT INTO lost_conn_tab VALUES (1)", SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);
+ rc = SQLExecute(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);
+
+ /* Kill the first connection while the transaction is open. */
+ printf("killing connection...\n");
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn2, &hstmt2);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn2);
+ snprintf(sql, sizeof(sql), "SELECT pg_terminate_backend(%d)", (int) pid);
+ rc = SQLExecDirect(hstmt2, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt2);
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt2);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt2);
+ rc = SQLDisconnect(conn2);
+ CHECK_CONN_RESULT(rc, "SQLDisconnect failed", conn2);
+ SQLFreeHandle(SQL_HANDLE_DBC, conn2);
+
+ /*
+ * Freeing the prepared statement sends DEALLOCATE, which is where the
+ * driver notices that the connection is gone. The error is not
+ * reported to the application.
+ */
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ printf("SQLFreeHandle: %s\n", SQL_SUCCEEDED(rc) ? "succeeded" : "failed");
+
+ /* The commit must fail. */
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ if (SQL_SUCCEEDED(rc))
+ printf("SQLEndTran(SQL_COMMIT) succeeded on a lost connection\n");
+ else
+ print_diag("SQLEndTran(SQL_COMMIT) failed", SQL_HANDLE_DBC, conn);
+
+ /* So must turning autocommit on, which commits the transaction. */
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_ON, 0);
+ if (SQL_SUCCEEDED(rc))
+ printf("SQLSetConnectAttr(SQL_AUTOCOMMIT_ON) succeeded on a lost connection\n");
+ else
+ print_diag("SQLSetConnectAttr(SQL_AUTOCOMMIT_ON) failed", SQL_HANDLE_DBC, conn);
+
+ /* A rollback is fine; the server has already done that. */
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_ROLLBACK);
+ if (SQL_SUCCEEDED(rc))
+ printf("SQLEndTran(SQL_ROLLBACK) succeeded\n");
+ else
+ print_diag("SQLEndTran(SQL_ROLLBACK) failed", SQL_HANDLE_DBC, conn);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/odbc-escapes-test.c b/test/src/odbc-escapes-test.c
index 667dff78..ea880b0c 100644
--- a/test/src/odbc-escapes-test.c
+++ b/test/src/odbc-escapes-test.c
@@ -147,6 +147,13 @@ static void escape_test(HSTMT hstmt)
executeQuery(hstmt);
printf("OUT param: %s\n", outbuf1);
+ prepareQuery(hstmt, "{ ? = call length(?) }");
+ memset(outbuf1, 0, sizeof(outbuf1));
+ bindOutParamString(hstmt, 1, NULL, outbuf1, sizeof(outbuf1) - 1, 0);
+ bindParamString(hstmt, 2, NULL, "foobar");
+ executeQuery(hstmt);
+ printf("OUT param: %s\n", outbuf1);
+
/* It's preferable to cast VARIADIC any fields */
prepareQuery(hstmt, "{ ? = call concat(?::text, ?::text) }");
memset(outbuf1, 0, sizeof(outbuf1));
diff --git a/test/src/param-negative-length-test.c b/test/src/param-negative-length-test.c
new file mode 100644
index 00000000..355283b3
--- /dev/null
+++ b/test/src/param-negative-length-test.c
@@ -0,0 +1,97 @@
+/*
+ * Test that a negative StrLen_or_IndPtr value of a bound parameter that is
+ * none of the special indicator values (SQL_NULL_DATA, SQL_NTS,
+ * SQL_DEFAULT_PARAM, SQL_DATA_AT_EXEC, SQL_LEN_DATA_AT_EXEC(n)) is rejected
+ * instead of being used as the parameter's byte count.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+static void
+select_with_length(HSTMT hstmt, SQLSMALLINT ctype, SQLSMALLINT sqltype,
+ const char *sql, char *value, SQLLEN buflen, SQLLEN length)
+{
+ SQLRETURN rc;
+ SQLLEN cbValue = length;
+ SQLLEN ind;
+ char result[100];
+
+ printf("length %ld: ", (long) length);
+ /* the line must be out before the driver is called, it may never return */
+ fflush(stdout);
+
+ rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
+ ctype, /* value type */
+ sqltype, /* param type */
+ 20, /* column size */
+ 0, /* dec digits */
+ value, /* param value ptr */
+ buflen, /* buffer len */
+ &cbValue /* StrLen_or_IndPtr */);
+ CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("SQLExecDirect failed", SQL_HANDLE_STMT, hstmt);
+ return;
+ }
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLGetData(hstmt, 1, SQL_C_CHAR, result, sizeof(result), &ind);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ printf("%s\n", ind == SQL_NULL_DATA ? "NULL" : result);
+
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+int main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ char digits[] = "123";
+ char bytes[] = "\x01\x02\x03";
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ /* SQL_C_CHAR -> integer, substituted into the statement without quotes */
+ printf("SQL_C_CHAR -> SQL_INTEGER\n");
+ select_with_length(hstmt, SQL_C_CHAR, SQL_INTEGER,
+ "SELECT CAST(? AS integer)",
+ digits, sizeof(digits), 3);
+ select_with_length(hstmt, SQL_C_CHAR, SQL_INTEGER,
+ "SELECT CAST(? AS integer)",
+ digits, sizeof(digits), SQL_NTS);
+ /*
+ * Not SQL_NULL_DATA (-1), SQL_DATA_AT_EXEC (-2), SQL_NTS (-3),
+ * SQL_DEFAULT_PARAM (-5) or SQL_LEN_DATA_AT_EXEC (<= -100).
+ */
+ select_with_length(hstmt, SQL_C_CHAR, SQL_INTEGER,
+ "SELECT CAST(? AS integer)",
+ digits, sizeof(digits), -10);
+
+ /* SQL_C_BINARY -> bytea, substituted as a quoted hex literal */
+ printf("SQL_C_BINARY -> SQL_VARBINARY\n");
+ select_with_length(hstmt, SQL_C_BINARY, SQL_VARBINARY,
+ "SELECT encode(CAST(? AS bytea), 'hex')",
+ bytes, sizeof(bytes), 3);
+ select_with_length(hstmt, SQL_C_BINARY, SQL_VARBINARY,
+ "SELECT encode(CAST(? AS bytea), 'hex')",
+ bytes, sizeof(bytes), SQL_NULL_DATA);
+ select_with_length(hstmt, SQL_C_BINARY, SQL_VARBINARY,
+ "SELECT encode(CAST(? AS bytea), 'hex')",
+ bytes, sizeof(bytes), -4);
+
+ rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFreeHandle failed", hstmt);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/positioned-delete-rollback-test.c b/test/src/positioned-delete-rollback-test.c
new file mode 100644
index 00000000..5f895f5d
--- /dev/null
+++ b/test/src/positioned-delete-rollback-test.c
@@ -0,0 +1,167 @@
+/*
+ * With statement-level rollback (Protocol 7.4-2), a statement that fails is
+ * rolled back alone: a row deleted earlier in the same transaction with
+ * SQLSetPos(SQL_DELETE) stays deleted, on a partitioned table as on a plain
+ * one.
+ */
+#include <stdio.h>
+
+#include "common.h"
+
+static HSTMT hstmt = SQL_NULL_HSTMT;
+
+static void
+exec_ok(const char *sql)
+{
+ SQLRETURN rc;
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+}
+
+static void
+commit(void)
+{
+ SQLRETURN rc;
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+}
+
+static void
+reset_orders(const char *orders_table)
+{
+ char sql[100];
+
+ snprintf(sql, sizeof(sql), "TRUNCATE %s", orders_table);
+ exec_ok(sql);
+ snprintf(sql, sizeof(sql), "INSERT INTO %s VALUES (1), (2)", orders_table);
+ exec_ok(sql);
+ commit();
+}
+
+static HSTMT
+open_cursor_on_order_1(const char *orders_table)
+{
+ SQLRETURN rc;
+ HSTMT cursor = SQL_NULL_HSTMT;
+ char sql[100];
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &cursor);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+ rc = SQLSetStmtAttr(cursor, SQL_ATTR_CONCURRENCY, (SQLPOINTER) SQL_CONCUR_ROWVER, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", cursor);
+ rc = SQLSetStmtAttr(cursor, SQL_ATTR_CURSOR_TYPE, (SQLPOINTER) SQL_CURSOR_STATIC, 0);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", cursor);
+
+ snprintf(sql, sizeof(sql), "SELECT id FROM %s ORDER BY id", orders_table);
+ rc = SQLExecDirect(cursor, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", cursor);
+ rc = SQLFetchScroll(cursor, SQL_FETCH_FIRST, 0);
+ CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", cursor);
+
+ return cursor;
+}
+
+/* a refused note is reported, and the transaction goes on */
+static void
+insert_note(SQLINTEGER note_id)
+{
+ SQLRETURN rc;
+ SQLLEN ind = 0;
+ SQLCHAR sqlstate[6] = "";
+
+ rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER,
+ 0, 0, ¬e_id, 0, &ind);
+ CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "INSERT INTO posdel_notes VALUES (?)", SQL_NTS);
+ if (SQL_SUCCEEDED(rc))
+ printf(" note %d inserted\n", (int) note_id);
+ else
+ {
+ SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, sqlstate, NULL, NULL, 0, NULL);
+ printf(" note %d refused, SQLSTATE=%s\n", (int) note_id, sqlstate);
+ }
+ SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+}
+
+static void
+print_orders(const char *orders_table)
+{
+ SQLRETURN rc;
+ SQLINTEGER order_id;
+ SQLLEN ind;
+ char sql[100];
+
+ snprintf(sql, sizeof(sql), "SELECT id FROM %s ORDER BY id", orders_table);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLBindCol(hstmt, 1, SQL_C_LONG, &order_id, 0, &ind);
+ CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
+ printf(" orders left after commit:");
+ while (SQL_SUCCEEDED(SQLFetch(hstmt)))
+ printf(" %d", (int) order_id);
+ printf("\n");
+ SQLFreeStmt(hstmt, SQL_UNBIND);
+ SQLFreeStmt(hstmt, SQL_CLOSE);
+ commit();
+}
+
+static void
+delete_order_1_then_insert_note(const char *orders_table, SQLINTEGER note_id)
+{
+ SQLRETURN rc;
+ HSTMT cursor;
+
+ reset_orders(orders_table);
+
+ cursor = open_cursor_on_order_1(orders_table);
+ rc = SQLSetPos(cursor, 1, SQL_DELETE, SQL_LOCK_NO_CHANGE);
+ CHECK_STMT_RESULT(rc, "SQLSetPos(SQL_DELETE) failed", cursor);
+ printf(" order 1 deleted with SQLSetPos\n");
+
+ /* must be the very next call after SQLSetPos */
+ insert_note(note_id);
+
+ SQLFreeHandle(SQL_HANDLE_STMT, cursor);
+ commit();
+
+ print_orders(orders_table);
+}
+
+int
+main(int argc, char **argv)
+{
+ SQLRETURN rc;
+
+ /* 7.4-2 is the default; it is spelled out for "make installcheck-all" */
+ test_connect_ext("Protocol=7.4-2");
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ exec_ok("CREATE TEMPORARY TABLE posdel_notes (id int4 PRIMARY KEY)");
+ exec_ok("INSERT INTO posdel_notes VALUES (7)");
+ exec_ok("CREATE TEMPORARY TABLE posdel_plain (id int4 PRIMARY KEY)");
+ exec_ok("CREATE TEMPORARY TABLE posdel_part (id int4 PRIMARY KEY) PARTITION BY RANGE (id)");
+ exec_ok("CREATE TEMPORARY TABLE posdel_part_1 PARTITION OF posdel_part FOR VALUES FROM (0) TO (1000)");
+
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+
+ printf("Case 1: partitioned table, the INSERT after the delete succeeds\n");
+ delete_order_1_then_insert_note("posdel_part", 8);
+
+ printf("Case 2: plain table, the INSERT after the delete fails\n");
+ delete_order_1_then_insert_note("posdel_plain", 7);
+
+ printf("Case 3: partitioned table, the INSERT after the delete fails\n");
+ delete_order_1_then_insert_note("posdel_part", 7);
+
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/src/pqopt-many-test.c b/test/src/pqopt-many-test.c
new file mode 100644
index 00000000..47253242
--- /dev/null
+++ b/test/src/pqopt-many-test.c
@@ -0,0 +1,148 @@
+/*
+ * Test that no libpq keyword given in pqopt is dropped.
+ *
+ * The driver used to build the PQconnectdbParams() arrays in a fixed
+ * array of 30 entries and silently skip the pqopt keywords that did not
+ * fit, in libpq's keyword order, so the last ones (target_session_attrs,
+ * gssencmode, require_auth, ...) were lost without an error. A pqopt
+ * keyword that repeated one of the driver's own settings with the same
+ * value also took a second entry.
+ *
+ * Each case connects with about 25 pqopt keywords, some of them repeating
+ * the driver's settings. The harmless ones are there to fill the array;
+ * target_session_attrs, near the end of libpq's table, decides whether the
+ * connection succeeds.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+#define FILLER_PQOPT \
+ "application_name=pqopt_many " \
+ "fallback_application_name=pqopt_fallback " \
+ "options=-cwork_mem=4MB " \
+ "sslmode=disable " \
+ "connect_timeout=15 " \
+ "keepalives=1 " \
+ "keepalives_idle=30 " \
+ "keepalives_interval=10 " \
+ "keepalives_count=5 " \
+ "tcp_user_timeout=0 " \
+ "sslcompression=0 " \
+ "sslsni=1 " \
+ "ssl_min_protocol_version=TLSv1.2 " \
+ "ssl_max_protocol_version=TLSv1.3 " \
+ "gssencmode=disable " \
+ "channel_binding=disable " \
+ "passfile=no-such-pgpass " \
+ "sslpassword=unused " \
+ "sslcert=no-such-cert " \
+ "sslkey=no-such-key " \
+ "sslrootcert=no-such-root " \
+ "sslcrl=no-such-crl " \
+ "sslcrldir=no-such-crldir "
+
+static int
+try_connect(const char *target, SQLHENV *phenv, SQLHDBC *phdbc)
+{
+ SQLRETURN rc;
+ SQLCHAR outstr[1024];
+ SQLSMALLINT outlen = 0;
+ char connstr[2048];
+
+ /*
+ * Give the driver its own keepalive and timeout settings too, equal to
+ * the ones in pqopt, so that they fill their entries twice over in the
+ * old code. SSLmode=disable is the driver's default.
+ */
+ snprintf(connstr, sizeof(connstr),
+ "DSN=%s;SSLmode=disable;KeepaliveTime=30;KeepaliveInterval=10;"
+ "pqopt={" FILLER_PQOPT "target_session_attrs=%s}",
+ get_test_dsn(), target);
+
+ rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, phenv);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ fprintf(stderr, "SQLAllocHandle(SQL_HANDLE_ENV) failed\n");
+ exit(1);
+ }
+ SQLSetEnvAttr(*phenv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0);
+ rc = SQLAllocHandle(SQL_HANDLE_DBC, *phenv, phdbc);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("SQLAllocHandle(SQL_HANDLE_DBC) failed", SQL_HANDLE_ENV, *phenv);
+ exit(1);
+ }
+ SQLSetConnectAttr(*phdbc, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER) 15, 0);
+
+ rc = SQLDriverConnect(*phdbc, NULL, (SQLCHAR *) connstr, SQL_NTS,
+ outstr, sizeof(outstr), &outlen,
+ SQL_DRIVER_NOPROMPT);
+ return SQL_SUCCEEDED(rc);
+}
+
+static void
+done(SQLHENV henv, SQLHDBC hdbc)
+{
+ SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
+ SQLFreeHandle(SQL_HANDLE_ENV, henv);
+}
+
+static void
+show_setting(SQLHDBC hdbc, const char *name)
+{
+ SQLRETURN rc;
+ SQLHSTMT hstmt = SQL_NULL_HSTMT;
+ char sql[100];
+ SQLCHAR buf[100];
+ SQLLEN ind = 0;
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
+ CHECK_CONN_RESULT(rc, "SQLAllocHandle(SQL_HANDLE_STMT) failed", hdbc);
+ snprintf(sql, sizeof(sql), "SELECT current_setting('%s')", name);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLGetData(hstmt, 1, SQL_C_CHAR, buf, sizeof(buf), &ind);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ printf("%s: %s\n", name, (char *) buf);
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+}
+
+int
+main(void)
+{
+ SQLHENV henv;
+ SQLHDBC hdbc;
+
+ /* every keyword is passed and the connection works */
+ if (!try_connect("any", &henv, &hdbc))
+ {
+ print_diag("SQLDriverConnect with target_session_attrs=any failed",
+ SQL_HANDLE_DBC, hdbc);
+ exit(1);
+ }
+ printf("target_session_attrs=any: connected\n");
+ show_setting(hdbc, "application_name");
+ show_setting(hdbc, "work_mem");
+ SQLDisconnect(hdbc);
+ done(henv, hdbc);
+
+ /*
+ * The test server is a primary, so a read-only session can only be
+ * refused. Before the fix the keyword was dropped and this connected.
+ */
+ if (try_connect("read-only", &henv, &hdbc))
+ {
+ printf("target_session_attrs=read-only: connected, the keyword was dropped\n");
+ SQLDisconnect(hdbc);
+ }
+ else
+ printf("target_session_attrs=read-only: refused\n");
+ done(henv, hdbc);
+
+ return 0;
+}
diff --git a/test/src/putdata-descriptor-params-test.c b/test/src/putdata-descriptor-params-test.c
new file mode 100644
index 00000000..bd2d677d
--- /dev/null
+++ b/test/src/putdata-descriptor-params-test.c
@@ -0,0 +1,109 @@
+/*
+ * Test SQLPutData for a data-at-execution parameter that the application
+ * described through the descriptor fields of the APD and the IPD, without
+ * calling SQLBindParameter for it.
+ *
+ * SQLBindParameter makes room for a parameter in three arrays of the
+ * driver: the APD's, the IPD's and the one that collects the data passed
+ * to SQLPutData. Setting descriptor fields makes room in the descriptor
+ * that is set only. SQLPutData must make sure all three hold the
+ * parameter before it stores the data.
+ *
+ * In the first case every parameter is described that way, so the array
+ * for the data does not exist yet. In the second, SQLBindParameter for
+ * parameter 1 has created it with one element, and the data is for
+ * parameter 2.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common.h"
+
+/*
+ * Run sql, whose last parameter, number param, is described through
+ * descriptor fields and gets "abc" from SQLPutData. A parameter before it
+ * is bound to "x" with SQLBindParameter.
+ */
+static void
+put_data_case(const char *sql, SQLSMALLINT param)
+{
+ SQLRETURN rc;
+ HSTMT hstmt = SQL_NULL_HSTMT;
+ SQLHDESC hApd = NULL, hIpd = NULL;
+ SQLLEN ind = SQL_DATA_AT_EXEC;
+ SQLLEN first_ind = SQL_NTS;
+ char first[] = "x";
+ SQLPOINTER token = NULL;
+ char buf[32];
+ SQLLEN buflen;
+
+ printf("%s, data for parameter %d\n", sql, param);
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
+ CHECK_CONN_RESULT(rc, "failed to allocate stmt handle", conn);
+
+ rc = SQLPrepare(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);
+ if (param > 1)
+ {
+ rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR,
+ SQL_VARCHAR, 20, 0, first, 0, &first_ind);
+ CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);
+ }
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_PARAM_DESC, &hApd, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+ rc = SQLGetStmtAttr(hstmt, SQL_ATTR_IMP_PARAM_DESC, &hIpd, 0, NULL);
+ CHECK_STMT_RESULT(rc, "SQLGetStmtAttr failed", hstmt);
+
+ rc = SQLSetDescField(hIpd, param, SQL_DESC_CONCISE_TYPE,
+ (SQLPOINTER) SQL_VARCHAR, 0);
+ CHECK_STMT_RESULT(rc, "IPD SQL_DESC_CONCISE_TYPE failed", hstmt);
+ rc = SQLSetDescField(hIpd, param, SQL_DESC_PARAMETER_TYPE,
+ (SQLPOINTER) SQL_PARAM_INPUT, 0);
+ CHECK_STMT_RESULT(rc, "IPD SQL_DESC_PARAMETER_TYPE failed", hstmt);
+ rc = SQLSetDescField(hApd, param, SQL_DESC_CONCISE_TYPE,
+ (SQLPOINTER) SQL_C_CHAR, 0);
+ CHECK_STMT_RESULT(rc, "APD SQL_DESC_CONCISE_TYPE failed", hstmt);
+ rc = SQLSetDescField(hApd, param, SQL_DESC_OCTET_LENGTH_PTR, &ind, 0);
+ CHECK_STMT_RESULT(rc, "APD SQL_DESC_OCTET_LENGTH_PTR failed", hstmt);
+ rc = SQLSetDescField(hApd, param, SQL_DESC_INDICATOR_PTR, &ind, 0);
+ CHECK_STMT_RESULT(rc, "APD SQL_DESC_INDICATOR_PTR failed", hstmt);
+ /* the value SQLParamData hands back for this parameter */
+ rc = SQLSetDescField(hApd, param, SQL_DESC_DATA_PTR, (SQLPOINTER) 1, 0);
+ CHECK_STMT_RESULT(rc, "APD SQL_DESC_DATA_PTR failed", hstmt);
+
+ rc = SQLExecute(hstmt);
+ printf("SQLExecute: %s\n", SQL_NEED_DATA == rc ? "SQL_NEED_DATA" : "other");
+ rc = SQLParamData(hstmt, &token);
+ printf("SQLParamData: %s\n", SQL_NEED_DATA == rc ? "SQL_NEED_DATA" : "other");
+ /* a crash in SQLPutData must not lose the lines above */
+ fflush(stdout);
+ rc = SQLPutData(hstmt, "abc", 3);
+ if (!SQL_SUCCEEDED(rc))
+ print_diag("SQLPutData failed", SQL_HANDLE_STMT, hstmt);
+ else
+ printf("SQLPutData succeeded\n");
+ rc = SQLParamData(hstmt, &token);
+ if (!SQL_SUCCEEDED(rc))
+ print_diag("the second SQLParamData failed", SQL_HANDLE_STMT, hstmt);
+ else
+ {
+ rc = SQLFetch(hstmt);
+ CHECK_STMT_RESULT(rc, "SQLFetch failed", hstmt);
+ rc = SQLGetData(hstmt, 1, SQL_C_CHAR, buf, sizeof(buf), &buflen);
+ CHECK_STMT_RESULT(rc, "SQLGetData failed", hstmt);
+ printf("result: %s\n", buf);
+ }
+
+ SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
+}
+
+int
+main(int argc, char **argv)
+{
+ test_connect();
+ put_data_case("SELECT 'got ' || ?::text", 1);
+ put_data_case("SELECT 'got ' || ?::text || ?::text", 2);
+ test_disconnect();
+ return 0;
+}
diff --git a/test/src/query-timeout-test.c b/test/src/query-timeout-test.c
new file mode 100644
index 00000000..cc9caa5e
--- /dev/null
+++ b/test/src/query-timeout-test.c
@@ -0,0 +1,192 @@
+/*
+ * Test SQL_ATTR_QUERY_TIMEOUT.
+ *
+ * The driver implements the timeout with "SET statement_timeout", which is
+ * transactional: a ROLLBACK undoes it and a COMMIT keeps it. The driver
+ * must notice both. Believing the session has a timeout a rollback undid,
+ * or that a committed timeout is gone, makes it skip the SET a statement
+ * needs.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "common.h"
+
+/*
+ * Execute a statement that takes longer than the timeout, and print
+ * whether it was cancelled.
+ */
+static void
+run_slow_query(HSTMT hstmt, const char *label)
+{
+ SQLRETURN rc;
+ char sqlstate[32];
+ char message[1000];
+ SQLINTEGER nativeerror;
+ SQLSMALLINT textlen;
+
+ printf("%s: ", label);
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SELECT pg_sleep(2)", SQL_NTS);
+ if (SQL_SUCCEEDED(rc))
+ printf("not cancelled\n");
+ else
+ {
+ rc = SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, sqlstate, &nativeerror,
+ message, sizeof(message), &textlen);
+ if (SQL_SUCCEEDED(rc))
+ printf("cancelled with SQLSTATE %s\n", sqlstate);
+ else
+ printf("failed, no error information\n");
+ }
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+static void
+exec_and_close(HSTMT hstmt, const char *sql)
+{
+ SQLRETURN rc;
+
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) sql, SQL_NTS);
+ CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+/*
+ * Report what the session has for statement_timeout.
+ *
+ * A cancelled statement leaves the transaction aborted, and the driver
+ * recovers it only when it is set to roll back on an error. With
+ * Protocol=7.4-0 it is not, so the session cannot be read until the
+ * transaction ends. Report that and end the transaction, rather than give
+ * up the test: the rest of it still says something under that setting.
+ */
+static void
+show_statement_timeout(HSTMT hstmt)
+{
+ SQLRETURN rc;
+ char sqlstate[32];
+ char message[1000];
+ SQLINTEGER nativeerror;
+ SQLSMALLINT textlen;
+
+ printf("SHOW statement_timeout: ");
+ rc = SQLExecDirect(hstmt, (SQLCHAR *) "SHOW statement_timeout", SQL_NTS);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ if (SQL_SUCCEEDED(SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, sqlstate,
+ &nativeerror, message,
+ sizeof(message), &textlen)))
+ printf("not readable, SQLSTATE %s\n", sqlstate);
+ else
+ printf("failed, no error information\n");
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_ROLLBACK);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+ return;
+ }
+ print_result(hstmt);
+ rc = SQLFreeStmt(hstmt, SQL_CLOSE);
+ CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);
+}
+
+int main(int argc, char **argv)
+{
+ SQLRETURN rc;
+ HSTMT hstmt_notimeout = SQL_NULL_HSTMT;
+ HSTMT hstmt_timeout = SQL_NULL_HSTMT;
+
+ test_connect();
+
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt_notimeout);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+ rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt_timeout);
+ if (!SQL_SUCCEEDED(rc))
+ {
+ print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
+ exit(1);
+ }
+ rc = SQLSetStmtAttr(hstmt_timeout, SQL_ATTR_QUERY_TIMEOUT, (SQLPOINTER) 1, SQL_IS_UINTEGER);
+ CHECK_STMT_RESULT(rc, "SQLSetStmtAttr failed", hstmt_timeout);
+
+ rc = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER);
+ CHECK_CONN_RESULT(rc, "SQLSetConnectAttr failed", conn);
+
+ /*
+ * Open the transaction with the handle without a timeout, so that the
+ * SET statement_timeout for the other handle is issued inside it.
+ * The ROLLBACK then undoes the SET on the server.
+ */
+ printf("-- SET statement_timeout = 1s inside a transaction, then ROLLBACK\n");
+ exec_and_close(hstmt_notimeout, "SELECT 1");
+ run_slow_query(hstmt_timeout, "timeout 1 before rollback");
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_ROLLBACK);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ run_slow_query(hstmt_timeout, "timeout 1 after rollback");
+ show_statement_timeout(hstmt_timeout);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ /*
+ * The opposite direction: the 1 second timeout is now committed on the
+ * session. "SET statement_timeout = 0" for the other handle is rolled
+ * back, and the session is back at 1 second.
+ */
+ printf("-- SET statement_timeout = 0 inside a transaction, then ROLLBACK\n");
+ exec_and_close(hstmt_timeout, "SELECT 1");
+ exec_and_close(hstmt_notimeout, "SELECT 1");
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_ROLLBACK);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ run_slow_query(hstmt_notimeout, "no timeout after rollback");
+ show_statement_timeout(hstmt_notimeout);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ /*
+ * The application's own ROLLBACK TO SAVEPOINT, when the savepoint is
+ * older than the SET, undoes it too, without ending the transaction.
+ */
+ printf("-- SET statement_timeout = 1s after a SAVEPOINT, then ROLLBACK TO it\n");
+ exec_and_close(hstmt_notimeout, "SAVEPOINT foo");
+ exec_and_close(hstmt_timeout, "SELECT 1");
+ show_statement_timeout(hstmt_timeout);
+ exec_and_close(hstmt_timeout, "ROLLBACK TO SAVEPOINT foo");
+ run_slow_query(hstmt_timeout, "timeout 1 after rollback to savepoint");
+ show_statement_timeout(hstmt_timeout);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_ROLLBACK);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ /*
+ * A COMMIT keeps the SET issued inside the transaction. The next
+ * statement without a timeout must get a "SET statement_timeout = 0"
+ * instead of running under the committed 1 second.
+ */
+ printf("-- SET statement_timeout = 1s inside a transaction, then COMMIT\n");
+ exec_and_close(hstmt_timeout, "SELECT 1");
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+ run_slow_query(hstmt_notimeout, "no timeout after commit");
+ show_statement_timeout(hstmt_notimeout);
+
+ rc = SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
+ CHECK_CONN_RESULT(rc, "SQLEndTran failed", conn);
+
+ /* Clean up */
+ test_disconnect();
+
+ return 0;
+}
diff --git a/test/tests b/test/tests
index 02076a11..2a426696 100644
--- a/test/tests
+++ b/test/tests
@@ -18,6 +18,7 @@ TESTBINS = exe/connect-test \
exe/result-conversions-test \
exe/result-conversions-endianness-test \
exe/prepare-test \
+ exe/describe-before-execute-test \
exe/premature-test \
exe/params-test \
exe/leading-literal-numparams-test \
@@ -68,6 +69,7 @@ TESTBINS = exe/connect-test \
exe/wchar-char-test \
exe/params-batch-exec-test \
exe/params-batch-putdata-error-test \
+ exe/lost-connection-commit-test \
exe/fetch-refcursors-test \
exe/descrec-test \
exe/descriptors-free-test \
@@ -88,6 +90,7 @@ TESTBINS = exe/connect-test \
exe/getdata-after-fetch-error-test \
exe/bindcol-count-limit-test \
exe/bookmark-oid-test \
+ exe/bookmark-buffer-length-test \
exe/close-cursor-savepoint-test \
exe/colattribute-stale-cache-test \
exe/colinfo-refcnt-test \
@@ -111,12 +114,14 @@ TESTBINS = exe/connect-test \
exe/catalog-identifier-args-test \
exe/catalog-name-length-test \
exe/catalog-current-schema-quote-test \
+ exe/putdata-descriptor-params-test \
exe/param-marker-lexer-test \
exe/cursor-name-quote-test \
- exe/many-cursor-updates-test \
exe/tables-null-type-test \
exe/diagfield-sqlstate-length-test \
+ exe/copydesc-param-name-test \
exe/fetch-bookmark-range-test \
+ exe/many-cursor-updates-test \
exe/wide-output-termination-test \
exe/log-secrets-redacted-test \
exe/default-ctype-altered-test \
@@ -141,8 +146,25 @@ TESTBINS = exe/connect-test \
exe/stale-parse-test \
exe/star-expansion-test \
exe/subclass-tableoid-test \
+ exe/param-negative-length-test \
+ exe/ird-smallint-fields-test \
exe/bool-param-length-test \
exe/param-name-length-test \
+ exe/commit-failure-test \
+ exe/large-object-open-error-test \
+ exe/positioned-delete-rollback-test \
+ exe/query-timeout-test \
+ exe/inheritance-keyset-test \
+ exe/bulk-bookmark-declare-fetch-test \
exe/bulkadd-before-fetch-test \
+ exe/fetch-before-first-test \
+ exe/getdata-binary-nodata-test \
+ exe/interval-type-name-test \
+ exe/extendedfetch-rowcount-test \
+ exe/pqopt-many-test \
+ exe/catalog-error-rollback-test \
+ exe/error-rollback-readonly-test \
exe/deferred-params-test \
- exe/describe-before-execute-test
+ exe/diag-threads-test \
+ exe/diagnostic-w-test \
+ exe/desc-threads-test
diff --git a/win_unicode.c b/win_unicode.c
index 6e19cccb..c57cd6b0 100644
--- a/win_unicode.c
+++ b/win_unicode.c
@@ -987,6 +987,9 @@ MYLOG(0, " c16dt=%p size=" FORMAT_SIZE_T "\n", c16dt, n);
if (c16dt)
c16dt[i] = PG_CARRIAGE_RETURN;
i++;
+ /* the CR may have taken the last slot */
+ if (c16dt && i >= n)
+ break;
}
brtn = mbrtoc16(c16dt ? c16dt + i : NULL, cdt, 4, &mbst);
if (0 == brtn)
@@ -998,7 +1001,7 @@ MYLOG(0, " c16dt=%p size=" FORMAT_SIZE_T "\n", c16dt, n);
continue;
cdt += brtn;
}
- if (c16dt && i >= n)
+ if (c16dt && n > 0 && i >= n)
c16dt[n - 1] = 0;
return i;
[parent: b9932501a536]