forked from sqlalchemy/sqlalchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_resultset.py
3711 lines (3049 loc) · 118 KB
/
test_resultset.py
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import collections.abc as collections_abc
from contextlib import contextmanager
import csv
from io import StringIO
import operator
import os
import pickle
import subprocess
import sys
from tempfile import mkstemp
from unittest.mock import Mock
from unittest.mock import patch
from sqlalchemy import CHAR
from sqlalchemy import column
from sqlalchemy import exc
from sqlalchemy import exc as sa_exc
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import INT
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import literal_column
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import sql
from sqlalchemy import String
from sqlalchemy import table
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import true
from sqlalchemy import tuple_
from sqlalchemy import type_coerce
from sqlalchemy import TypeDecorator
from sqlalchemy import VARCHAR
from sqlalchemy.engine import cursor as _cursor
from sqlalchemy.engine import default
from sqlalchemy.engine import Row
from sqlalchemy.engine.result import SimpleResultMetaData
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import ColumnElement
from sqlalchemy.sql import expression
from sqlalchemy.sql import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy.sql.selectable import LABEL_STYLE_NONE
from sqlalchemy.sql.selectable import TextualSelect
from sqlalchemy.sql.sqltypes import NULLTYPE
from sqlalchemy.sql.util import ClauseAdapter
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import assertions
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import in_
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_false
from sqlalchemy.testing import is_true
from sqlalchemy.testing import le_
from sqlalchemy.testing import mock
from sqlalchemy.testing import ne_
from sqlalchemy.testing import not_in
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
class CursorResultTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("user_name", VARCHAR(20)),
test_needs_acid=True,
)
Table(
"addresses",
metadata,
Column(
"address_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("user_id", Integer, ForeignKey("users.user_id")),
Column("address", String(30)),
test_needs_acid=True,
)
Table(
"users2",
metadata,
Column("user_id", INT, primary_key=True),
Column("user_name", VARCHAR(20)),
test_needs_acid=True,
)
Table(
"test",
metadata,
Column(
"x", Integer, primary_key=True, test_needs_autoincrement=False
),
Column("y", String(50)),
)
@testing.variation(
"type_", ["text", "driversql", "core", "textstar", "driverstar"]
)
def test_freeze(self, type_, connection):
"""test #8963"""
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
if type_.core:
stmt = select(users).order_by(users.c.user_id)
else:
if "star" in type_.name:
stmt = "select * from users order by user_id"
else:
stmt = "select user_id, user_name from users order by user_id"
if "text" in type_.name:
stmt = text(stmt)
if "driver" in type_.name:
result = connection.exec_driver_sql(stmt)
else:
result = connection.execute(stmt)
frozen = result.freeze()
unfrozen = frozen()
eq_(unfrozen.keys(), ["user_id", "user_name"])
eq_(unfrozen.all(), [(1, "john"), (2, "jack")])
unfrozen = frozen()
eq_(
unfrozen.mappings().all(),
[
{"user_id": 1, "user_name": "john"},
{"user_id": 2, "user_name": "jack"},
],
)
@testing.requires.insert_executemany_returning
def test_splice_horizontally(self, connection):
users = self.tables.users
addresses = self.tables.addresses
r1 = connection.execute(
users.insert().returning(users.c.user_name, users.c.user_id),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r2 = connection.execute(
addresses.insert().returning(
addresses.c.address_id,
addresses.c.address,
addresses.c.user_id,
),
[
dict(address_id=1, user_id=1, address="foo@bar.com"),
dict(address_id=2, user_id=2, address="bar@bat.com"),
],
)
rows = r1.splice_horizontally(r2).all()
eq_(
rows,
[
("john", 1, 1, "foo@bar.com", 1),
("jack", 2, 2, "bar@bat.com", 2),
],
)
eq_(rows[0]._mapping[users.c.user_id], 1)
eq_(rows[0]._mapping[addresses.c.user_id], 1)
eq_(rows[1].address, "bar@bat.com")
with expect_raises_message(
exc.InvalidRequestError, "Ambiguous column name 'user_id'"
):
rows[0].user_id
def test_keys_no_rows(self, connection):
for i in range(2):
r = connection.execute(
text("update users set user_name='new' where user_id=10")
)
with expect_raises_message(
exc.ResourceClosedError,
"This result object does not return rows",
):
r.keys()
def test_row_keys_removed(self, connection):
r = connection.execute(
text("select * from users where user_id=2")
).first()
with expect_raises(AttributeError):
r.keys()
def test_row_contains_key_no_strings(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2")
).first()
not_in("user_name", r)
in_("user_name", r._mapping)
not_in("foobar", r)
not_in("foobar", r._mapping)
def test_row_iteration(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.execute(users.select())
rows = []
for row in r:
rows.append(row)
eq_(len(rows), 3)
def test_scalars(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.scalars(users.select().order_by(users.c.user_id))
eq_(r.all(), [7, 8, 9])
def test_result_tuples(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.execute(
users.select().order_by(users.c.user_id)
).tuples()
eq_(r.all(), [(7, "jack"), (8, "ed"), (9, "fred")])
def test_row_tuple(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.execute(users.select().order_by(users.c.user_id)).all()
exp = [(7, "jack"), (8, "ed"), (9, "fred")]
eq_([row._t for row in r], exp)
eq_([row._tuple() for row in r], exp)
with assertions.expect_deprecated(
r"The Row.t attribute is deprecated in favor of Row._t"
):
eq_([row.t for row in r], exp)
with assertions.expect_deprecated(
r"The Row.tuple\(\) method is deprecated in "
r"favor of Row._tuple\(\)"
):
eq_([row.tuple() for row in r], exp)
def test_row_next(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
r = connection.execute(users.select())
rows = []
while True:
row = next(r, "foo")
if row == "foo":
break
rows.append(row)
eq_(len(rows), 3)
@testing.requires.subqueries
def test_anonymous_rows(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
sel = (
select(users.c.user_id)
.where(users.c.user_name == "jack")
.scalar_subquery()
)
for row in connection.execute(select(sel + 1, sel + 3)):
eq_(row._mapping["anon_1"], 8)
eq_(row._mapping["anon_2"], 10)
def test_row_comparison(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=7, user_name="jack"))
rp = connection.execute(users.select()).first()
eq_(rp, rp)
is_(not (rp != rp), True)
equal = (7, "jack")
eq_(rp, equal)
eq_(equal, rp)
is_((not (rp != equal)), True)
is_(not (equal != equal), True)
def endless():
while True:
yield 1
ne_(rp, endless())
ne_(endless(), rp)
# test that everything compares the same
# as it would against a tuple
for compare in [False, 8, endless(), "xyz", (7, "jack")]:
for op in [
operator.eq,
operator.ne,
operator.gt,
operator.lt,
operator.ge,
operator.le,
]:
try:
control = op(equal, compare)
except TypeError:
# Py3K raises TypeError for some invalid comparisons
assert_raises(TypeError, op, rp, compare)
else:
eq_(control, op(rp, compare))
try:
control = op(compare, equal)
except TypeError:
# Py3K raises TypeError for some invalid comparisons
assert_raises(TypeError, op, compare, rp)
else:
eq_(control, op(compare, rp))
@testing.provide_metadata
def test_column_label_overlap_fallback(self, connection):
content = Table("content", self.metadata, Column("type", String(30)))
bar = Table("bar", self.metadata, Column("content_type", String(30)))
self.metadata.create_all(connection)
connection.execute(content.insert().values(type="t1"))
row = connection.execute(
content.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
).first()
in_(content.c.type, row._mapping)
not_in(bar.c.content_type, row._mapping)
# in 1.x, would warn for string match, but return a result
not_in(sql.column("content_type"), row)
not_in(bar.c.content_type, row._mapping)
row = connection.execute(
select(func.now().label("content_type"))
).first()
not_in(content.c.type, row._mapping)
not_in(bar.c.content_type, row._mapping)
# in 1.x, would warn for string match, but return a result
not_in(sql.column("content_type"), row._mapping)
def _pickle_row_data(self, connection, use_labels):
users = self.tables.users
connection.execute(
users.insert(),
[
{"user_id": 7, "user_name": "jack"},
{"user_id": 8, "user_name": "ed"},
{"user_id": 9, "user_name": "fred"},
],
)
result = connection.execute(
users.select()
.order_by(users.c.user_id)
.set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
if use_labels
else LABEL_STYLE_NONE
)
).all()
return result
@testing.variation("use_pickle", [True, False])
@testing.variation("use_labels", [True, False])
def test_pickled_rows(self, connection, use_pickle, use_labels):
users = self.tables.users
addresses = self.tables.addresses
result = self._pickle_row_data(connection, use_labels)
if use_pickle:
result = pickle.loads(pickle.dumps(result))
eq_(result, [(7, "jack"), (8, "ed"), (9, "fred")])
if use_labels:
eq_(result[0]._mapping["users_user_id"], 7)
eq_(
list(result[0]._fields),
["users_user_id", "users_user_name"],
)
else:
eq_(result[0]._mapping["user_id"], 7)
eq_(list(result[0]._fields), ["user_id", "user_name"])
eq_(result[0][0], 7)
assert_raises(
exc.NoSuchColumnError,
lambda: result[0]._mapping["fake key"],
)
# previously would warn
if use_pickle:
with expect_raises_message(
exc.NoSuchColumnError,
"Row was unpickled; lookup by ColumnElement is " "unsupported",
):
result[0]._mapping[users.c.user_id]
else:
eq_(result[0]._mapping[users.c.user_id], 7)
if use_pickle:
with expect_raises_message(
exc.NoSuchColumnError,
"Row was unpickled; lookup by ColumnElement is " "unsupported",
):
result[0]._mapping[users.c.user_name]
else:
eq_(result[0]._mapping[users.c.user_name], "jack")
assert_raises(
exc.NoSuchColumnError,
lambda: result[0]._mapping[addresses.c.user_id],
)
assert_raises(
exc.NoSuchColumnError,
lambda: result[0]._mapping[addresses.c.address_id],
)
@testing.variation("use_labels", [True, False])
def test_pickle_rows_other_process(self, connection, use_labels):
result = self._pickle_row_data(connection, use_labels)
f, name = mkstemp("pkl")
with os.fdopen(f, "wb") as f:
pickle.dump(result, f)
name = name.replace(os.sep, "/")
code = (
"import sqlalchemy; import pickle; print(["
f"r[0] for r in pickle.load(open('''{name}''', 'rb'))])"
)
proc = subprocess.run(
[sys.executable, "-c", code], stdout=subprocess.PIPE
)
exp = str([r[0] for r in result]).encode()
eq_(proc.returncode, 0)
eq_(proc.stdout.strip(), exp)
os.unlink(name)
def test_column_error_printing(self, connection):
result = connection.execute(select(1))
row = result.first()
class unprintable:
def __str__(self):
raise ValueError("nope")
msg = r"Could not locate column in row for column '%s'"
for accessor, repl in [
("x", "x"),
(Column("q", Integer), "q"),
(Column("q", Integer) + 12, r"q \+ :q_1"),
(unprintable(), "unprintable element.*"),
]:
assert_raises_message(
exc.NoSuchColumnError, msg % repl, result._getter, accessor
)
is_(result._getter(accessor, False), None)
assert_raises_message(
exc.NoSuchColumnError,
msg % repl,
lambda: row._mapping[accessor],
)
def test_fetchmany(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "n%d" % i} for i in range(7, 15)],
)
r = connection.execute(users.select())
rows = []
for row in r.fetchmany(size=2):
rows.append(row)
eq_(len(rows), 2)
@testing.requires.arraysize
def test_fetchmany_arraysize_default(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "n%d" % i} for i in range(1, 150)],
)
r = connection.execute(users.select())
arraysize = r.cursor.arraysize
rows = list(r.fetchmany())
eq_(len(rows), min(arraysize, 150))
@testing.requires.arraysize
def test_fetchmany_arraysize_set(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "n%d" % i} for i in range(7, 15)],
)
r = connection.execute(users.select())
r.cursor.arraysize = 4
rows = list(r.fetchmany())
eq_(len(rows), 4)
def test_column_slices(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
connection.execute(users.insert(), dict(user_id=2, user_name="jack"))
connection.execute(
addresses.insert(),
dict(address_id=1, user_id=2, address="foo@bar.com"),
)
r = connection.execute(text("select * from addresses")).first()
eq_(r[0:1], (1,))
eq_(r[1:], (2, "foo@bar.com"))
eq_(r[:-1], (1, 2))
def test_mappings(self, connection):
users = self.tables.users
addresses = self.tables.addresses
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
connection.execute(users.insert(), dict(user_id=2, user_name="jack"))
connection.execute(
addresses.insert(),
dict(address_id=1, user_id=2, address="foo@bar.com"),
)
r = connection.execute(text("select * from addresses"))
eq_(
r.mappings().all(),
[{"address_id": 1, "user_id": 2, "address": "foo@bar.com"}],
)
def test_column_accessor_basic_compiled_mapping(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
users.select().where(users.c.user_id == 2)
).first()
eq_(r.user_id, 2)
eq_(r._mapping["user_id"], 2)
eq_(r._mapping[users.c.user_id], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
eq_(r._mapping[users.c.user_name], "jack")
def test_column_accessor_basic_compiled_traditional(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
users.select().where(users.c.user_id == 2)
).first()
eq_(r.user_id, 2)
eq_(r._mapping["user_id"], 2)
eq_(r._mapping[users.c.user_id], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
eq_(r._mapping[users.c.user_name], "jack")
@testing.combinations(
(select(literal_column("1").label("col1")), ("col1",)),
(
select(
literal_column("1").label("col1"),
literal_column("2").label("col2"),
),
("col1", "col2"),
),
argnames="sql,cols",
)
def test_compiled_star_doesnt_interfere_w_description(
self, connection, sql, cols
):
"""test #6665"""
row = connection.execute(
select("*").select_from(sql.subquery())
).first()
eq_(row._fields, cols)
eq_(row._mapping["col1"], 1)
def test_row_getitem_string(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2")
).first()
with expect_raises_message(TypeError, "tuple indices must be"):
r["foo"]
eq_(r._mapping["user_name"], "jack")
def test_row_getitem_column(self, connection):
col = literal_column("1").label("foo")
row = connection.execute(select(col)).first()
with expect_raises_message(TypeError, "tuple indices must be"):
row[col]
eq_(row._mapping[col], 1)
def test_column_accessor_basic_text(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2")
).first()
eq_(r.user_id, 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_id"], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
# cases which used to succeed w warning
with expect_raises_message(
exc.NoSuchColumnError, "Could not locate column in row"
):
r._mapping[users.c.user_id]
with expect_raises_message(
exc.NoSuchColumnError, "Could not locate column in row"
):
r._mapping[users.c.user_name]
def test_column_accessor_text_colexplicit(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
r = connection.execute(
text("select * from users where user_id=2").columns(
users.c.user_id, users.c.user_name
)
).first()
eq_(r.user_id, 2)
eq_(r._mapping["user_id"], 2)
eq_(r._mapping[users.c.user_id], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
eq_(r._mapping[users.c.user_name], "jack")
def test_column_accessor_textual_select(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
[
dict(user_id=1, user_name="john"),
dict(user_id=2, user_name="jack"),
],
)
# this will create column() objects inside
# the select(), these need to match on name anyway
r = connection.execute(
select(column("user_id"), column("user_name"))
.select_from(table("users"))
.where(text("user_id=2"))
).first()
# keyed access works in many ways
eq_(r.user_id, 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_id"], 2)
eq_(r.user_name, "jack")
eq_(r._mapping["user_name"], "jack")
# error cases that previously would warn
with expect_raises_message(
exc.NoSuchColumnError, "Could not locate column in row"
):
r._mapping[users.c.user_id]
with expect_raises_message(
exc.NoSuchColumnError, "Could not locate column in row"
):
r._mapping[users.c.user_name]
def test_column_accessor_dotted_union(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# test a little sqlite < 3.10.0 weirdness - with the UNION,
# cols come back as "users.user_id" in cursor.description
r = connection.execute(
text(
"select users.user_id, users.user_name "
"from users "
"UNION select users.user_id, "
"users.user_name from users"
)
).first()
eq_(r._mapping["user_id"], 1)
eq_(r._mapping["user_name"], "john")
eq_(list(r._fields), ["user_id", "user_name"])
def test_column_accessor_sqlite_raw(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
r = connection.execute(
text(
"select users.user_id, users.user_name "
"from users "
"UNION select users.user_id, "
"users.user_name from users",
).execution_options(sqlite_raw_colnames=True)
).first()
if testing.against("sqlite < 3.10.0"):
not_in("user_id", r)
not_in("user_name", r)
eq_(r["users.user_id"], 1)
eq_(r["users.user_name"], "john")
eq_(list(r._fields), ["users.user_id", "users.user_name"])
else:
not_in("users.user_id", r._mapping)
not_in("users.user_name", r._mapping)
eq_(r._mapping["user_id"], 1)
eq_(r._mapping["user_name"], "john")
eq_(list(r._fields), ["user_id", "user_name"])
def test_column_accessor_sqlite_translated(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
r = connection.execute(
text(
"select users.user_id, users.user_name "
"from users "
"UNION select users.user_id, "
"users.user_name from users",
)
).first()
eq_(r._mapping["user_id"], 1)
eq_(r._mapping["user_name"], "john")
if testing.against("sqlite < 3.10.0"):
eq_(r._mapping["users.user_id"], 1)
eq_(r._mapping["users.user_name"], "john")
else:
not_in("users.user_id", r._mapping)
not_in("users.user_name", r._mapping)
eq_(list(r._fields), ["user_id", "user_name"])
def test_column_accessor_labels_w_dots(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# test using literal tablename.colname
r = connection.execute(
text(
'select users.user_id AS "users.user_id", '
'users.user_name AS "users.user_name" '
"from users",
).execution_options(sqlite_raw_colnames=True)
).first()
eq_(r._mapping["users.user_id"], 1)
eq_(r._mapping["users.user_name"], "john")
not_in("user_name", r._mapping)
eq_(list(r._fields), ["users.user_id", "users.user_name"])
def test_column_accessor_unary(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# unary expressions
r = connection.execute(
select(users.c.user_name.distinct()).order_by(users.c.user_name)
).first()
eq_(r._mapping[users.c.user_name], "john")
eq_(r.user_name, "john")
@testing.fixture
def _ab_row_fixture(self, connection):
r = connection.execute(
select(literal(1).label("a"), literal(2).label("b"))
).first()
return r
def test_named_tuple_access(self, _ab_row_fixture):
r = _ab_row_fixture
eq_(r.a, 1)
eq_(r.b, 2)
def test_named_tuple_missing_attr(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(
AttributeError, "Could not locate column in row for column 'c'"
):
r.c
def test_named_tuple_no_delete_present(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(AttributeError, "can't delete attribute"):
del r.a
def test_named_tuple_no_delete_missing(self, _ab_row_fixture):
r = _ab_row_fixture
# including for non-existent attributes
with expect_raises_message(AttributeError, "can't delete attribute"):
del r.c
def test_named_tuple_no_assign_present(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(AttributeError, "can't set attribute"):
r.a = 5
with expect_raises_message(AttributeError, "can't set attribute"):
r.a += 5
def test_named_tuple_no_assign_missing(self, _ab_row_fixture):
r = _ab_row_fixture
# including for non-existent attributes
with expect_raises_message(AttributeError, "can't set attribute"):
r.c = 5
def test_named_tuple_no_self_assign_missing(self, _ab_row_fixture):
r = _ab_row_fixture
with expect_raises_message(
AttributeError, "Could not locate column in row for column 'c'"
):
r.c += 5
def test_mapping_tuple_readonly_errors(self, connection):
r = connection.execute(
select(literal(1).label("a"), literal(2).label("b"))
).first()
r = r._mapping
eq_(r["a"], 1)
eq_(r["b"], 2)
with expect_raises_message(
KeyError, "Could not locate column in row for column 'c'"
):
r["c"]
with expect_raises_message(
TypeError, "'RowMapping' object does not support item assignment"
):
r["a"] = 5
with expect_raises_message(
TypeError, "'RowMapping' object does not support item assignment"