Skip to content

Bcp 2 - #4

Open
rad-pat wants to merge 22 commits into
masterfrom
bcp_2
Open

rad-pat wants to merge 22 commits into
masterfrom
bcp_2

Conversation

@rad-pat

@rad-pat rad-pat commented Mar 23, 2026

Copy link
Copy Markdown
Member

No description provided.

@rad-pat
rad-pat force-pushed the bcp_2 branch 6 times, most recently from 6f7c893 to 7909397 Compare March 23, 2026 14:05
@rad-pat
rad-pat force-pushed the bcp_2 branch 3 times, most recently from 51282aa to 0641759 Compare June 8, 2026 13:52
@rad-pat
rad-pat force-pushed the bcp_2 branch 7 times, most recently from 13f4ad1 to 9787a2a Compare October 23, 2026 18:33
@rad-pat
rad-pat force-pushed the bcp_2 branch 2 times, most recently from 98dde7c to 01ed1d7 Compare November 6, 2026 15:23
ziyziy89 and others added 11 commits November 6, 2026 11:11
…ameters

- fast_executemany: an error while sending data-at-execution parameters
  returned without resetting SQL_ATTR_PARAMSET_SIZE and
  SQL_ATTR_PARAM_BIND_OFFSET_PTR (left pointing at a local), so the next
  execute on the cursor failed or crashed.  Route those errors through the
  normal cleanup, cancelling first if SQLPutData failed.
- fast_executemany: reject Decimals that cannot fit in SQL_NUMERIC_STRUCT
  before building the scaled digit tuple, and check the results of the
  Python calls that follow.
- Decimal NaN and Infinity raise a ProgrammingError instead of crashing.
  as_tuple() and UUID.bytes_le results are checked before use.
- CreateDecimalString uses Py_ssize_t lengths and counters.
- TVP type and schema names must be str; encoding failures are raised
  instead of passing NULL to PyBytes_AsString.  Row and value references
  are held while in use, NULL results are checked, and an empty first row
  is now caught by the "same size" check.
- fast_executemany checks the row buffer size for overflow.
A (sqltype, size) tuple with no scale set DecimalDigits to the column size,
so (SQL_DECIMAL, 18) bound as decimal(18, 18) and values like 123 were out of
range.  Keep the described/derived scale instead.
- `del row[i]` and `del row.name` passed a NULL value to Row_ass_item,
  which INCREF'd it.  Raise TypeError instead.
- Row_getattro used the column map's value as an index without a bounds
  check.  The map comes from the unpickle constructor, so check it.
- Row_richcompare treated an error from PyObject_RichCompareBool as
  "not equal" and continued with the exception set.  Propagate it.
- Catalog functions (tables, columns, primaryKeys, ...) on a closed cursor
  passed NULL to free_results.  Raise "Attempt to use a closed cursor."
- fetchval with rows_as_dicts passed the dict to Row_item.  Always fetch a
  Row for fetchval.
