{{ message }}
Repository navigation
Expand file tree
/
Copy pathtest_019_bulkcopy.py
More file actions
591 lines (464 loc) · 22.7 KB
/
Copy pathtest_019_bulkcopy.py
File metadata and controls
591 lines (464 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Basic integration tests for bulkcopy via the mssql_python driver."""
import time
import pytest
# Skip the entire module when mssql_py_core can't be loaded (e.g. it's not
# installed, or its native extension fails to load in some build containers).
# exc_type=ImportError is required because pytest 9.1 changed importorskip's
# default to only skip on ModuleNotFoundError, so a module that is found but
# fails to import its native extension would otherwise be raised as a collection
# error instead of being skipped. The skip reason is left to pytest so it
# reports the actual underlying import error.
mssql_py_core = pytest.importorskip(
"mssql_py_core",
exc_type=ImportError,
)
def test_connection_and_cursor(cursor):
"""Test that connection and cursor work correctly."""
cursor.execute("SELECT 1 AS connected")
result = cursor.fetchone()
assert result[0] == 1
def test_insert_and_fetch(cursor):
"""Test basic insert and fetch operations."""
table_name = "mssql_python_test_basic"
# Create table
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT, name NVARCHAR(50))")
cursor.connection.commit()
# Insert data
cursor.execute(f"INSERT INTO {table_name} (id, name) VALUES (?, ?)", (1, "Alice"))
cursor.execute(f"INSERT INTO {table_name} (id, name) VALUES (?, ?)", (2, "Bob"))
# Fetch and verify
cursor.execute(f"SELECT id, name FROM {table_name} ORDER BY id")
rows = cursor.fetchall()
assert len(rows) == 2
assert rows[0][0] == 1 and rows[0][1] == "Alice"
assert rows[1][0] == 2 and rows[1][1] == "Bob"
# Cleanup
cursor.execute(f"DROP TABLE {table_name}")
def test_bulkcopy_basic(cursor):
"""Test basic bulkcopy operation via mssql_python driver with auto-mapping.
Uses automatic column mapping (columns mapped by ordinal position).
"""
table_name = "mssql_python_bulkcopy_test"
# Create table
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT, name VARCHAR(50), value FLOAT)")
cursor.connection.commit()
# Prepare test data - columns match table order (id, name, value)
data = [
(1, "Alice", 100.5),
(2, "Bob", 200.75),
(3, "Charlie", 300.25),
]
# Perform bulkcopy with auto-mapping (no column_mappings specified)
# Using explicit timeout parameter instead of kwargs
result = cursor.bulkcopy(table_name, data, timeout=60)
# Verify result
assert result is not None
assert result["rows_copied"] == 3
# Verify data was inserted correctly
cursor.execute(f"SELECT id, name, value FROM {table_name} ORDER BY id")
rows = cursor.fetchall()
assert len(rows) == 3
assert rows[0][0] == 1 and rows[0][1] == "Alice" and abs(rows[0][2] - 100.5) < 0.01
assert rows[1][0] == 2 and rows[1][1] == "Bob" and abs(rows[1][2] - 200.75) < 0.01
assert rows[2][0] == 3 and rows[2][1] == "Charlie" and abs(rows[2][2] - 300.25) < 0.01
# Cleanup
cursor.execute(f"DROP TABLE {table_name}")
def test_bulkcopy_without_database_parameter(conn_str):
"""Test bulkcopy operation works when DATABASE is not specified in connection string.
The database keyword in connection string is optional. In its absence,
the client sends an empty database name and the server responds with
the default database the client was connected to.
"""
from mssql_python import connect
from mssql_python.connection_string_parser import _ConnectionStringParser
from mssql_python.connection_string_builder import _ConnectionStringBuilder
# Parse the connection string using the proper parser
parser = _ConnectionStringParser(validate_keywords=False)
params = parser._parse(conn_str)
# Remove DATABASE parameter if present (case-insensitive, handles all synonyms)
params.pop("database", None)
# Rebuild the connection string using the builder to preserve braced values
builder = _ConnectionStringBuilder(params)
conn_str_no_db = builder.build()
# Create connection without DATABASE parameter
conn = connect(conn_str_no_db)
try:
cursor = conn.cursor()
# Verify we're connected to a database (should be the default)
cursor.execute("SELECT DB_NAME() AS current_db")
current_db = cursor.fetchone()[0]
assert current_db is not None, "Should be connected to a database"
# Skip on Azure SQL Database (EngineEdition 5): bulkcopy internally
# opens a second connection via mssql_py_core using the stored
# connection string. Without a DATABASE keyword that second
# connection cannot resolve the target table on Azure SQL.
cursor.execute("SELECT CAST(SERVERPROPERTY('EngineEdition') AS INT)")
engine_edition = cursor.fetchone()[0]
if engine_edition == 5:
pytest.skip(
"bulkcopy uses a separate internal connection; without "
"DATABASE in the connection string it cannot resolve "
"table metadata on Azure SQL"
)
# Use unqualified table names — the table is created in whatever
# database we connected to. Three-part names ([db].[schema].[table])
# are NOT supported on Azure SQL, and the default database (often
# master) may deny CREATE TABLE on other CI environments, so we
# skip gracefully when the current database doesn't allow DDL.
table_name = "mssql_python_bulkcopy_no_db_test"
try:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT, name VARCHAR(50), value FLOAT)")
conn.commit()
except Exception as e:
pytest.skip(f"Cannot create table in default database '{current_db}': {e}")
# Prepare test data
data = [
(1, "Alice", 100.5),
(2, "Bob", 200.75),
(3, "Charlie", 300.25),
]
# Perform bulkcopy - this should NOT raise ValueError about missing DATABASE
result = cursor.bulkcopy(table_name, data, timeout=60)
# Verify result
assert result is not None
assert result["rows_copied"] == 3
# Verify data was inserted correctly
cursor.execute(f"SELECT id, name, value FROM {table_name} ORDER BY id")
rows = cursor.fetchall()
assert len(rows) == 3
assert rows[0][0] == 1 and rows[0][1] == "Alice" and abs(rows[0][2] - 100.5) < 0.01
assert rows[1][0] == 2 and rows[1][1] == "Bob" and abs(rows[1][2] - 200.75) < 0.01
assert rows[2][0] == 3 and rows[2][1] == "Charlie" and abs(rows[2][2] - 300.25) < 0.01
# Cleanup
cursor.execute(f"DROP TABLE {table_name}")
cursor.close()
finally:
conn.close()
def test_bulkcopy_with_server_synonyms(conn_str):
"""Test that bulkcopy works with all SERVER parameter synonyms: server, addr, address."""
from mssql_python import connect
from mssql_python.connection_string_parser import _ConnectionStringParser
from mssql_python.connection_string_builder import _ConnectionStringBuilder
# Parse the connection string using the proper parser
parser = _ConnectionStringParser(validate_keywords=False)
params = parser._parse(conn_str)
# Test with 'Addr' synonym - replace 'server' with 'addr'
server_value = (
params.pop("server", None) or params.pop("addr", None) or params.pop("address", None)
)
params["addr"] = server_value
builder = _ConnectionStringBuilder(params)
conn_string_addr = builder.build()
conn = connect(conn_string_addr)
try:
cursor = conn.cursor()
table_name = "test_bulkcopy_addr_synonym"
# Create table
cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
cursor.execute(f"""
CREATE TABLE {table_name} (
id INT,
name NVARCHAR(50),
value FLOAT
)
""")
conn.commit()
# Test data
test_data = [(1, "Test1", 1.5), (2, "Test2", 2.5), (3, "Test3", 3.5)]
# Perform bulkcopy with connection using Addr parameter
result = cursor.bulkcopy(table_name, test_data)
# Verify result
assert result is not None
assert "rows_copied" in result
assert result["rows_copied"] == 3
# Verify data
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
count = cursor.fetchone()[0]
assert count == 3
# Cleanup
cursor.execute(f"DROP TABLE {table_name}")
cursor.close()
finally:
conn.close()
# Test with 'Address' synonym - replace with 'address'
params = parser._parse(conn_str)
server_value = (
params.pop("server", None) or params.pop("addr", None) or params.pop("address", None)
)
params["address"] = server_value
builder = _ConnectionStringBuilder(params)
conn_string_address = builder.build()
conn = connect(conn_string_address)
try:
cursor = conn.cursor()
table_name = "test_bulkcopy_address_synonym"
# Create table
cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
cursor.execute(f"""
CREATE TABLE {table_name} (
id INT,
name NVARCHAR(50),
value FLOAT
)
""")
conn.commit()
# Test data
test_data = [(1, "Test1", 1.5), (2, "Test2", 2.5), (3, "Test3", 3.5)]
# Perform bulkcopy with connection using Address parameter
result = cursor.bulkcopy(table_name, test_data)
# Verify result
assert result is not None
assert "rows_copied" in result
assert result["rows_copied"] == 3
# Verify data
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
count = cursor.fetchone()[0]
assert count == 3
# Cleanup
cursor.execute(f"DROP TABLE {table_name}")
cursor.close()
finally:
conn.close()
# Test that bulkcopy fails when SERVER parameter is missing entirely
params = parser._parse(conn_str)
# Remove all server synonyms
params.pop("server", None)
params.pop("addr", None)
params.pop("address", None)
builder = _ConnectionStringBuilder(params)
conn_string_no_server = builder.build()
# Ensure we have a valid connection string for the main connection
conn = connect(conn_str)
try:
cursor = conn.cursor()
# Manually override the connection string to one without server
cursor.connection.connection_str = conn_string_no_server
table_name = "test_bulkcopy_no_server"
test_data = [(1, "Test1", 1.5)]
# This should raise ValueError due to missing SERVER parameter
try:
cursor.bulkcopy(table_name, test_data)
assert False, "Expected ValueError for missing SERVER parameter"
except ValueError as e:
assert "SERVER parameter is required" in str(e)
cursor.close()
finally:
conn.close()
# ---------------------------------------------------------
# GH-482: Regression tests for bulkcopy Row acceptance
# ---------------------------------------------------------
def test_bulkcopy_fetchmany_row_objects(cursor):
"""Regression test: fetchmany() Row objects piped directly into bulkcopy (GH-482).
This is the primary use case from the customer report — table-to-table
copy where fetchmany returns Row objects that bulkcopy must accept.
"""
source_table = "mssql_python_bcp_row_src"
target_table = "mssql_python_bcp_row_tgt"
try:
# Setup source table with data
cursor.execute(f"IF OBJECT_ID('{source_table}', 'U') IS NOT NULL DROP TABLE {source_table}")
cursor.execute(f"CREATE TABLE {source_table} (id INT, name NVARCHAR(50), val FLOAT)")
cursor.connection.commit()
cursor.executemany(
f"INSERT INTO {source_table} VALUES (?, ?, ?)",
[(1, "Alice", 10.5), (2, "Bob", 20.75), (3, "Charlie", 30.25)],
)
cursor.connection.commit()
# Setup empty target table
cursor.execute(f"IF OBJECT_ID('{target_table}', 'U') IS NOT NULL DROP TABLE {target_table}")
cursor.execute(f"CREATE TABLE {target_table} (id INT, name NVARCHAR(50), val FLOAT)")
cursor.connection.commit()
# Fetch Row objects from source
cursor.execute(f"SELECT id, name, val FROM {source_table} ORDER BY id")
rows = cursor.fetchmany(100) # Returns list[Row]
assert len(rows) == 3
# Pipe Row objects directly into bulkcopy — this is the GH-482 fix
result = cursor.bulkcopy(target_table, rows, timeout=60)
assert result["rows_copied"] == 3
# Verify data landed correctly
cursor.execute(f"SELECT id, name, val FROM {target_table} ORDER BY id")
target_rows = cursor.fetchall()
assert len(target_rows) == 3
assert target_rows[0][0] == 1 and target_rows[0][1] == "Alice"
assert target_rows[1][0] == 2 and target_rows[1][1] == "Bob"
assert target_rows[2][0] == 3 and target_rows[2][1] == "Charlie"
finally:
cursor.execute(f"IF OBJECT_ID('{source_table}', 'U') IS NOT NULL DROP TABLE {source_table}")
cursor.execute(f"IF OBJECT_ID('{target_table}', 'U') IS NOT NULL DROP TABLE {target_table}")
cursor.connection.commit()
def test_bulkcopy_fetchall_row_objects(cursor):
"""Regression test: fetchall() Row objects piped directly into bulkcopy (GH-482)."""
source_table = "mssql_python_bcp_fetchall_src"
target_table = "mssql_python_bcp_fetchall_tgt"
try:
cursor.execute(f"IF OBJECT_ID('{source_table}', 'U') IS NOT NULL DROP TABLE {source_table}")
cursor.execute(f"CREATE TABLE {source_table} (id INT, txt VARCHAR(20))")
cursor.connection.commit()
cursor.executemany(
f"INSERT INTO {source_table} VALUES (?, ?)",
[(1, "row1"), (2, "row2")],
)
cursor.connection.commit()
cursor.execute(f"IF OBJECT_ID('{target_table}', 'U') IS NOT NULL DROP TABLE {target_table}")
cursor.execute(f"CREATE TABLE {target_table} (id INT, txt VARCHAR(20))")
cursor.connection.commit()
# fetchall returns list[Row]
cursor.execute(f"SELECT id, txt FROM {source_table} ORDER BY id")
rows = cursor.fetchall()
result = cursor.bulkcopy(target_table, rows, timeout=60)
assert result["rows_copied"] == 2
cursor.execute(f"SELECT id, txt FROM {target_table} ORDER BY id")
target_rows = cursor.fetchall()
assert len(target_rows) == 2
assert target_rows[0][1] == "row1"
assert target_rows[1][1] == "row2"
finally:
cursor.execute(f"IF OBJECT_ID('{source_table}', 'U') IS NOT NULL DROP TABLE {source_table}")
cursor.execute(f"IF OBJECT_ID('{target_table}', 'U') IS NOT NULL DROP TABLE {target_table}")
cursor.connection.commit()
def test_bulkcopy_rejects_list_rows(cursor):
"""Regression test: list rows are rejected since Rust only accepts PyTuple (GH-482)."""
table_name = "mssql_python_bcp_list_reject"
try:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT)")
cursor.connection.commit()
# list rows should raise TypeError — Rust rejects PyList
with pytest.raises(TypeError, match="tuples or Row objects"):
cursor.bulkcopy(table_name, [[1], [2], [3]], timeout=60)
finally:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.connection.commit()
def test_bulkcopy_tuple_passthrough(cursor):
"""Regression test: tuple rows still work as before (GH-482 doesn't break existing)."""
table_name = "mssql_python_bcp_tuple_pass"
try:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT, name VARCHAR(20))")
cursor.connection.commit()
data = [(1, "Alice"), (2, "Bob")]
result = cursor.bulkcopy(table_name, data, timeout=60)
assert result["rows_copied"] == 2
finally:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.connection.commit()
def test_bulkcopy_accepts_timeout_zero(cursor):
"""GH-697: timeout=0 means no timeout per the BCP spec, so it must not be rejected."""
table_name = "mssql_python_bcp_timeout_zero"
try:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT, name VARCHAR(20))")
cursor.connection.commit()
result = cursor.bulkcopy(table_name, [(1, "Alice"), (2, "Bob")], timeout=0)
assert result["rows_copied"] == 2
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
assert cursor.fetchone()[0] == 2
finally:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.connection.commit()
def test_bulkcopy_timeout_zero_disables_the_timeout(cursor):
"""GH-697: a copy that times out at timeout=1 completes at timeout=0.
The source paces itself with sleeps so the copy always outlives a 1 second
timeout regardless of machine speed. Same source both times, so the only
variable is the timeout value.
"""
table_name = "mssql_python_bcp_timeout_zero_behaviour"
def slow_rows():
for i in range(30):
time.sleep(0.1) # 3s total, comfortably past the 1s timeout
yield (i, f"row{i}")
try:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT, name NVARCHAR(50))")
cursor.connection.commit()
# baseline: the timeout is real and fires on this source
with pytest.raises(Exception, match="(?i)timeout"):
cursor.bulkcopy(table_name, slow_rows(), timeout=1)
cursor.execute(f"DELETE FROM {table_name}")
cursor.connection.commit()
# same source, timeout disabled: runs to completion
result = cursor.bulkcopy(table_name, slow_rows(), timeout=0)
assert result["rows_copied"] == 30
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
assert cursor.fetchone()[0] == 30
finally:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.connection.commit()
def test_bulkcopy_rejects_invalid_timeouts(cursor):
"""GH-697: negatives and bools stay rejected. Validation fires before any DB work."""
with pytest.raises(ValueError, match="timeout must be non-negative"):
cursor.bulkcopy("mssql_python_bcp_unused", [(1,)], timeout=-1)
with pytest.raises(TypeError, match="timeout must be a non-negative integer"):
cursor.bulkcopy("mssql_python_bcp_unused", [(1,)], timeout=1.5)
# bool is an int subclass, so False would otherwise slip through as 0
# and silently disable the timeout.
for flag in (False, True):
with pytest.raises(TypeError, match="timeout must be a non-negative integer"):
cursor.bulkcopy("mssql_python_bcp_unused", [(1,)], timeout=flag)
def test_bulkcopy_empty_iterator(cursor):
"""Regression test: empty iterator doesn't crash (GH-482)."""
table_name = "mssql_python_bcp_empty"
try:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.execute(f"CREATE TABLE {table_name} (id INT)")
cursor.connection.commit()
result = cursor.bulkcopy(table_name, [], timeout=60)
assert result["rows_copied"] == 0
finally:
cursor.execute(f"IF OBJECT_ID('{table_name}', 'U') IS NOT NULL DROP TABLE {table_name}")
cursor.connection.commit()
def test_bulkcopy_udt_geometry(cursor):
"""GH-667: bulk copy into a CLR UDT column.
Custom (user-defined) CLR UDTs require a deployed assembly, so this test uses
the built-in ``geometry`` CLR UDT, which travels the identical TDS ``0xF0``
wire path. Before the fix, bulk copy of any UDT column failed with
``Unsupported TDS type for bulk copy: 0xF0``; the fix streams UDTs as
``varbinary(max)`` (their ``IBinarySerialize`` form).
The test seeds a ``geometry`` column, reads the serialized UDT bytes back,
bulk copies them into a second ``geometry`` column, and verifies a byte-exact
round-trip (including a NULL).
"""
src = "mssql_python_bcp_udt_src"
dst = "mssql_python_bcp_udt_dst"
def _read(table):
cursor.execute(f"SELECT id, g FROM {table} ORDER BY id")
return [(r[0], bytes(r[1]) if r[1] is not None else None) for r in cursor.fetchall()]
try:
# Seed a geometry (built-in CLR UDT) source table via T-SQL.
cursor.execute(f"IF OBJECT_ID('{src}', 'U') IS NOT NULL DROP TABLE {src}")
cursor.execute(f"CREATE TABLE {src} (id INT NOT NULL, g geometry NULL)")
cursor.execute(
f"INSERT INTO {src} (id, g) VALUES "
"(1, geometry::STGeomFromText('POINT(1 2)', 0)), "
"(2, geometry::STGeomFromText('LINESTRING(0 0, 10 10, 20 25)', 0)), "
"(3, NULL), "
"(4, geometry::STGeomFromText('POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))', 0))"
)
cursor.connection.commit()
# Read the serialized UDT bytes back (unaffected by the fix).
source_rows = _read(src)
assert len(source_rows) == 4
assert sum(1 for _, g in source_rows if g is not None) == 3
assert any(g is None for _, g in source_rows)
# Destination geometry table.
cursor.execute(f"IF OBJECT_ID('{dst}', 'U') IS NOT NULL DROP TABLE {dst}")
cursor.execute(f"CREATE TABLE {dst} (id INT NOT NULL, g geometry NULL)")
cursor.connection.commit()
# Bulk copy the UDT bytes into the geometry column. Requires the GH-667
# fix in the bundled mssql_py_core (both the varbinary(max) wire mapping
# and the bytes->UDT value-coercion). Pre-fix this failed with
# "Unsupported TDS type for bulk copy: 0xF0" / a bad varbinary(-1) type /
# a "target SQL type is Udt" coercion error.
result = cursor.bulkcopy(dst, source_rows, timeout=60)
assert result["rows_copied"] == 4
# Verify byte-exact round-trip, including the NULL row.
assert _read(dst) == source_rows
finally:
cursor.execute(f"IF OBJECT_ID('{src}', 'U') IS NOT NULL DROP TABLE {src}")
cursor.execute(f"IF OBJECT_ID('{dst}', 'U') IS NOT NULL DROP TABLE {dst}")
cursor.connection.commit()
You can’t perform that action at this time.
