Repository navigation
Expand file tree
/
Copy pathtest_bindings.py
More file actions
439 lines (406 loc) · 14.5 KB
/
Copy pathtest_bindings.py
File metadata and controls
439 lines (406 loc) · 14.5 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
import logging
import tempfile
from os import path
tempfile.gettempdir()
for logger_name in ['snowflake.connector', 'botocore']:
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
ch = logging.FileHandler(
path.join(tempfile.gettempdir(), 'python_connector.log'))
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter(
'%(asctime)s - %(threadName)s %(filename)s:%(lineno)d - %(funcName)s() - %(levelname)s - %(message)s'))
logger.addHandler(ch)
import calendar
import time
from datetime import datetime, date, timedelta
from datetime import time as datetime_time
from decimal import Decimal
import pendulum
import pytest
import pytz
from snowflake.connector.compat import PY2
from snowflake.connector.converter import convert_datetime_to_epoch
from snowflake.connector.errors import ProgrammingError
PST_TZ = "America/Los_Angeles"
JST_TZ = "Asia/Tokyo"
def test_invalid_binding_option(conn_cnx):
"""
Invalid paramstyle parameters
"""
with pytest.raises(ProgrammingError):
with conn_cnx(paramstyle=u'hahaha'):
pass
# valid cases
for s in [u'format', u'pyformat', u'qmark', u'numeric']:
with conn_cnx(paramstyle=s):
pass
def test_binding(conn_cnx, db_parameters):
"""
Paramstyle qmark basic tests
"""
with conn_cnx(paramstyle=u'qmark') as cnx:
cnx.cursor().execute("""
create or replace table {name} (
c1 BOOLEAN,
c2 INTEGER,
c3 NUMBER(38,2),
c4 VARCHAR(1234),
c5 FLOAT,
c6 BINARY,
c7 BINARY,
c8 TIMESTAMP_NTZ,
c9 TIMESTAMP_NTZ,
c10 TIMESTAMP_NTZ,
c11 TIMESTAMP_NTZ,
c12 TIMESTAMP_LTZ,
c13 TIMESTAMP_LTZ,
c14 TIMESTAMP_LTZ,
c15 TIMESTAMP_LTZ,
c16 TIMESTAMP_TZ,
c17 TIMESTAMP_TZ,
c18 TIMESTAMP_TZ,
c19 TIMESTAMP_TZ,
c20 DATE,
c21 TIME,
c22 TIMESTAMP_NTZ,
c23 TIME,
c24 STRING
)
""".format(name=db_parameters['name']))
current_utctime = datetime.utcnow()
current_localtime = pytz.utc.localize(
current_utctime,
is_dst=False).astimezone(pytz.timezone(PST_TZ))
current_localtime_without_tz = datetime.now()
current_localtime_with_other_tz = pytz.utc.localize(
current_localtime_without_tz,
is_dst=False).astimezone(pytz.timezone(JST_TZ))
dt = date(2017, 12, 30)
tm = datetime_time(hour=1, minute=2, second=3, microsecond=456)
struct_time_v = time.strptime("30 Sep 01 11:20:30", "%d %b %y %H:%M:%S")
tdelta = timedelta(seconds=tm.hour * 3600 + tm.minute * 60 + tm.second,
microseconds=tm.microsecond)
try:
with conn_cnx(paramstyle=u'qmark', timezone=PST_TZ) as cnx:
cnx.cursor().execute("""
insert into {name} values(
?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?)
""".format(name=db_parameters['name']), (
True,
1,
Decimal("1.2"),
'str1',
1.2,
# Py2 has bytes in str type, so Python Connector
bytes(b'abc') if not PY2 else bytearray(b'abc'),
bytearray(b'def'),
current_utctime,
current_localtime,
current_localtime_without_tz,
current_localtime_with_other_tz,
(u"TIMESTAMP_LTZ", current_utctime),
(u"TIMESTAMP_LTZ", current_localtime),
(u"TIMESTAMP_LTZ", current_localtime_without_tz),
(u"TIMESTAMP_LTZ", current_localtime_with_other_tz),
(u"TIMESTAMP_TZ", current_utctime),
(u"TIMESTAMP_TZ", current_localtime),
(u"TIMESTAMP_TZ", current_localtime_without_tz),
(u"TIMESTAMP_TZ", current_localtime_with_other_tz),
dt,
tm,
(u"TIMESTAMP_NTZ", struct_time_v),
(u"TIME", tdelta),
(u"TEXT", None)
))
ret = cnx.cursor().execute("""
select * from {name} where c1=? and c2=?
""".format(name=db_parameters['name']), (
True,
1
)).fetchone()
assert ret[0], "BOOLEAN"
assert ret[2] == Decimal("1.2"), "NUMBER"
assert ret[4] == 1.2, "FLOAT"
assert ret[5] == b'abc'
assert ret[6] == b'def'
assert ret[7] == current_utctime
assert convert_datetime_to_epoch(
ret[8]) == convert_datetime_to_epoch(current_localtime)
assert convert_datetime_to_epoch(
ret[9]) == convert_datetime_to_epoch(
current_localtime_without_tz)
assert convert_datetime_to_epoch(
ret[10]) == convert_datetime_to_epoch(
current_localtime_with_other_tz)
assert convert_datetime_to_epoch(
ret[11]) == convert_datetime_to_epoch(current_utctime)
assert convert_datetime_to_epoch(
ret[12]) == convert_datetime_to_epoch(current_localtime)
assert convert_datetime_to_epoch(
ret[13]) == convert_datetime_to_epoch(
current_localtime_without_tz)
assert convert_datetime_to_epoch(
ret[14]) == convert_datetime_to_epoch(
current_localtime_with_other_tz)
assert convert_datetime_to_epoch(
ret[15]) == convert_datetime_to_epoch(current_utctime)
assert convert_datetime_to_epoch(
ret[16]) == convert_datetime_to_epoch(current_localtime)
assert convert_datetime_to_epoch(
ret[17]) == convert_datetime_to_epoch(
current_localtime_without_tz)
assert convert_datetime_to_epoch(
ret[18]) == convert_datetime_to_epoch(
current_localtime_with_other_tz)
assert ret[19] == dt
assert ret[20] == tm
assert convert_datetime_to_epoch(
ret[21]) == calendar.timegm(struct_time_v)
assert timedelta(seconds=ret[22].hour * 3600 + ret[22].minute * 60 +
ret[22].second,
microseconds=ret[22].microsecond) == tdelta
assert ret[23] is None
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
def test_pendulum_binding(conn_cnx, db_parameters):
pendulum_test = pendulum.now()
try:
with conn_cnx() as cnx:
cnx.cursor().execute("""
create or replace table {name} (
c1 timestamp
)
""".format(name=db_parameters['name']))
c = cnx.cursor()
fmt = "insert into {name}(c1) values(%(v1)s)".format(
name=db_parameters['name']
)
c.execute(fmt, {'v1': pendulum_test})
assert len(cnx.cursor().execute(
"select count(*) from {name}".format(
name=db_parameters['name'])).fetchall()) == 1
with conn_cnx(paramstyle=u'qmark') as cnx:
cnx.cursor().execute("""
create or replace table {name} (c1 timestamp, c2 timestamp)
""".format(name=db_parameters['name']))
with conn_cnx(paramstyle=u'qmark') as cnx:
cnx.cursor().execute("""
insert into {name} values(?, ?)
""".format(name=db_parameters['name']), (pendulum_test, pendulum_test))
ret = cnx.cursor().execute("""
select * from {name}
""".format(name=db_parameters['name'])).fetchone()
assert convert_datetime_to_epoch(
ret[0]) == convert_datetime_to_epoch(pendulum_test)
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
def test_binding_with_numeric(conn_cnx, db_parameters):
"""
Paramstyle numeric tests. Both qmark and numeric leverages server side
bindings.
"""
with conn_cnx(paramstyle=u'numeric') as cnx:
cnx.cursor().execute("""
create or replace table {name} (c1 integer, c2 string)
""".format(name=db_parameters['name']))
try:
with conn_cnx(paramstyle=u'numeric') as cnx:
cnx.cursor().execute("""
insert into {name}(c1, c2) values(:2, :1)
""".format(name=db_parameters['name']), (
u'str1',
123
))
cnx.cursor().execute("""
insert into {name}(c1, c2) values(:2, :1)
""".format(name=db_parameters['name']), (
u'str2',
456
))
# numeric and qmark can be used in the same session
rec = cnx.cursor().execute("""
select * from {name} where c1=?
""".format(name=db_parameters['name']), (123,)).fetchall()
assert len(rec) == 1
assert rec[0][0] == 123
assert rec[0][1] == u'str1'
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
def test_binding_timestamps(conn_cnx, db_parameters):
"""
Binding datetime object with TIMESTAMP_LTZ. The value is bound
as TIMESTAMP_NTZ, but since it is converted to UTC in the backend,
the returned value must be
"""
with conn_cnx() as cnx:
cnx.cursor().execute("""
create or replace table {name} (
c1 integer,
c2 timestamp_ltz)
""".format(name=db_parameters['name']))
try:
with conn_cnx(paramstyle=u'numeric', timezone=PST_TZ) as cnx:
current_localtime = datetime.now()
cnx.cursor().execute("""
insert into {name}(c1, c2) values(:1, :2)
""".format(name=db_parameters['name']), (
123,
("TIMESTAMP_LTZ", current_localtime)
))
rec = cnx.cursor().execute("""
select * from {name} where c1=?
""".format(name=db_parameters['name']), (123,)).fetchall()
assert len(rec) == 1
assert rec[0][0] == 123
assert convert_datetime_to_epoch(rec[0][1]) == \
convert_datetime_to_epoch(current_localtime)
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
def test_binding_bulk_insert(conn_cnx, db_parameters):
"""
Bulk insert test.
"""
with conn_cnx() as cnx:
cnx.cursor().execute("""
create or replace table {name} (
c1 integer,
c2 string
)
""".format(name=db_parameters['name']))
try:
with conn_cnx(paramstyle=u'qmark') as cnx:
# short list
c = cnx.cursor()
fmt = 'insert into {name}(c1,c2) values(?,?)'.format(
name=db_parameters['name'])
c.executemany(fmt, [
(1, 'test1'),
(2, 'test2'),
(3, 'test3'),
(4, 'test4'),
])
assert c.rowcount == 4
# large list
num_rows = 100000
c = cnx.cursor()
c.executemany(fmt, [
(idx, 'test{}'.format(idx)) for idx in range(num_rows)
])
assert c.rowcount == num_rows
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
def test_binding_bulk_update(conn_cnx, db_parameters):
"""
Bulk update test.
NOTE: UPDATE,MERGE and DELETE are not supported for actual bulk operation
but executemany accepts the multiple rows and iterate DMLs
"""
with conn_cnx() as cnx:
cnx.cursor().execute("""
create or replace table {name} (
c1 integer,
c2 string
)
""".format(name=db_parameters['name']))
try:
with conn_cnx(paramstyle=u'qmark') as cnx:
# short list
c = cnx.cursor()
fmt = 'insert into {name}(c1,c2) values(?,?)'.format(
name=db_parameters['name'])
c.executemany(fmt, [
(1, 'test1'),
(2, 'test2'),
(3, 'test3'),
(4, 'test4'),
])
assert c.rowcount == 4
fmt = "update {name} set c2=:2 where c1=:1".format(
name=db_parameters['name'])
c.executemany(fmt, [
(1, 'test5'),
(2, 'test6'),
])
assert c.rowcount == 2
fmt = "select * from {name} where c1=?".format(
name=db_parameters['name']
)
rec = cnx.cursor().execute(fmt, (1,)).fetchall()
assert rec[0][0] == 1
assert rec[0][1] == 'test5'
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
@pytest.mark.skipif(not PY2, reason="Long type test")
def test_binding_long_value(conn_cnx, db_parameters):
"""
Test binding a long value. The problem was it was bound as '1L' and raised
a SQL compilation error.
"""
try:
with conn_cnx() as cnx:
cnx.cursor().execute("""
create or replace table {name} (
c1 integer
)
""".format(name=db_parameters['name']))
c = cnx.cursor()
fmt = "insert into {name}(c1) values(%(v1)s)".format(
name=db_parameters['name']
)
c.execute(fmt, {'v1': long(1)})
assert len(cnx.cursor().execute(
"select count(*) from {name}".format(
name=db_parameters['name'])).fetchall()) == 1
finally:
with conn_cnx() as cnx:
cnx.cursor().execute("""
drop table if exists {name}
""".format(name=db_parameters['name']))
def test_binding_identifier(conn_cnx, db_parameters):
"""
Binding a table name
"""
try:
with conn_cnx(paramstyle=u'qmark') as cnx:
data = u'test'
cnx.cursor().execute("""
create or replace table identifier(?) (c1 string)
""", (db_parameters['name'],))
with conn_cnx(paramstyle=u'qmark') as cnx:
cnx.cursor().execute("""
insert into identifier(?) values(?)
""", (db_parameters['name'], data))
ret = cnx.cursor().execute("""
select * from identifier(?)
""", (db_parameters['name'],)).fetchall()
assert len(ret) == 1
assert ret[0][0] == data
finally:
with conn_cnx(paramstyle=u'qmark') as cnx:
cnx.cursor().execute("""
drop table if exists identifier(?)
""", (db_parameters['name'],))