- If create_name_map failed (e.g. a column name that can't be decoded),
  colinfos stayed allocated with no description or map, and the next fetch
  read through them.  Free colinfos on failure.
- TVP data-at-execution: the column loop used the row's current length
  rather than the number of bound columns, released the row and cell before
  using them, and didn't check for NULL.  Bound the loop by the nested
  bindings, hold the references (including the cell whose buffer the driver
  reads), and check errors.
- Errors while sending data-at-execution parameters now cancel the
  statement, so the cursor is usable afterwards instead of failing with
  HY010.
- connect(encoding=...) with a name that can't be encoded as UTF-8 passed
  NULL to PyBytes_AsString.  Raise the encoding error.
- attrs_before: check PySequence_GetItem results (and re-check the item
  type, since the sequence is read again after validation), check the key
  for overflow, and give str values a NUL as wide as a character; they are
  passed with SQL_NTS but a bytes object only ends in one NUL byte.
- set_attr: validate the connection, raise encoding errors instead of
  passing a NULL buffer, and raise integer overflow.
- getinfo, searchescape and Windows dataSources clamp the returned length
  to the buffer when the driver truncates.  searchescape validates the
  connection and checks the decode.
- TimeFromTicks converted the original object instead of the int (so floats
  returned with a TypeError pending) and dereferenced a NULL localtime()
  result.  Raise OverflowError for values localtime() can't represent.
…call

DecimalFromNumericStruct converted the 16-byte magnitude to a Python int, the int to a str, the
str to a tuple of one int per digit, and then called Decimal((sign, digits, exponent)).  That
made several Python objects per digit for every value read.

Format the value as "<digits>E<-scale>" in C instead and call Decimal() once.  The result is
identical, exponent included.  Reading 200,000 numeric(18,2) values takes about 20-25% less
time on PostgreSQL and SQL Server.
…can't describe it

ExecuteMulti used SQLDescribeParam's precision and scale for Decimal parameters even when the
driver reports SQL_DESCRIBE_PARAMETER "N".  psqlODBC is such a driver: it describes every
numeric parameter as numeric(28,6), or with the precision and scale last bound to the
statement.  So on PostgreSQL, fast_executemany raised "Converting decimal loses precision" for
any value with more than 6 decimal places, and for any fractional value after the same cursor
had run the statement with an integral Decimal.

When the driver can't describe the parameter and setinputsizes doesn't give a scale, bind
Decimals as numeric(38, s), or with the setinputsizes size as the precision, and take s from
the values.  DetectCType picks the smallest scale the batch's first row needs, counting only
significant digits, or the previous batch's scale if the row fits it too.  A later row that
does not fit the scale chosen, but fits another, ends the current batch, and the parameters
are rebound from that row.

Digits are checked against the precision in the SQL_NUMERIC_STRUCT, for Decimals and ints,
rather than the 39 digits the 16-byte val can hold: psqlODBC silently drops the leading digits
of a value with more digits than the struct's precision.  The described type and size are
restored before each batch, so guessing for a Decimal does not change how a str in the same
column is bound.
…pport NaN and Infinity

5.4.0 reads DECIMAL and NUMERIC columns into a SQL_NUMERIC_STRUCT.  psqlODBC cannot put NaN,
Infinity, or more than 38 digits into the struct, and silently returns 0 for the first two and a
wrong number for the third.  The text path the struct replaced has its own problem: it strips
everything but the decimal separator pyodbc read from the locale at import, so a driver that
sends '.' while that separator is ',' (mkleehammer#753), or psqlODBC under a comma locale set after
import, reads 3656.88 as 365688.

Connection.decimal_mode selects how these columns are read:

- 'binary': the SQL_NUMERIC_STRUCT, as in 5.4.0.  It stays the default except for
  PostgreSQL.  A value the driver reports did not fit (01004) raises DataError instead of
  returning the wrong number left in the struct.  The column is not read again as text: a
  conforming driver returns SQL_NO_DATA for a column already read, and what others return
  cannot be relied on.
- 'text': text from drivers that never add grouping separators.  The one separator can only be
  the decimal point, so '.' and ',' are both accepted whatever the locale, along with NaN and
  [-]Infinity.  Anything else raises DataError.  This is the default when SQL_DBMS_NAME is
  PostgreSQL, and is as fast as 'binary'.
- 'locale': the pre-5.4 path, using setDecimalSeparator, for drivers that add grouping
  separators or currency symbols.

fetch_decimal_as_string is deprecated and will be removed in 6.0.  Reading or setting it raises
FutureWarning; True selects 'locale' and False 'binary', as before, except that True leaves
'text' alone, since the getter returns True for both text modes and saving and restoring the
value should change nothing.  decimal_mode accepts the same bools, also with a FutureWarning,
until 6.0.

Cursor.execute now binds Decimal NaN, Infinity, and -Infinity as text and leaves it to the
database to accept or reject them; PostgreSQL stores them and SQL Server raises DataError.
fast_executemany and table-valued parameters still raise ProgrammingError, since the struct
cannot hold them, and a signaling NaN always raises.

Tests check that 'binary' and 'text' reads give identical Decimals, exponent included, on SQL
Server and PostgreSQL.
…top variant recursion

- ReadVarColumn: with readvar_initsize smaller than one character plus the terminator (1, for
  any NVARCHAR), the first read computed a length of -1 and the next SQLGetData wrote before
  the buffer.  An odd size split UTF-16 characters, and msodbcsql looped forever on
  readvar_initsize = 1.  Make the buffer at least one element plus the terminator, and a whole
  number of elements.
- ReadVarColumn: don't trust a length the driver reports beyond the space offered, and don't
  subtract the terminator from a final length that never included it.
- The GUID path passed an int for Py_BuildValue's "y#", which reads a Py_ssize_t.
- A driver reporting sql_variant as the underlying type of a sql_variant recursed without
  limit.  Raise instead.
- SQLWChar returned PyUnicode_AsUTF8 directly for UTF-8.  The buffer goes to W APIs with
  SQL_NTS, but that string ends in one NUL byte, not a NUL SQLWCHAR, so with
  setdecoding(SQL_WMETADATA, encoding='utf-8') the driver read past the end of the name.  Use
  the general path, which appends four NULs.
- The general path cleared encoding errors, so a name that could not be encoded (a lone
  surrogate) gave "SystemError: returned NULL without setting an exception".  Leave the error
  set, raise TypeError for an encoding that does not return bytes, and handle a failed
  allocation.  set_attr no longer needs to encode twice to get the error.
- tablePrivileges and statistics cast the UTF-16 name length to SQLSMALLINT.  Longer names
  wrapped, and a name of exactly 65533 characters became SQL_NTS, so the driver read past the
  end looking for a terminator.  Raise ValueError for names over 32767 characters.
mkleehammer and others added 10 commits November 7, 2026 17:48
…in the regex

- InitializeDecimal wrapped the borrowed decimal_point from localeconv() in an Object, which
  released it.  "." and "," are cached singletons, but with a locale whose decimal point is not
  Latin-1 (fa_IR, for example) the separator was freed while still in use.  The imports and
  localeconv() result were not checked for NULL either.
- SetDecimalPoint put the separator into a character class unescaped, so "]" or "-" changed
  the class and setDecimalSeparator("z-a") raised after the separator had been replaced.
  Escape it, and build everything before replacing any global.
GetErrorFromHandle and GetDiagRecs (Cursor.messages) read diagnostic records with
SQLGetDiagRecW:

- The length returned by the retry with a larger buffer was not checked again, so a driver
  reporting more than it was offered made the decode read past the buffer.  Clamp it.
- The new buffer size, a SQLSMALLINT, was computed as length + 1 and wrapped at 32767.
- The SQLSTATE and message buffers were sized for a 2-byte SQLWCHAR.  pyodbc expects UTF-16,
  but give them room for a 4-byte one so a driver manager using it cannot write past them.
- A message that could not be decoded left its exception set.
…x length types

- bytearray parameters are copied to bytes when bound, including
  fast_executemany data-at-execution cells, so the buffer the driver reads
  cannot be resized or freed by another thread while the GIL is released.
- Decimal.as_tuple() results are fully checked: the sign must be 0 or 1 and
  the digits 0-9, since CreateDecimalString sizes its buffer from them (a
  subclass returning a negative sign overflowed the heap).  A scale larger
  than 32767, which cannot be bound as a SQLSMALLINT, raises
  ProgrammingError, as does an exponent larger than any Decimal's, which
  would overflow the arithmetic on it.
- String, data-at-execution, and Decimal string lengths are SQLLEN instead of
  being truncated through SQLINTEGER.  SQL statements and TVP names too long
  for a SQLINTEGER raise ValueError.
- Fix printf-style format specifiers for Py_ssize_t and unsigned long values
  in error messages.
Deleting pyodbc.pooling or pyodbc.odbcversion crashed the first connect,
and deleting pyodbc.lowercase or pyodbc.native_uuid left an AttributeError
set.  Read all four through one helper that clears errors and uses the
default.  This also fixes a reference leak on every result set from
reading pyodbc.lowercase.
pyodbc requires Python 3.11, so remove comments describing Python 2
behavior and Python 2 type names.  connect() with a non-str connection
string now says "must be a str" instead of "a string or unicode object".
Creating the exception calls the exception class, which Python 3.12
rejects with SystemError when an exception is already set.  The TVP
"Expected Decimal" error was raised this way with an AttributeError
pending.
…ee the read buffer on errors

nextset() on a closed cursor returned NULL without an exception
(SystemError), and a SQLNumResultCols failure returned the exception
object instead of raising it.  ReadVarColumn leaked its buffer when
SQLGetData failed.
GitHub no longer supports the macos-14 runner image: the 5.5.0 artifacts build
was rejected with "The configuration 'macos-14-arm64-us-default' is not
supported".  The wheels' macOS tag (macosx_11_0_arm64) comes from
cibuildwheel's Python builds, not the runner.
Adds Connection methods that drive the SQL Server bulk-copy (BCP) API
directly, loading rows into a table with explicit host types. They are
the building blocks for the BCP fast path for fast_executemany in the
next commit, and serve loads that want BCP options of their own (batch
size, hints, KEEPNULLS, error limits).

Usage (SQL Server with Microsoft ODBC Driver 13 or later):
  - open the connection with
    attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}
  - cnxn.bcp_init(table, batch_rows=0, keep_nulls=False, hints=None,
                  max_errors=0)
  - ctx = cnxn.bcp_bind_columns([pyodbc.SQLINT4, pyodbc.SQLNCHAR, ...])
  - for each row: cnxn.bcp_setrow(ctx, row), then cnxn.bcp_sendrow()
  - cnxn.bcp_batch(ctx) and cnxn.bcp_done() return the rows stored
The host types are exported as pyodbc.SQLBIT, SQLINT2/4/8, SQLFLT4/8,
SQLNCHAR, SQLCHARACTER, SQLBINARY and SQLUNIQUEID, along with DB_IN,
SQL_COPT_SS_BCP and SQL_BCP_ON.

The driver's bcp_* exports are bound on demand, once per connection, from
the library of the driver that connection uses, and only when that is
Microsoft ODBC Driver 13 or later for SQL Server; any other driver raises
a clear error. SQL Server Native Client and Driver 11 are left out because
behind the Windows driver manager's connection pooling, which pyodbc turns
on by default, they leave a failed batch without diagnostics. The module
is found by the connection's driver name (on Linux, failing that, by its
exact path in /proc/self/maps), and elsewhere than Windows is opened with
RTLD_NOLOAD, so two SQL Server drivers loaded in one process never share
entry points.
bcp_initW takes the table name, so names outside the ANSI code page work.
Loader diagnostics are gated behind PYODBC_BCP_DEBUG.

