denisenkom / pytds

Python DBAPI driver for MSSQL using pure Python TDS (Tabular Data Stream) protocol implementation
MIT License
192 stars 53 forks source link

Send PLP_NULL for VARBINARY(MAX) too to avoid exceptions #131

Closed gizmo93 closed 2 years ago

gizmo93 commented 2 years ago

Hey! It seems like the same handling which is used for NVARCHAR(MAX) and VARCHAR(MAX) needs to be applied to VARBINARY(MAX).

Create a new table like this:

DROP TABLE IF EXISTS BulkInsertTest; CREATE TABLE BulkInsertTest ( Id INT NOT NULL PRIMARY KEY IDENTITY (1,1), Bin VARBINARY(MAX) NULL, )

data = [
        {'Bin': 'aaa'.encode('utf-8'),}
        for i in range(100_000)
    ]

with con2.cursor() as cursor:
    cursor.copy_to(
        table_or_view='BulkInsertTest',
        schema='dbo',
        columns=[
            pytds.Column('Bin', type=pytds.tds_types.VarBinaryMaxType(), flags=1),
        ],
        data=[
            tuple(el.values())
            for el in data
        ]
    )
    con2.commit()

Leads to:

pytds.tds_base.OperationalError: While reading current row from host, a premature end-of-message was encountered--an incoming data stream was interrupted when the server expected to see more data. The host program may have terminated. Ensure that you are using a supported client application programming interface (API).

With the fix here it works.

Greetz Danny