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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
|
# coding: utf-8
import itertools
from operator import itemgetter
import re
import sqlalchemy as sa
from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import Index
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import join
from sqlalchemy import MetaData
from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import Sequence
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql import base as postgresql
from sqlalchemy.dialects.postgresql import ExcludeConstraint
from sqlalchemy.dialects.postgresql import INTEGER
from sqlalchemy.dialects.postgresql import INTERVAL
from sqlalchemy.dialects.postgresql import TSRANGE
from sqlalchemy.engine import reflection
from sqlalchemy.sql.schema import CheckConstraint
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock
from sqlalchemy.testing.assertions import assert_raises
from sqlalchemy.testing.assertions import AssertsExecutionResults
from sqlalchemy.testing.assertions import eq_
class ForeignTableReflectionTest(fixtures.TablesTest, AssertsExecutionResults):
"""Test reflection on foreign tables"""
__requires__ = ("postgresql_test_dblink",)
__only_on__ = "postgresql >= 9.3"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
from sqlalchemy.testing import config
dblink = config.file_config.get(
"sqla_testing", "postgres_test_db_link"
)
Table(
"testtable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(30)),
)
for ddl in [
"CREATE SERVER test_server FOREIGN DATA WRAPPER postgres_fdw "
"OPTIONS (dbname 'test', host '%s')" % dblink,
"CREATE USER MAPPING FOR public \
SERVER test_server options (user 'scott', password 'tiger')",
"CREATE FOREIGN TABLE test_foreigntable ( "
" id INT, "
" data VARCHAR(30) "
") SERVER test_server OPTIONS (table_name 'testtable')",
]:
sa.event.listen(metadata, "after_create", sa.DDL(ddl))
for ddl in [
"DROP FOREIGN TABLE test_foreigntable",
"DROP USER MAPPING FOR public SERVER test_server",
"DROP SERVER test_server",
]:
sa.event.listen(metadata, "before_drop", sa.DDL(ddl))
def test_foreign_table_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("test_foreigntable", metadata, autoload=True)
eq_(
set(table.columns.keys()),
set(["id", "data"]),
"Columns of reflected foreign table didn't equal expected columns",
)
def test_get_foreign_table_names(self):
inspector = inspect(testing.db)
with testing.db.connect():
ft_names = inspector.get_foreign_table_names()
eq_(ft_names, ["test_foreigntable"])
def test_get_table_names_no_foreign(self):
inspector = inspect(testing.db)
with testing.db.connect():
names = inspector.get_table_names()
eq_(names, ["testtable"])
class PartitionedReflectionTest(fixtures.TablesTest, AssertsExecutionResults):
# partitioned table reflection, issue #4237
__only_on__ = "postgresql >= 10"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
# the actual function isn't reflected yet
dv = Table(
"data_values",
metadata,
Column("modulus", Integer, nullable=False),
Column("data", String(30)),
Column("q", Integer),
postgresql_partition_by="range(modulus)",
)
# looks like this is reflected prior to #4237
sa.event.listen(
dv,
"after_create",
sa.DDL(
"CREATE TABLE data_values_4_10 PARTITION OF data_values "
"FOR VALUES FROM (4) TO (10)"
),
)
if testing.against("postgresql >= 11"):
Index("my_index", dv.c.q)
def test_get_tablenames(self):
assert {"data_values", "data_values_4_10"}.issubset(
inspect(testing.db).get_table_names()
)
def test_reflect_cols(self):
cols = inspect(testing.db).get_columns("data_values")
eq_([c["name"] for c in cols], ["modulus", "data", "q"])
def test_reflect_cols_from_partition(self):
cols = inspect(testing.db).get_columns("data_values_4_10")
eq_([c["name"] for c in cols], ["modulus", "data", "q"])
@testing.only_on("postgresql >= 11")
def test_reflect_index(self):
idx = inspect(testing.db).get_indexes("data_values")
eq_(
idx, [{"column_names": ["q"], "name": "my_index", "unique": False}]
)
@testing.only_on("postgresql >= 11")
def test_reflect_index_from_partition(self):
idx = inspect(testing.db).get_indexes("data_values_4_10")
# note the name appears to be generated by PG, currently
# 'data_values_4_10_q_idx'
eq_(idx, [{"column_names": ["q"], "name": mock.ANY, "unique": False}])
class MaterializedViewReflectionTest(
fixtures.TablesTest, AssertsExecutionResults
):
"""Test reflection on materialized views"""
__only_on__ = "postgresql >= 9.3"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
testtable = Table(
"testtable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(30)),
)
# insert data before we create the view
@sa.event.listens_for(testtable, "after_create")
def insert_data(target, connection, **kw):
connection.execute(target.insert(), {"id": 89, "data": "d1"})
materialized_view = sa.DDL(
"CREATE MATERIALIZED VIEW test_mview AS " "SELECT * FROM testtable"
)
plain_view = sa.DDL(
"CREATE VIEW test_regview AS " "SELECT * FROM testtable"
)
sa.event.listen(testtable, "after_create", plain_view)
sa.event.listen(testtable, "after_create", materialized_view)
sa.event.listen(
testtable,
"before_drop",
sa.DDL("DROP MATERIALIZED VIEW test_mview"),
)
sa.event.listen(
testtable, "before_drop", sa.DDL("DROP VIEW test_regview")
)
def test_mview_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("test_mview", metadata, autoload=True)
eq_(
set(table.columns.keys()),
set(["id", "data"]),
"Columns of reflected mview didn't equal expected columns",
)
def test_mview_select(self):
metadata = MetaData(testing.db)
table = Table("test_mview", metadata, autoload=True)
eq_(table.select().execute().fetchall(), [(89, "d1")])
def test_get_view_names(self):
insp = inspect(testing.db)
eq_(set(insp.get_view_names()), set(["test_regview", "test_mview"]))
def test_get_view_names_plain(self):
insp = inspect(testing.db)
eq_(
set(insp.get_view_names(include=("plain",))), set(["test_regview"])
)
def test_get_view_names_plain_string(self):
insp = inspect(testing.db)
eq_(set(insp.get_view_names(include="plain")), set(["test_regview"]))
def test_get_view_names_materialized(self):
insp = inspect(testing.db)
eq_(
set(insp.get_view_names(include=("materialized",))),
set(["test_mview"]),
)
def test_get_view_names_reflection_cache_ok(self):
insp = inspect(testing.db)
eq_(
set(insp.get_view_names(include=("plain",))), set(["test_regview"])
)
eq_(
set(insp.get_view_names(include=("materialized",))),
set(["test_mview"]),
)
eq_(set(insp.get_view_names()), set(["test_regview", "test_mview"]))
def test_get_view_names_empty(self):
insp = inspect(testing.db)
assert_raises(ValueError, insp.get_view_names, include=())
def test_get_view_definition(self):
insp = inspect(testing.db)
eq_(
re.sub(
r"[\n\t ]+",
" ",
insp.get_view_definition("test_mview").strip(),
),
"SELECT testtable.id, testtable.data FROM testtable;",
)
class DomainReflectionTest(fixtures.TestBase, AssertsExecutionResults):
"""Test PostgreSQL domains"""
__only_on__ = "postgresql > 8.3"
__backend__ = True
@classmethod
def setup_class(cls):
con = testing.db.connect()
for ddl in [
'CREATE SCHEMA "SomeSchema"',
"CREATE DOMAIN testdomain INTEGER NOT NULL DEFAULT 42",
"CREATE DOMAIN test_schema.testdomain INTEGER DEFAULT 0",
"CREATE TYPE testtype AS ENUM ('test')",
"CREATE DOMAIN enumdomain AS testtype",
"CREATE DOMAIN arraydomain AS INTEGER[]",
'CREATE DOMAIN "SomeSchema"."Quoted.Domain" INTEGER DEFAULT 0',
]:
try:
con.execute(ddl)
except exc.DBAPIError as e:
if "already exists" not in str(e):
raise e
con.execute(
"CREATE TABLE testtable (question integer, answer " "testdomain)"
)
con.execute(
"CREATE TABLE test_schema.testtable(question "
"integer, answer test_schema.testdomain, anything "
"integer)"
)
con.execute(
"CREATE TABLE crosschema (question integer, answer "
"test_schema.testdomain)"
)
con.execute("CREATE TABLE enum_test (id integer, data enumdomain)")
con.execute("CREATE TABLE array_test (id integer, data arraydomain)")
con.execute(
"CREATE TABLE quote_test "
'(id integer, data "SomeSchema"."Quoted.Domain")'
)
@classmethod
def teardown_class(cls):
con = testing.db.connect()
con.execute("DROP TABLE testtable")
con.execute("DROP TABLE test_schema.testtable")
con.execute("DROP TABLE crosschema")
con.execute("DROP TABLE quote_test")
con.execute("DROP DOMAIN testdomain")
con.execute("DROP DOMAIN test_schema.testdomain")
con.execute("DROP TABLE enum_test")
con.execute("DROP DOMAIN enumdomain")
con.execute("DROP TYPE testtype")
con.execute("DROP TABLE array_test")
con.execute("DROP DOMAIN arraydomain")
con.execute('DROP DOMAIN "SomeSchema"."Quoted.Domain"')
con.execute('DROP SCHEMA "SomeSchema"')
def test_table_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("testtable", metadata, autoload=True)
eq_(
set(table.columns.keys()),
set(["question", "answer"]),
"Columns of reflected table didn't equal expected columns",
)
assert isinstance(table.c.answer.type, Integer)
def test_domain_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("testtable", metadata, autoload=True)
eq_(
str(table.columns.answer.server_default.arg),
"42",
"Reflected default value didn't equal expected value",
)
assert (
not table.columns.answer.nullable
), "Expected reflected column to not be nullable."
def test_enum_domain_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("enum_test", metadata, autoload=True)
eq_(table.c.data.type.enums, ["test"])
def test_array_domain_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("array_test", metadata, autoload=True)
eq_(table.c.data.type.__class__, ARRAY)
eq_(table.c.data.type.item_type.__class__, INTEGER)
def test_quoted_remote_schema_domain_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("quote_test", metadata, autoload=True)
eq_(table.c.data.type.__class__, INTEGER)
def test_table_is_reflected_test_schema(self):
metadata = MetaData(testing.db)
table = Table(
"testtable", metadata, autoload=True, schema="test_schema"
)
eq_(
set(table.columns.keys()),
set(["question", "answer", "anything"]),
"Columns of reflected table didn't equal expected columns",
)
assert isinstance(table.c.anything.type, Integer)
def test_schema_domain_is_reflected(self):
metadata = MetaData(testing.db)
table = Table(
"testtable", metadata, autoload=True, schema="test_schema"
)
eq_(
str(table.columns.answer.server_default.arg),
"0",
"Reflected default value didn't equal expected value",
)
assert (
table.columns.answer.nullable
), "Expected reflected column to be nullable."
def test_crosschema_domain_is_reflected(self):
metadata = MetaData(testing.db)
table = Table("crosschema", metadata, autoload=True)
eq_(
str(table.columns.answer.server_default.arg),
"0",
"Reflected default value didn't equal expected value",
)
assert (
table.columns.answer.nullable
), "Expected reflected column to be nullable."
def test_unknown_types(self):
from sqlalchemy.databases import postgresql
ischema_names = postgresql.PGDialect.ischema_names
postgresql.PGDialect.ischema_names = {}
try:
m2 = MetaData(testing.db)
assert_raises(exc.SAWarning, Table, "testtable", m2, autoload=True)
@testing.emits_warning("Did not recognize type")
def warns():
m3 = MetaData(testing.db)
t3 = Table("testtable", m3, autoload=True)
assert t3.c.answer.type.__class__ == sa.types.NullType
finally:
postgresql.PGDialect.ischema_names = ischema_names
class ReflectionTest(fixtures.TestBase):
__only_on__ = "postgresql"
__backend__ = True
@testing.fails_if(
"postgresql < 8.4", "Better int2vector functions not available"
)
@testing.provide_metadata
def test_reflected_primary_key_order(self):
meta1 = self.metadata
subject = Table(
"subject",
meta1,
Column("p1", Integer, primary_key=True),
Column("p2", Integer, primary_key=True),
PrimaryKeyConstraint("p2", "p1"),
)
meta1.create_all()
meta2 = MetaData(testing.db)
subject = Table("subject", meta2, autoload=True)
eq_(subject.primary_key.columns.keys(), ["p2", "p1"])
@testing.provide_metadata
def test_pg_weirdchar_reflection(self):
meta1 = self.metadata
subject = Table(
"subject", meta1, Column("id$", Integer, primary_key=True)
)
referer = Table(
"referer",
meta1,
Column("id", Integer, primary_key=True),
Column("ref", Integer, ForeignKey("subject.id$")),
)
meta1.create_all()
meta2 = MetaData(testing.db)
subject = Table("subject", meta2, autoload=True)
referer = Table("referer", meta2, autoload=True)
self.assert_(
(subject.c["id$"] == referer.c.ref).compare(
subject.join(referer).onclause
)
)
@testing.provide_metadata
def test_reflect_default_over_128_chars(self):
Table(
"t",
self.metadata,
Column("x", String(200), server_default="abcd" * 40),
).create(testing.db)
m = MetaData()
t = Table("t", m, autoload=True, autoload_with=testing.db)
eq_(
t.c.x.server_default.arg.text,
"'%s'::character varying" % ("abcd" * 40),
)
@testing.fails_if("postgresql < 8.1", "schema name leaks in, not sure")
@testing.provide_metadata
def test_renamed_sequence_reflection(self):
metadata = self.metadata
Table("t", metadata, Column("id", Integer, primary_key=True))
metadata.create_all()
m2 = MetaData(testing.db)
t2 = Table("t", m2, autoload=True, implicit_returning=False)
eq_(t2.c.id.server_default.arg.text, "nextval('t_id_seq'::regclass)")
r = t2.insert().execute()
eq_(r.inserted_primary_key, [1])
testing.db.connect().execution_options(autocommit=True).execute(
"alter table t_id_seq rename to foobar_id_seq"
)
m3 = MetaData(testing.db)
t3 = Table("t", m3, autoload=True, implicit_returning=False)
eq_(
t3.c.id.server_default.arg.text,
"nextval('foobar_id_seq'::regclass)",
)
r = t3.insert().execute()
eq_(r.inserted_primary_key, [2])
@testing.provide_metadata
def test_altered_type_autoincrement_pk_reflection(self):
metadata = self.metadata
Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
)
metadata.create_all()
testing.db.connect().execution_options(autocommit=True).execute(
"alter table t alter column id type varchar(50)"
)
m2 = MetaData(testing.db)
t2 = Table("t", m2, autoload=True)
eq_(t2.c.id.autoincrement, False)
eq_(t2.c.x.autoincrement, False)
@testing.provide_metadata
def test_renamed_pk_reflection(self):
metadata = self.metadata
Table("t", metadata, Column("id", Integer, primary_key=True))
metadata.create_all()
testing.db.connect().execution_options(autocommit=True).execute(
"alter table t rename id to t_id"
)
m2 = MetaData(testing.db)
t2 = Table("t", m2, autoload=True)
eq_([c.name for c in t2.primary_key], ["t_id"])
@testing.provide_metadata
def test_has_temporary_table(self):
assert not testing.db.has_table("some_temp_table")
user_tmp = Table(
"some_temp_table",
self.metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
prefixes=["TEMPORARY"],
)
user_tmp.create(testing.db)
assert testing.db.has_table("some_temp_table")
@testing.provide_metadata
def test_cross_schema_reflection_one(self):
meta1 = self.metadata
users = Table(
"users",
meta1,
Column("user_id", Integer, primary_key=True),
Column("user_name", String(30), nullable=False),
schema="test_schema",
)
addresses = Table(
"email_addresses",
meta1,
Column("address_id", Integer, primary_key=True),
Column("remote_user_id", Integer, ForeignKey(users.c.user_id)),
Column("email_address", String(20)),
schema="test_schema",
)
meta1.create_all()
meta2 = MetaData(testing.db)
addresses = Table(
"email_addresses", meta2, autoload=True, schema="test_schema"
)
users = Table("users", meta2, mustexist=True, schema="test_schema")
j = join(users, addresses)
self.assert_(
(users.c.user_id == addresses.c.remote_user_id).compare(j.onclause)
)
@testing.provide_metadata
def test_cross_schema_reflection_two(self):
meta1 = self.metadata
subject = Table(
"subject", meta1, Column("id", Integer, primary_key=True)
)
referer = Table(
"referer",
meta1,
Column("id", Integer, primary_key=True),
Column("ref", Integer, ForeignKey("subject.id")),
schema="test_schema",
)
meta1.create_all()
meta2 = MetaData(testing.db)
subject = Table("subject", meta2, autoload=True)
referer = Table("referer", meta2, schema="test_schema", autoload=True)
self.assert_(
(subject.c.id == referer.c.ref).compare(
subject.join(referer).onclause
)
)
@testing.provide_metadata
def test_cross_schema_reflection_three(self):
meta1 = self.metadata
subject = Table(
"subject",
meta1,
Column("id", Integer, primary_key=True),
schema="test_schema_2",
)
referer = Table(
"referer",
meta1,
Column("id", Integer, primary_key=True),
Column("ref", Integer, ForeignKey("test_schema_2.subject.id")),
schema="test_schema",
)
meta1.create_all()
meta2 = MetaData(testing.db)
subject = Table(
"subject", meta2, autoload=True, schema="test_schema_2"
)
referer = Table("referer", meta2, autoload=True, schema="test_schema")
self.assert_(
(subject.c.id == referer.c.ref).compare(
subject.join(referer).onclause
)
)
@testing.provide_metadata
def test_cross_schema_reflection_four(self):
meta1 = self.metadata
subject = Table(
"subject",
meta1,
Column("id", Integer, primary_key=True),
schema="test_schema_2",
)
referer = Table(
"referer",
meta1,
Column("id", Integer, primary_key=True),
Column("ref", Integer, ForeignKey("test_schema_2.subject.id")),
schema="test_schema",
)
meta1.create_all()
conn = testing.db.connect()
conn.detach()
conn.execute("SET search_path TO test_schema, test_schema_2")
meta2 = MetaData(bind=conn)
subject = Table(
"subject",
meta2,
autoload=True,
schema="test_schema_2",
postgresql_ignore_search_path=True,
)
referer = Table(
"referer",
meta2,
autoload=True,
schema="test_schema",
postgresql_ignore_search_path=True,
)
self.assert_(
(subject.c.id == referer.c.ref).compare(
subject.join(referer).onclause
)
)
conn.close()
@testing.provide_metadata
def test_cross_schema_reflection_five(self):
meta1 = self.metadata
# we assume 'public'
default_schema = testing.db.dialect.default_schema_name
subject = Table(
"subject", meta1, Column("id", Integer, primary_key=True)
)
referer = Table(
"referer",
meta1,
Column("id", Integer, primary_key=True),
Column("ref", Integer, ForeignKey("subject.id")),
)
meta1.create_all()
meta2 = MetaData(testing.db)
subject = Table(
"subject",
meta2,
autoload=True,
schema=default_schema,
postgresql_ignore_search_path=True,
)
referer = Table(
"referer",
meta2,
autoload=True,
schema=default_schema,
postgresql_ignore_search_path=True,
)
assert subject.schema == default_schema
self.assert_(
(subject.c.id == referer.c.ref).compare(
subject.join(referer).onclause
)
)
@testing.provide_metadata
def test_cross_schema_reflection_six(self):
# test that the search path *is* taken into account
# by default
meta1 = self.metadata
Table(
"some_table",
meta1,
Column("id", Integer, primary_key=True),
schema="test_schema",
)
Table(
"some_other_table",
meta1,
Column("id", Integer, primary_key=True),
Column("sid", Integer, ForeignKey("test_schema.some_table.id")),
schema="test_schema_2",
)
meta1.create_all()
with testing.db.connect() as conn:
conn.detach()
conn.execute(
"set search_path to test_schema_2, test_schema, public"
)
m1 = MetaData(conn)
Table("some_table", m1, schema="test_schema", autoload=True)
t2_schema = Table(
"some_other_table", m1, schema="test_schema_2", autoload=True
)
t2_no_schema = Table("some_other_table", m1, autoload=True)
t1_no_schema = Table("some_table", m1, autoload=True)
m2 = MetaData(conn)
t1_schema_isp = Table(
"some_table",
m2,
schema="test_schema",
autoload=True,
postgresql_ignore_search_path=True,
)
t2_schema_isp = Table(
"some_other_table",
m2,
schema="test_schema_2",
autoload=True,
postgresql_ignore_search_path=True,
)
# t2_schema refers to t1_schema, but since "test_schema"
# is in the search path, we instead link to t2_no_schema
assert t2_schema.c.sid.references(t1_no_schema.c.id)
# the two no_schema tables refer to each other also.
assert t2_no_schema.c.sid.references(t1_no_schema.c.id)
# but if we're ignoring search path, then we maintain
# those explicit schemas vs. what the "default" schema is
assert t2_schema_isp.c.sid.references(t1_schema_isp.c.id)
@testing.provide_metadata
def test_cross_schema_reflection_seven(self):
# test that the search path *is* taken into account
# by default
meta1 = self.metadata
Table(
"some_table",
meta1,
Column("id", Integer, primary_key=True),
schema="test_schema",
)
Table(
"some_other_table",
meta1,
Column("id", Integer, primary_key=True),
Column("sid", Integer, ForeignKey("test_schema.some_table.id")),
schema="test_schema_2",
)
meta1.create_all()
with testing.db.connect() as conn:
conn.detach()
conn.execute(
"set search_path to test_schema_2, test_schema, public"
)
meta2 = MetaData(conn)
meta2.reflect(schema="test_schema_2")
eq_(
set(meta2.tables),
set(["test_schema_2.some_other_table", "some_table"]),
)
meta3 = MetaData(conn)
meta3.reflect(
schema="test_schema_2", postgresql_ignore_search_path=True
)
eq_(
set(meta3.tables),
set(
[
"test_schema_2.some_other_table",
"test_schema.some_table",
]
),
)
@testing.provide_metadata
def test_cross_schema_reflection_metadata_uses_schema(self):
# test [ticket:3716]
metadata = self.metadata
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("sid", Integer, ForeignKey("some_other_table.id")),
schema="test_schema",
)
Table(
"some_other_table",
metadata,
Column("id", Integer, primary_key=True),
schema=None,
)
metadata.create_all()
with testing.db.connect() as conn:
meta2 = MetaData(conn, schema="test_schema")
meta2.reflect()
eq_(
set(meta2.tables),
set(["some_other_table", "test_schema.some_table"]),
)
@testing.provide_metadata
def test_uppercase_lowercase_table(self):
metadata = self.metadata
a_table = Table("a", metadata, Column("x", Integer))
A_table = Table("A", metadata, Column("x", Integer))
a_table.create()
assert testing.db.has_table("a")
assert not testing.db.has_table("A")
A_table.create(checkfirst=True)
assert testing.db.has_table("A")
def test_uppercase_lowercase_sequence(self):
a_seq = Sequence("a")
A_seq = Sequence("A")
a_seq.create(testing.db)
assert testing.db.dialect.has_sequence(testing.db, "a")
assert not testing.db.dialect.has_sequence(testing.db, "A")
A_seq.create(testing.db, checkfirst=True)
assert testing.db.dialect.has_sequence(testing.db, "A")
a_seq.drop(testing.db)
A_seq.drop(testing.db)
@testing.provide_metadata
def test_index_reflection(self):
"""Reflecting partial & expression-based indexes should warn"""
metadata = self.metadata
Table(
"party",
metadata,
Column("id", String(10), nullable=False),
Column("name", String(20), index=True),
Column("aname", String(20)),
)
metadata.create_all()
testing.db.execute(
"""
create index idx1 on party ((id || name))
"""
)
testing.db.execute(
"""
create unique index idx2 on party (id) where name = 'test'
"""
)
testing.db.execute(
"""
create index idx3 on party using btree
(lower(name::text), lower(aname::text))
"""
)
def go():
m2 = MetaData(testing.db)
t2 = Table("party", m2, autoload=True)
assert len(t2.indexes) == 2
# Make sure indexes are in the order we expect them in
tmp = [(idx.name, idx) for idx in t2.indexes]
tmp.sort()
r1, r2 = [idx[1] for idx in tmp]
assert r1.name == "idx2"
assert r1.unique is True
assert r2.unique is False
assert [t2.c.id] == r1.columns
assert [t2.c.name] == r2.columns
testing.assert_warnings(
go,
[
"Skipped unsupported reflection of "
"expression-based index idx1",
"Predicate of partial index idx2 ignored during " "reflection",
"Skipped unsupported reflection of "
"expression-based index idx3",
],
)
@testing.fails_if("postgresql < 8.3", "index ordering not supported")
@testing.provide_metadata
def test_index_reflection_with_sorting(self):
"""reflect indexes with sorting options set"""
t1 = Table(
"party",
self.metadata,
Column("id", String(10), nullable=False),
Column("name", String(20)),
Column("aname", String(20)),
)
with testing.db.connect() as conn:
t1.create(conn)
# check ASC, DESC options alone
conn.execute(
"""
create index idx1 on party
(id, name ASC, aname DESC)
"""
)
# check DESC w/ NULLS options
conn.execute(
"""
create index idx2 on party
(name DESC NULLS FIRST, aname DESC NULLS LAST)
"""
)
# check ASC w/ NULLS options
conn.execute(
"""
create index idx3 on party
(name ASC NULLS FIRST, aname ASC NULLS LAST)
"""
)
# reflect data
with testing.db.connect() as conn:
m2 = MetaData(conn)
t2 = Table("party", m2, autoload=True)
eq_(len(t2.indexes), 3)
# Make sure indexes are in the order we expect them in
r1, r2, r3 = sorted(t2.indexes, key=lambda idx: idx.name)
eq_(r1.name, "idx1")
eq_(r2.name, "idx2")
eq_(r3.name, "idx3")
# "ASC NULLS LAST" is implicit default for indexes,
# and "NULLS FIRST" is implicit default for "DESC".
# (https://www.postgresql.org/docs/11/indexes-ordering.html)
def compile_exprs(exprs):
return list(map(str, exprs))
eq_(
compile_exprs([t2.c.id, t2.c.name, t2.c.aname.desc()]),
compile_exprs(r1.expressions),
)
eq_(
compile_exprs([t2.c.name.desc(), t2.c.aname.desc().nullslast()]),
compile_exprs(r2.expressions),
)
eq_(
compile_exprs([t2.c.name.nullsfirst(), t2.c.aname]),
compile_exprs(r3.expressions),
)
@testing.provide_metadata
def test_index_reflection_modified(self):
"""reflect indexes when a column name has changed - PG 9
does not update the name of the column in the index def.
[ticket:2141]
"""
metadata = self.metadata
Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
)
metadata.create_all()
conn = testing.db.connect().execution_options(autocommit=True)
conn.execute("CREATE INDEX idx1 ON t (x)")
conn.execute("ALTER TABLE t RENAME COLUMN x to y")
ind = testing.db.dialect.get_indexes(conn, "t", None)
eq_(ind, [{"unique": False, "column_names": ["y"], "name": "idx1"}])
conn.close()
@testing.fails_if("postgresql < 8.2", "reloptions not supported")
@testing.provide_metadata
def test_index_reflection_with_storage_options(self):
"""reflect indexes with storage options set"""
metadata = self.metadata
Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
)
metadata.create_all()
with testing.db.connect().execution_options(autocommit=True) as conn:
conn.execute("CREATE INDEX idx1 ON t (x) WITH (fillfactor = 50)")
ind = testing.db.dialect.get_indexes(conn, "t", None)
eq_(
ind,
[
{
"unique": False,
"column_names": ["x"],
"name": "idx1",
"dialect_options": {
"postgresql_with": {"fillfactor": "50"}
},
}
],
)
m = MetaData()
t1 = Table("t", m, autoload_with=conn)
eq_(
list(t1.indexes)[0].dialect_options["postgresql"]["with"],
{"fillfactor": "50"},
)
@testing.provide_metadata
def test_index_reflection_with_access_method(self):
"""reflect indexes with storage options set"""
metadata = self.metadata
Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("x", ARRAY(Integer)),
)
metadata.create_all()
with testing.db.connect().execution_options(autocommit=True) as conn:
conn.execute("CREATE INDEX idx1 ON t USING gin (x)")
ind = testing.db.dialect.get_indexes(conn, "t", None)
eq_(
ind,
[
{
"unique": False,
"column_names": ["x"],
"name": "idx1",
"dialect_options": {"postgresql_using": "gin"},
}
],
)
m = MetaData()
t1 = Table("t", m, autoload_with=conn)
eq_(
list(t1.indexes)[0].dialect_options["postgresql"]["using"],
"gin",
)
@testing.skip_if("postgresql < 11.0", "indnkeyatts not supported")
@testing.provide_metadata
def test_index_reflection_with_include(self):
"""reflect indexes with include set"""
metadata = self.metadata
Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("x", ARRAY(Integer)),
Column("name", String(20)),
)
metadata.create_all()
with testing.db.connect() as conn:
conn.execute("CREATE INDEX idx1 ON t (x) INCLUDE (name)")
# prior to #5205, this would return:
# [{'column_names': ['x', 'name'],
# 'name': 'idx1', 'unique': False}]
with testing.expect_warnings(
"INCLUDE columns for "
"covering index idx1 ignored during reflection"
):
ind = testing.db.dialect.get_indexes(conn, "t", None)
eq_(
ind,
[{"unique": False, "column_names": ["x"], "name": "idx1"}],
)
@testing.provide_metadata
def test_foreign_key_option_inspection(self):
metadata = self.metadata
Table(
"person",
metadata,
Column("id", String(length=32), nullable=False, primary_key=True),
Column(
"company_id",
ForeignKey(
"company.id",
name="person_company_id_fkey",
match="FULL",
onupdate="RESTRICT",
ondelete="RESTRICT",
deferrable=True,
initially="DEFERRED",
),
),
)
Table(
"company",
metadata,
Column("id", String(length=32), nullable=False, primary_key=True),
Column("name", String(length=255)),
Column(
"industry_id",
ForeignKey(
"industry.id",
name="company_industry_id_fkey",
onupdate="CASCADE",
ondelete="CASCADE",
deferrable=False, # PG default
# PG default
initially="IMMEDIATE",
),
),
)
Table(
"industry",
metadata,
Column("id", Integer(), nullable=False, primary_key=True),
Column("name", String(length=255)),
)
fk_ref = {
"person_company_id_fkey": {
"name": "person_company_id_fkey",
"constrained_columns": ["company_id"],
"referred_columns": ["id"],
"referred_table": "company",
"referred_schema": None,
"options": {
"onupdate": "RESTRICT",
"deferrable": True,
"ondelete": "RESTRICT",
"initially": "DEFERRED",
"match": "FULL",
},
},
"company_industry_id_fkey": {
"name": "company_industry_id_fkey",
"constrained_columns": ["industry_id"],
"referred_columns": ["id"],
"referred_table": "industry",
"referred_schema": None,
"options": {
"onupdate": "CASCADE",
"deferrable": None,
"ondelete": "CASCADE",
"initially": None,
"match": None,
},
},
}
metadata.create_all()
inspector = inspect(testing.db)
fks = inspector.get_foreign_keys(
"person"
) + inspector.get_foreign_keys("company")
for fk in fks:
eq_(fk, fk_ref[fk["name"]])
@testing.provide_metadata
def test_inspect_enums_schema(self):
conn = testing.db.connect()
enum_type = postgresql.ENUM(
"sad",
"ok",
"happy",
name="mood",
schema="test_schema",
metadata=self.metadata,
)
enum_type.create(conn)
inspector = reflection.Inspector.from_engine(conn.engine)
eq_(
inspector.get_enums("test_schema"),
[
{
"visible": False,
"name": "mood",
"schema": "test_schema",
"labels": ["sad", "ok", "happy"],
}
],
)
@testing.provide_metadata
def test_inspect_enums(self):
enum_type = postgresql.ENUM(
"cat", "dog", "rat", name="pet", metadata=self.metadata
)
enum_type.create(testing.db)
inspector = reflection.Inspector.from_engine(testing.db)
eq_(
inspector.get_enums(),
[
{
"visible": True,
"labels": ["cat", "dog", "rat"],
"name": "pet",
"schema": "public",
}
],
)
@testing.provide_metadata
def test_inspect_enums_case_sensitive(self):
sa.event.listen(
self.metadata,
"before_create",
sa.DDL('create schema "TestSchema"'),
)
sa.event.listen(
self.metadata,
"after_drop",
sa.DDL('drop schema "TestSchema" cascade'),
)
for enum in "lower_case", "UpperCase", "Name.With.Dot":
for schema in None, "test_schema", "TestSchema":
postgresql.ENUM(
"CapsOne",
"CapsTwo",
name=enum,
schema=schema,
metadata=self.metadata,
)
self.metadata.create_all(testing.db)
inspector = inspect(testing.db)
for schema in None, "test_schema", "TestSchema":
eq_(
sorted(
inspector.get_enums(schema=schema), key=itemgetter("name")
),
[
{
"visible": schema is None,
"labels": ["CapsOne", "CapsTwo"],
"name": "Name.With.Dot",
"schema": "public" if schema is None else schema,
},
{
"visible": schema is None,
"labels": ["CapsOne", "CapsTwo"],
"name": "UpperCase",
"schema": "public" if schema is None else schema,
},
{
"visible": schema is None,
"labels": ["CapsOne", "CapsTwo"],
"name": "lower_case",
"schema": "public" if schema is None else schema,
},
],
)
@testing.provide_metadata
def test_inspect_enums_case_sensitive_from_table(self):
sa.event.listen(
self.metadata,
"before_create",
sa.DDL('create schema "TestSchema"'),
)
sa.event.listen(
self.metadata,
"after_drop",
sa.DDL('drop schema "TestSchema" cascade'),
)
counter = itertools.count()
for enum in "lower_case", "UpperCase", "Name.With.Dot":
for schema in None, "test_schema", "TestSchema":
enum_type = postgresql.ENUM(
"CapsOne",
"CapsTwo",
name=enum,
metadata=self.metadata,
schema=schema,
)
Table(
"t%d" % next(counter),
self.metadata,
Column("q", enum_type),
)
self.metadata.create_all(testing.db)
inspector = inspect(testing.db)
counter = itertools.count()
for enum in "lower_case", "UpperCase", "Name.With.Dot":
for schema in None, "test_schema", "TestSchema":
cols = inspector.get_columns("t%d" % next(counter))
cols[0]["type"] = (
cols[0]["type"].schema,
cols[0]["type"].name,
cols[0]["type"].enums,
)
eq_(
cols,
[
{
"name": "q",
"type": (schema, enum, ["CapsOne", "CapsTwo"]),
"nullable": True,
"default": None,
"autoincrement": False,
"comment": None,
}
],
)
@testing.provide_metadata
def test_inspect_enums_star(self):
enum_type = postgresql.ENUM(
"cat", "dog", "rat", name="pet", metadata=self.metadata
)
schema_enum_type = postgresql.ENUM(
"sad",
"ok",
"happy",
name="mood",
schema="test_schema",
metadata=self.metadata,
)
enum_type.create(testing.db)
schema_enum_type.create(testing.db)
inspector = reflection.Inspector.from_engine(testing.db)
eq_(
inspector.get_enums(),
[
{
"visible": True,
"labels": ["cat", "dog", "rat"],
"name": "pet",
"schema": "public",
}
],
)
eq_(
inspector.get_enums("*"),
[
{
"visible": True,
"labels": ["cat", "dog", "rat"],
"name": "pet",
"schema": "public",
},
{
"visible": False,
"name": "mood",
"schema": "test_schema",
"labels": ["sad", "ok", "happy"],
},
],
)
@testing.provide_metadata
def test_inspect_enum_empty(self):
enum_type = postgresql.ENUM(name="empty", metadata=self.metadata)
enum_type.create(testing.db)
inspector = reflection.Inspector.from_engine(testing.db)
eq_(
inspector.get_enums(),
[
{
"visible": True,
"labels": [],
"name": "empty",
"schema": "public",
}
],
)
@testing.provide_metadata
def test_inspect_enum_empty_from_table(self):
Table(
"t", self.metadata, Column("x", postgresql.ENUM(name="empty"))
).create(testing.db)
t = Table("t", MetaData(testing.db), autoload_with=testing.db)
eq_(t.c.x.type.enums, [])
@testing.provide_metadata
@testing.only_on("postgresql >= 8.5")
def test_reflection_with_unique_constraint(self):
insp = inspect(testing.db)
meta = self.metadata
uc_table = Table(
"pgsql_uc",
meta,
Column("a", String(10)),
UniqueConstraint("a", name="uc_a"),
)
uc_table.create()
# PostgreSQL will create an implicit index for a unique
# constraint. Separately we get both
indexes = set(i["name"] for i in insp.get_indexes("pgsql_uc"))
constraints = set(
i["name"] for i in insp.get_unique_constraints("pgsql_uc")
)
self.assert_("uc_a" in indexes)
self.assert_("uc_a" in constraints)
# reflection corrects for the dupe
reflected = Table("pgsql_uc", MetaData(testing.db), autoload=True)
indexes = set(i.name for i in reflected.indexes)
constraints = set(uc.name for uc in reflected.constraints)
self.assert_("uc_a" not in indexes)
self.assert_("uc_a" in constraints)
@testing.requires.btree_gist
@testing.provide_metadata
def test_reflection_with_exclude_constraint(self):
m = self.metadata
Table(
"t",
m,
Column("id", Integer, primary_key=True),
Column("period", TSRANGE),
ExcludeConstraint(("period", "&&"), name="quarters_period_excl"),
)
m.create_all()
insp = inspect(testing.db)
# PostgreSQL will create an implicit index for an exclude constraint.
# we don't reflect the EXCLUDE yet.
eq_(
insp.get_indexes("t"),
[
{
"unique": False,
"name": "quarters_period_excl",
"duplicates_constraint": "quarters_period_excl",
"dialect_options": {"postgresql_using": "gist"},
"column_names": ["period"],
}
],
)
# reflection corrects for the dupe
reflected = Table("t", MetaData(testing.db), autoload=True)
eq_(set(reflected.indexes), set())
@testing.provide_metadata
def test_reflect_unique_index(self):
insp = inspect(testing.db)
meta = self.metadata
# a unique index OTOH we are able to detect is an index
# and not a unique constraint
uc_table = Table(
"pgsql_uc",
meta,
Column("a", String(10)),
Index("ix_a", "a", unique=True),
)
uc_table.create()
indexes = dict((i["name"], i) for i in insp.get_indexes("pgsql_uc"))
constraints = set(
i["name"] for i in insp.get_unique_constraints("pgsql_uc")
)
self.assert_("ix_a" in indexes)
assert indexes["ix_a"]["unique"]
self.assert_("ix_a" not in constraints)
reflected = Table("pgsql_uc", MetaData(testing.db), autoload=True)
indexes = dict((i.name, i) for i in reflected.indexes)
constraints = set(uc.name for uc in reflected.constraints)
self.assert_("ix_a" in indexes)
assert indexes["ix_a"].unique
self.assert_("ix_a" not in constraints)
@testing.provide_metadata
def test_reflect_check_constraint(self):
meta = self.metadata
udf_create = """\
CREATE OR REPLACE FUNCTION is_positive(
x integer DEFAULT '-1'::integer)
RETURNS boolean
LANGUAGE 'plpgsql'
COST 100
VOLATILE
AS $BODY$BEGIN
RETURN x > 0;
END;$BODY$;
"""
sa.event.listen(meta, "before_create", sa.DDL(udf_create))
sa.event.listen(
meta, "after_drop", sa.DDL("DROP FUNCTION is_positive(integer)")
)
Table(
"pgsql_cc",
meta,
Column("a", Integer()),
Column("b", String),
CheckConstraint("a > 1 AND a < 5", name="cc1"),
CheckConstraint("a = 1 OR (a > 2 AND a < 5)", name="cc2"),
CheckConstraint("is_positive(a)", name="cc3"),
CheckConstraint("b != 'hi\nim a name \nyup\n'", name="cc4"),
)
meta.create_all()
reflected = Table("pgsql_cc", MetaData(), autoload_with=testing.db)
check_constraints = dict(
(uc.name, uc.sqltext.text)
for uc in reflected.constraints
if isinstance(uc, CheckConstraint)
)
eq_(
check_constraints,
{
u"cc1": u"(a > 1) AND (a < 5)",
u"cc2": u"(a = 1) OR ((a > 2) AND (a < 5))",
u"cc3": u"is_positive(a)",
u"cc4": u"(b)::text <> 'hi\nim a name \nyup\n'::text",
},
)
def test_reflect_check_warning(self):
rows = [("some name", "NOTCHECK foobar")]
conn = mock.Mock(
execute=lambda *arg, **kw: mock.MagicMock(
fetchall=lambda: rows, __iter__=lambda self: iter(rows)
)
)
with mock.patch.object(
testing.db.dialect, "get_table_oid", lambda *arg, **kw: 1
):
with testing.expect_warnings(
"Could not parse CHECK constraint text: 'NOTCHECK foobar'"
):
testing.db.dialect.get_check_constraints(conn, "foo")
def test_reflect_extra_newlines(self):
rows = [
("some name", "CHECK (\n(a \nIS\n NOT\n\n NULL\n)\n)"),
("some other name", "CHECK ((b\nIS\nNOT\nNULL))"),
("some CRLF name", "CHECK ((c\r\n\r\nIS\r\nNOT\r\nNULL))"),
("some name", "CHECK (c != 'hi\nim a name\n')"),
]
conn = mock.Mock(
execute=lambda *arg, **kw: mock.MagicMock(
fetchall=lambda: rows, __iter__=lambda self: iter(rows)
)
)
with mock.patch.object(
testing.db.dialect, "get_table_oid", lambda *arg, **kw: 1
):
check_constraints = testing.db.dialect.get_check_constraints(
conn, "foo"
)
eq_(
check_constraints,
[
{
"name": "some name",
"sqltext": "a \nIS\n NOT\n\n NULL\n",
},
{"name": "some other name", "sqltext": "b\nIS\nNOT\nNULL"},
{
"name": "some CRLF name",
"sqltext": "c\r\n\r\nIS\r\nNOT\r\nNULL",
},
{"name": "some name", "sqltext": "c != 'hi\nim a name\n'"},
],
)
def test_reflect_with_not_valid_check_constraint(self):
rows = [("some name", "CHECK ((a IS NOT NULL)) NOT VALID")]
conn = mock.Mock(
execute=lambda *arg, **kw: mock.MagicMock(
fetchall=lambda: rows, __iter__=lambda self: iter(rows)
)
)
with mock.patch.object(
testing.db.dialect, "get_table_oid", lambda *arg, **kw: 1
):
check_constraints = testing.db.dialect.get_check_constraints(
conn, "foo"
)
eq_(
check_constraints,
[
{
"name": "some name",
"sqltext": "a IS NOT NULL",
"dialect_options": {"not_valid": True},
}
],
)
class CustomTypeReflectionTest(fixtures.TestBase):
class CustomType(object):
def __init__(self, arg1=None, arg2=None):
self.arg1 = arg1
self.arg2 = arg2
ischema_names = None
def setup(self):
ischema_names = postgresql.PGDialect.ischema_names
postgresql.PGDialect.ischema_names = ischema_names.copy()
self.ischema_names = ischema_names
def teardown(self):
postgresql.PGDialect.ischema_names = self.ischema_names
self.ischema_names = None
def _assert_reflected(self, dialect):
for sch, args in [
("my_custom_type", (None, None)),
("my_custom_type()", (None, None)),
("my_custom_type(ARG1)", ("ARG1", None)),
("my_custom_type(ARG1, ARG2)", ("ARG1", "ARG2")),
]:
column_info = dialect._get_column_info(
"colname", sch, None, False, {}, {}, "public", None, ""
)
assert isinstance(column_info["type"], self.CustomType)
eq_(column_info["type"].arg1, args[0])
eq_(column_info["type"].arg2, args[1])
def test_clslevel(self):
postgresql.PGDialect.ischema_names["my_custom_type"] = self.CustomType
dialect = postgresql.PGDialect()
self._assert_reflected(dialect)
def test_instancelevel(self):
dialect = postgresql.PGDialect()
dialect.ischema_names = dialect.ischema_names.copy()
dialect.ischema_names["my_custom_type"] = self.CustomType
self._assert_reflected(dialect)
class IntervalReflectionTest(fixtures.TestBase):
__only_on__ = "postgresql"
__backend__ = True
def test_interval_types(self):
for sym in [
"YEAR",
"MONTH",
"DAY",
"HOUR",
"MINUTE",
"SECOND",
"YEAR TO MONTH",
"DAY TO HOUR",
"DAY TO MINUTE",
"DAY TO SECOND",
"HOUR TO MINUTE",
"HOUR TO SECOND",
"MINUTE TO SECOND",
]:
self._test_interval_symbol(sym)
@testing.provide_metadata
def _test_interval_symbol(self, sym):
t = Table(
"i_test",
self.metadata,
Column("id", Integer, primary_key=True),
Column("data1", INTERVAL(fields=sym)),
)
t.create(testing.db)
columns = {
rec["name"]: rec
for rec in inspect(testing.db).get_columns("i_test")
}
assert isinstance(columns["data1"]["type"], INTERVAL)
eq_(columns["data1"]["type"].fields, sym.lower())
eq_(columns["data1"]["type"].precision, None)
@testing.provide_metadata
def test_interval_precision(self):
t = Table(
"i_test",
self.metadata,
Column("id", Integer, primary_key=True),
Column("data1", INTERVAL(precision=6)),
)
t.create(testing.db)
columns = {
rec["name"]: rec
for rec in inspect(testing.db).get_columns("i_test")
}
assert isinstance(columns["data1"]["type"], INTERVAL)
eq_(columns["data1"]["type"].fields, None)
eq_(columns["data1"]["type"].precision, 6)
|