Safety:
  - The connection owns the bound buffers until bcp_done, so dropping the
    context cannot free them under the driver.
  - In autocommit mode a session runs in its own transaction, committed
    at each batch, so closing the connection first discards the rows sent
    since the last batch; in manual-commit mode the rows join the open
    transaction. autocommit cannot change mid-session.
  - bcp_setrow converts the whole row before writing any of it, so a value
    conversion that runs Python code (and might even close the connection)
    cannot pull the session out from under it, and every bcp_sendrow needs
    a successful bcp_setrow first.
  - str goes to SQLNCHAR columns as UTF-16. SQLCHARACTER takes bytes or
    ASCII str only, since the driver reads it in the client's code page.
  - Variable-length columns use an 8-byte length prefix plus bcp_collen,
    which (max) columns need: the driver misreads a zero-length 8-byte
    prefix on its own.

Tests in tests/sqlserver_test.py cover every host type with NULLs,
batches, manual-commit mode, misuse, and a conversion that closes the
connection mid-row.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lyo1SXh7BDrSf1BctKfCrz
@rad-pat
rad-pat force-pushed the bcp_2 branch 2 times, most recently from 3694c18 to 34e1910 Compare November 27, 2026 13:01
Adds an optional bulk-copy (BCP) path for Cursor.executemany with
fast_executemany against SQL Server, built on the driver loader and
column buffers of the previous commit. When enabled, an INSERT of one
parameterized VALUES row is carried out with the SQL Server bulk-copy API
instead of parameter arrays, which is much faster for large loads, without
the caller having to change code or write data files. The path is an
optimisation only: it stores exactly what the plain fast_executemany path
stores, and anything it cannot reproduce is left to that path.

Usage (SQL Server with Microsoft ODBC Driver 13 or later):
  - open the connection with
    attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}
  - cursor.fast_executemany = True
  - cursor.use_bcp_fast = True
  - optional: cursor.bcp_batch_rows (rows per batch)
              cursor.bcp_tablock    (pass the TABLOCK hint)
After a BCP load, cursor.rowcount is the number of rows copied.

How a call is decided, all before bcp_init (src/bcp_executemany.cpp):
  - The statement must be INSERT [INTO] [[db.]schema.]table [(columns)]
    VALUES (?, ...) with nothing else: TOP, hints, OUTPUT, other sources,
    literals, expressions, several rows, further statements, quoted or
    undelimited reserved-word identifiers fall back.
  - The connection must use Microsoft ODBC Driver 13 or later with
    SQL_COPT_SS_BCP on; a pooled connection opened without it falls back
    rather than failing.
  - The destination's columns come from the catalog views of its own
    database (tempdb for temporary tables), so values map to columns as the
    INSERT would: a column list leaves the unlisted columns to the server
    (identity, computed, DEFAULT, NULL), names folding case only where the
    database compares identifiers ignoring case, and a positional INSERT
    skips identity and computed columns. A table with an enabled INSERT
    trigger falls back: a trigger that rolls back a bulk copy run inside a
    transaction leaves the driver unable to use the connection.
  - Every row is scanned once. Each column gets a host type from its
    destination type and the Python types it holds, only for pairings whose
    driver conversion stores what the plain path stores; other pairings,
    other types, malformed rows and values longer than their column (which
    the plain path rejects, or for numbers in narrow text columns
    truncates) fall back. Text goes as UTF-16 (SQLNCHAR), since the driver
    reads SQLCHARACTER data in the client's ANSI code page; text for a
    char or varchar column with a multi-byte collation falls back when its
    encoded bytes could exceed the column, which the server rejects but
    the driver quietly cuts short. Drivers before 17.4 send text for a
    UTF-8 collation as bytes the server rejects, so with them such columns
    take only ASCII text. Decimals go as exact text with every digit,
    whatever the thread's decimal context, as the plain path has sent
    them since 5.4.0. One the plain path's SQL_NUMERIC_STRUCT cannot
    hold raises as that path does, before it is formatted, and a Decimal
    subclass falls back, since the plain path reads its as_tuple rather
    than its __format__. Dates and times are formatted to the destination's
    precision with the plain path's rounding, since the driver rejects
    excess digits and does not carry datetime rounding past midnight. Conversions like these, which the
    path does itself, are in src/bcp_convert.cpp.
    uniqueidentifier columns take uuid.UUID values and strings in the
    canonical 36-character form, the only ones the plain path stores, as
    their 16 bytes. As SQLAlchemy binds dates and times for SQL Server,
    date columns also take datetimes whose hours, minutes and seconds are
    zero, and time columns HH:MM:SS[.fraction] text with no more digits
    than their scale; the plain path rejects other values of those kinds
    there.
  - setinputsizes entries are honoured. Under an entry the plain path
    sends each value as the entry's SQL type and the server converts it
    to the column's, so BCP sends what that conversion stores, for str
    under (SQL_WVARCHAR, n, 0), bool under SQL_BIT, int under SQL_BIGINT,
    float under SQL_DOUBLE, Decimal under (SQL_NUMERIC or SQL_DECIMAL,
    p, s), datetime and date under (SQL_TYPE_TIMESTAMP, 27, 7) and date
    under SQL_TYPE_DATE. Timestamps round half up from seven digits
    (datetime to its nearest 1/300 s tick). Decimals round half away from
    zero into decimal and money, truncate into integers, and raise as the
    plain path does for more places than the entry's scale. Doubles go
    into decimal as their exact binary value rounded half away from zero,
    into integers truncated, and into real rounded with subnormals kept.
    A number stores 1 in a bit column unless it is zero. Text goes into a
    char or varchar column only when the column's code page holds every
    character exactly, as the server's substitutes for the rest differ
    from the driver's best-fit ones. The server converts even NULLs from
    the entry's type, so a column of NULLs takes an nvarchar entry into
    anything but a binary column, and other entries only where their own
    values may go. None entries keep the rules above; other entries and
    pairings fall back.
  - datetimeoffset is the one deliberate exception to matching the plain
    path, whose driver gives a value the client machine's local offset for
    its date: BCP stores what a user would expect, an aware datetime with
    its own offset and a naive one or a date at +00:00, and raises for an
    offset SQL Server cannot hold.

Loading:
  - KEEPNULLS and the CHECK_CONSTRAINTS and FIRE_TRIGGERS hints make BCP
    store what the INSERT would: explicit NULLs stay NULL, constraints are
    checked and triggers fire.
  - A failure once rows are streaming rolls back everything the call sent
    and raises: the load runs in its own transaction in autocommit mode, and
    after a savepoint (set in the same round trip as the catalog query) in
    manual-commit mode. With bcp_batch_rows, each completed batch is
    committed in autocommit mode and only the failing batch is discarded.
  - Driver diagnostics are read before bcp_done, which clears them, and
    bcp_batch failures (-1) are detected.
  - (max) columns use an 8-byte length prefix plus bcp_collen, because the
    driver misreads a zero-length 8-byte prefix; an empty string goes to
    char(n) as a space, because the driver repeats the previous value there.

Tests in tests/sqlserver_test.py compare BCP with the plain path across
every allowed pairing of value and column type, except text, ntext and
image, which the plain path sizes from their 2 GB column size and cannot
load on 32-bit Python, so they are checked against the values sent. With
setinputsizes they compare both paths for every supported entry and
column pairing, with edge cases and a seeded random load, check from
cursor.rowcount that BCP ran, and cover the entries it declines and the
values both paths reject. They also cover older drivers falling back,
the other fall backs, statement shapes, column mapping, table names,
INSERT semantics, rollback in both commit modes, a conversion that closes
the connection or the cursor mid-load, and a row changed while it is being
sent.
utils/bcp_benchmark.py is a standalone benchmark.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lyo1SXh7BDrSf1BctKfCrz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants