This file is indexed.

/usr/share/pyshared/sqlalchemy/types.py is in python-sqlalchemy 0.7.4-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
# sqlalchemy/types.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

"""defines genericized SQL types, each represented by a subclass of
:class:`~sqlalchemy.types.AbstractType`.  Dialects define further subclasses of these
types.

For more information see the SQLAlchemy documentation on types.

"""
__all__ = [ 'TypeEngine', 'TypeDecorator', 'AbstractType', 'UserDefinedType',
            'INT', 'CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR','TEXT', 'Text',
            'FLOAT', 'NUMERIC', 'REAL', 'DECIMAL', 'TIMESTAMP', 'DATETIME', 
            'CLOB', 'BLOB', 'BOOLEAN', 'SMALLINT', 'INTEGER', 'DATE', 'TIME',
            'String', 'Integer', 'SmallInteger', 'BigInteger', 'Numeric',
            'Float', 'DateTime', 'Date', 'Time', 'LargeBinary', 'Binary',
            'Boolean', 'Unicode', 'MutableType', 'Concatenable',
            'UnicodeText','PickleType', 'Interval', 'Enum' ]

import inspect
import datetime as dt
import codecs

from sqlalchemy import exc, schema
from sqlalchemy.sql import expression, operators
from sqlalchemy.util import pickle
from sqlalchemy.util.compat import decimal
from sqlalchemy.sql.visitors import Visitable
from sqlalchemy import util
from sqlalchemy import processors, events, event
import collections
default = util.importlater("sqlalchemy.engine", "default")

NoneType = type(None)
if util.jython:
    import array

class AbstractType(Visitable):
    """Base for all types - not needed except for backwards 
    compatibility."""

class TypeEngine(AbstractType):
    """Base for built-in types."""

    def copy_value(self, value):
        return value

    def bind_processor(self, dialect):
        """Return a conversion function for processing bind values.

        Returns a callable which will receive a bind parameter value
        as the sole positional argument and will return a value to
        send to the DB-API.

        If processing is not necessary, the method should return ``None``.

        :param dialect: Dialect instance in use.

        """
        return None

    def result_processor(self, dialect, coltype):
        """Return a conversion function for processing result row values.

        Returns a callable which will receive a result row column
        value as the sole positional argument and will return a value
        to return to the user.

        If processing is not necessary, the method should return ``None``.

        :param dialect: Dialect instance in use.

        :param coltype: DBAPI coltype argument received in cursor.description.

        """
        return None

    def compare_values(self, x, y):
        """Compare two values for equality."""

        return x == y

    def is_mutable(self):
        """Return True if the target Python type is 'mutable'.

        This allows systems like the ORM to know if a column value can
        be considered 'not changed' by comparing the identity of
        objects alone.  Values such as dicts, lists which
        are serialized into strings are examples of "mutable" 
        column structures.

        .. note:: This functionality is now superseded by the
          ``sqlalchemy.ext.mutable`` extension described in 
          :ref:`mutable_toplevel`.

        When this method is overridden, :meth:`copy_value` should
        also be supplied.   The :class:`.MutableType` mixin
        is recommended as a helper.

        """
        return False

    def get_dbapi_type(self, dbapi):
        """Return the corresponding type object from the underlying DB-API, if
        any.

         This can be useful for calling ``setinputsizes()``, for example.

        """
        return None

    @property
    def python_type(self):
        """Return the Python type object expected to be returned
        by instances of this type, if known.   
        
        Basically, for those types which enforce a return type,
        or are known across the board to do such for all common 
        DBAPIs (like ``int`` for example), will return that type.
        
        If a return type is not defined, raises
        ``NotImplementedError``.
        
        Note that any type also accommodates NULL in SQL which
        means you can also get back ``None`` from any type
        in practice.

        """
        raise NotImplementedError()

    def with_variant(self, type_, dialect_name):
        """Produce a new type object that will utilize the given 
        type when applied to the dialect of the given name.

        e.g.::

            from sqlalchemy.types import String
            from sqlalchemy.dialects import mysql

            s = String()

            s = s.with_variant(mysql.VARCHAR(collation='foo'), 'mysql')

        The construction of :meth:`.TypeEngine.with_variant` is always
        from the "fallback" type to that which is dialect specific.
        The returned type is an instance of :class:`.Variant`, which
        itself provides a :meth:`~sqlalchemy.types.Variant.with_variant` that can 
        be called repeatedly.

        :param type_: a :class:`.TypeEngine` that will be selected
         as a variant from the originating type, when a dialect
         of the given name is in use.
        :param dialect_name: base name of the dialect which uses 
         this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)

        New in 0.7.2.

        """
        return Variant(self, {dialect_name:type_})

    def _adapt_expression(self, op, othertype):
        """evaluate the return type of <self> <op> <othertype>,
        and apply any adaptations to the given operator.

        """
        return op, self

    @util.memoized_property
    def _type_affinity(self):
        """Return a rudimental 'affinity' value expressing the general class
        of type."""

        typ = None
        for t in self.__class__.__mro__:
            if t is TypeEngine or t is UserDefinedType:
                return typ
            elif issubclass(t, TypeEngine):
                typ = t
        else:
            return self.__class__

    def dialect_impl(self, dialect):
        """Return a dialect-specific implementation for this :class:`.TypeEngine`."""

        try:
            return dialect._type_memos[self]['impl']
        except KeyError:
            return self._dialect_info(dialect)['impl']

    def _cached_bind_processor(self, dialect):
        """Return a dialect-specific bind processor for this type."""

        try:
            return dialect._type_memos[self]['bind']
        except KeyError:
            d = self._dialect_info(dialect)
            d['bind'] = bp = d['impl'].bind_processor(dialect)
            return bp

    def _cached_result_processor(self, dialect, coltype):
        """Return a dialect-specific result processor for this type."""

        try:
            return dialect._type_memos[self][coltype]
        except KeyError:
            d = self._dialect_info(dialect)
            # key assumption: DBAPI type codes are
            # constants.  Else this dictionary would
            # grow unbounded.
            d[coltype] = rp = d['impl'].result_processor(dialect, coltype)
            return rp

    def _dialect_info(self, dialect):
        """Return a dialect-specific registry which 
        caches a dialect-specific implementation, bind processing
        function, and one or more result processing functions."""

        if self in dialect._type_memos:
            return dialect._type_memos[self]
        else:
            impl = self._gen_dialect_impl(dialect)
            if impl is self:
                impl = self.adapt(type(self))
            # this can't be self, else we create a cycle
            assert impl is not self
            dialect._type_memos[self] = d = {'impl':impl}
            return d

    def _gen_dialect_impl(self, dialect):
        return dialect.type_descriptor(self)

    def adapt(self, cls, **kw):
        """Produce an "adapted" form of this type, given an "impl" class 
        to work with. 

        This method is used internally to associate generic 
        types with "implementation" types that are specific to a particular
        dialect.
        """
        return util.constructor_copy(self, cls, **kw)

    def _coerce_compared_value(self, op, value):
        """Suggest a type for a 'coerced' Python value in an expression.

        Given an operator and value, gives the type a chance
        to return a type which the value should be coerced into.

        The default behavior here is conservative; if the right-hand
        side is already coerced into a SQL type based on its 
        Python type, it is usually left alone.

        End-user functionality extension here should generally be via
        :class:`.TypeDecorator`, which provides more liberal behavior in that
        it defaults to coercing the other side of the expression into this
        type, thus applying special Python conversions above and beyond those
        needed by the DBAPI to both ides. It also provides the public method
        :meth:`.TypeDecorator.coerce_compared_value` which is intended for
        end-user customization of this behavior.

        """
        _coerced_type = _type_map.get(type(value), NULLTYPE)
        if _coerced_type is NULLTYPE or _coerced_type._type_affinity \
            is self._type_affinity:
            return self
        else:
            return _coerced_type

    def _compare_type_affinity(self, other):
        return self._type_affinity is other._type_affinity

    def compile(self, dialect=None):
        """Produce a string-compiled form of this :class:`.TypeEngine`.

        When called with no arguments, uses a "default" dialect
        to produce a string result.

        :param dialect: a :class:`.Dialect` instance.

        """
        # arg, return value is inconsistent with
        # ClauseElement.compile()....this is a mistake.

        if not dialect:
            dialect = self._default_dialect

        return dialect.type_compiler.process(self)

    @property
    def _default_dialect(self):
        if self.__class__.__module__.startswith("sqlalchemy.dialects"):
            tokens = self.__class__.__module__.split(".")[0:3]
            mod = ".".join(tokens)
            return getattr(__import__(mod).dialects, tokens[-1]).dialect()
        else:
            return default.DefaultDialect()

    def __str__(self):
        # Py3K
        #return unicode(self.compile())
        # Py2K
        return unicode(self.compile()).\
                        encode('ascii', 'backslashreplace')
        # end Py2K

    def __init__(self, *args, **kwargs):
        """Support implementations that were passing arguments"""
        if args or kwargs:
            util.warn_deprecated("Passing arguments to type object "
                    "constructor %s is deprecated" % self.__class__)

    def __repr__(self):
        return util.generic_repr(self)

class UserDefinedType(TypeEngine):
    """Base for user defined types.

    This should be the base of new types.  Note that
    for most cases, :class:`.TypeDecorator` is probably
    more appropriate::

      import sqlalchemy.types as types

      class MyType(types.UserDefinedType):
          def __init__(self, precision = 8):
              self.precision = precision

          def get_col_spec(self):
              return "MYTYPE(%s)" % self.precision

          def bind_processor(self, dialect):
              def process(value):
                  return value
              return process

          def result_processor(self, dialect, coltype):
              def process(value):
                  return value
              return process

    Once the type is made, it's immediately usable::

      table = Table('foo', meta,
          Column('id', Integer, primary_key=True),
          Column('data', MyType(16))
          )

    """
    __visit_name__ = "user_defined"

    def _adapt_expression(self, op, othertype):
        """evaluate the return type of <self> <op> <othertype>,
        and apply any adaptations to the given operator.

        """
        return self.adapt_operator(op), self

    def adapt_operator(self, op):
        """A hook which allows the given operator to be adapted
        to something new. 

        See also UserDefinedType._adapt_expression(), an as-yet-
        semi-public method with greater capability in this regard.

        """
        return op

class TypeDecorator(TypeEngine):
    """Allows the creation of types which add additional functionality
    to an existing type.

    This method is preferred to direct subclassing of SQLAlchemy's
    built-in types as it ensures that all required functionality of 
    the underlying type is kept in place.

    Typical usage::

      import sqlalchemy.types as types

      class MyType(types.TypeDecorator):
          '''Prefixes Unicode values with "PREFIX:" on the way in and
          strips it off on the way out.
          '''

          impl = types.Unicode

          def process_bind_param(self, value, dialect):
              return "PREFIX:" + value

          def process_result_value(self, value, dialect):
              return value[7:]

          def copy(self):
              return MyType(self.impl.length)

    The class-level "impl" variable is required, and can reference any
    TypeEngine class.  Alternatively, the load_dialect_impl() method
    can be used to provide different type classes based on the dialect
    given; in this case, the "impl" variable can reference
    ``TypeEngine`` as a placeholder.

    Types that receive a Python type that isn't similar to the ultimate type
    used may want to define the :meth:`TypeDecorator.coerce_compared_value`
    method. This is used to give the expression system a hint when coercing
    Python objects into bind parameters within expressions. Consider this
    expression::

        mytable.c.somecol + datetime.date(2009, 5, 15)

    Above, if "somecol" is an ``Integer`` variant, it makes sense that 
    we're doing date arithmetic, where above is usually interpreted
    by databases as adding a number of days to the given date. 
    The expression system does the right thing by not attempting to
    coerce the "date()" value into an integer-oriented bind parameter.

    However, in the case of ``TypeDecorator``, we are usually changing an
    incoming Python type to something new - ``TypeDecorator`` by default will
    "coerce" the non-typed side to be the same type as itself. Such as below,
    we define an "epoch" type that stores a date value as an integer::

        class MyEpochType(types.TypeDecorator):
            impl = types.Integer

            epoch = datetime.date(1970, 1, 1)

            def process_bind_param(self, value, dialect):
                return (value - self.epoch).days

            def process_result_value(self, value, dialect):
                return self.epoch + timedelta(days=value)

    Our expression of ``somecol + date`` with the above type will coerce the
    "date" on the right side to also be treated as ``MyEpochType``.

    This behavior can be overridden via the
    :meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
    that should be used for the value of the expression. Below we set it such
    that an integer value will be treated as an ``Integer``, and any other
    value is assumed to be a date and will be treated as a ``MyEpochType``::

        def coerce_compared_value(self, op, value):
            if isinstance(value, int):
                return Integer()
            else:
                return self

    """

    __visit_name__ = "type_decorator"

    def __init__(self, *args, **kwargs):
        """Construct a :class:`.TypeDecorator`.

        Arguments sent here are passed to the constructor 
        of the class assigned to the ``impl`` class level attribute,
        where the ``self.impl`` attribute is assigned an instance
        of the implementation type.  If ``impl`` at the class level
        is already an instance, then it's assigned to ``self.impl``
        as is.

        Subclasses can override this to customize the generation
        of ``self.impl``.

        """
        if not hasattr(self.__class__, 'impl'):
            raise AssertionError("TypeDecorator implementations "
                                 "require a class-level variable "
                                 "'impl' which refers to the class of "
                                 "type being decorated")
        self.impl = to_instance(self.__class__.impl, *args, **kwargs)


    def _gen_dialect_impl(self, dialect):
        adapted = dialect.type_descriptor(self)
        if adapted is not self:
            return adapted

        # otherwise adapt the impl type, link
        # to a copy of this TypeDecorator and return
        # that.
        typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
        tt = self.copy()
        if not isinstance(tt, self.__class__):
            raise AssertionError('Type object %s does not properly '
                                 'implement the copy() method, it must '
                                 'return an object of type %s' % (self,
                                 self.__class__))
        tt.impl = typedesc
        return tt

    @property
    def _type_affinity(self):
        return self.impl._type_affinity

    def type_engine(self, dialect):
        """Return a dialect-specific :class:`.TypeEngine` instance for this :class:`.TypeDecorator`.

        In most cases this returns a dialect-adapted form of
        the :class:`.TypeEngine` type represented by ``self.impl``.
        Makes usage of :meth:`dialect_impl` but also traverses
        into wrapped :class:`.TypeDecorator` instances.
        Behavior can be customized here by overriding :meth:`load_dialect_impl`.

        """
        adapted = dialect.type_descriptor(self)
        if type(adapted) is not type(self):
            return adapted
        elif isinstance(self.impl, TypeDecorator):
            return self.impl.type_engine(dialect)
        else:
            return self.load_dialect_impl(dialect)

    def load_dialect_impl(self, dialect):
        """Return a :class:`.TypeEngine` object corresponding to a dialect.

        This is an end-user override hook that can be used to provide
        differing types depending on the given dialect.  It is used
        by the :class:`.TypeDecorator` implementation of :meth:`type_engine` 
        to help determine what type should ultimately be returned
        for a given :class:`.TypeDecorator`.

        By default returns ``self.impl``.

        """
        return self.impl

    def __getattr__(self, key):
        """Proxy all other undefined accessors to the underlying
        implementation."""

        return getattr(self.impl, key)

    def process_bind_param(self, value, dialect):
        """Receive a bound parameter value to be converted.

        Subclasses override this method to return the
        value that should be passed along to the underlying
        :class:`.TypeEngine` object, and from there to the 
        DBAPI ``execute()`` method.

        :param value: the value.  Can be None.
        :param dialect: the :class:`.Dialect` in use.

        """
        raise NotImplementedError()

    def process_result_value(self, value, dialect):
        """Receive a result-row column value to be converted.

        Subclasses override this method to return the
        value that should be passed back to the application,
        given a value that is already processed by
        the underlying :class:`.TypeEngine` object, originally
        from the DBAPI cursor method ``fetchone()`` or similar.

        :param value: the value.  Can be None.
        :param dialect: the :class:`.Dialect` in use.

        """
        raise NotImplementedError()

    def bind_processor(self, dialect):
        """Provide a bound value processing function for the given :class:`.Dialect`.

        This is the method that fulfills the :class:`.TypeEngine` 
        contract for bound value conversion.   :class:`.TypeDecorator`
        will wrap a user-defined implementation of 
        :meth:`process_bind_param` here.

        User-defined code can override this method directly,
        though its likely best to use :meth:`process_bind_param` so that
        the processing provided by ``self.impl`` is maintained.

        """
        if self.__class__.process_bind_param.func_code \
            is not TypeDecorator.process_bind_param.func_code:
            process_param = self.process_bind_param
            impl_processor = self.impl.bind_processor(dialect)
            if impl_processor:
                def process(value):
                    return impl_processor(process_param(value, dialect))

            else:
                def process(value):
                    return process_param(value, dialect)

            return process
        else:
            return self.impl.bind_processor(dialect)

    def result_processor(self, dialect, coltype):
        """Provide a result value processing function for the given :class:`.Dialect`.

        This is the method that fulfills the :class:`.TypeEngine` 
        contract for result value conversion.   :class:`.TypeDecorator`
        will wrap a user-defined implementation of 
        :meth:`process_result_value` here.

        User-defined code can override this method directly,
        though its likely best to use :meth:`process_result_value` so that
        the processing provided by ``self.impl`` is maintained.

        """
        if self.__class__.process_result_value.func_code \
            is not TypeDecorator.process_result_value.func_code:
            process_value = self.process_result_value
            impl_processor = self.impl.result_processor(dialect,
                    coltype)
            if impl_processor:
                def process(value):
                    return process_value(impl_processor(value), dialect)

            else:
                def process(value):
                    return process_value(value, dialect)

            return process
        else:
            return self.impl.result_processor(dialect, coltype)

    def coerce_compared_value(self, op, value):
        """Suggest a type for a 'coerced' Python value in an expression.

        By default, returns self.   This method is called by
        the expression system when an object using this type is 
        on the left or right side of an expression against a plain Python
        object which does not yet have a SQLAlchemy type assigned::

            expr = table.c.somecolumn + 35

        Where above, if ``somecolumn`` uses this type, this method will
        be called with the value ``operator.add``
        and ``35``.  The return value is whatever SQLAlchemy type should
        be used for ``35`` for this particular operation.

        """
        return self

    def _coerce_compared_value(self, op, value):
        """See :meth:`.TypeEngine._coerce_compared_value` for a description."""

        return self.coerce_compared_value(op, value)

    def copy(self):
        """Produce a copy of this :class:`.TypeDecorator` instance.

        This is a shallow copy and is provided to fulfill part of 
        the :class:`.TypeEngine` contract.  It usually does not
        need to be overridden unless the user-defined :class:`.TypeDecorator`
        has local state that should be deep-copied.

        """
        instance = self.__class__.__new__(self.__class__)
        instance.__dict__.update(self.__dict__)
        return instance

    def get_dbapi_type(self, dbapi):
        """Return the DBAPI type object represented by this :class:`.TypeDecorator`.

        By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the 
        underlying "impl".
        """
        return self.impl.get_dbapi_type(dbapi)

    def copy_value(self, value):
        """Given a value, produce a copy of it.

        By default this calls upon :meth:`.TypeEngine.copy_value` 
        of the underlying "impl".

        :meth:`.copy_value` will return the object
        itself, assuming "mutability" is not enabled.
        Only the :class:`.MutableType` mixin provides a copy 
        function that actually produces a new object.
        The copying function is used by the ORM when
        "mutable" types are used, to memoize the original
        version of an object as loaded from the database,
        which is then compared to the possibly mutated
        version to check for changes.

        Modern implementations should use the 
        ``sqlalchemy.ext.mutable`` extension described in
        :ref:`mutable_toplevel` for intercepting in-place
        changes to values.

        """
        return self.impl.copy_value(value)

    def compare_values(self, x, y):
        """Given two values, compare them for equality.

        By default this calls upon :meth:`.TypeEngine.compare_values` 
        of the underlying "impl", which in turn usually
        uses the Python equals operator ``==``.

        This function is used by the ORM to compare
        an original-loaded value with an intercepted
        "changed" value, to determine if a net change
        has occurred.

        """
        return self.impl.compare_values(x, y)

    def is_mutable(self):
        """Return True if the target Python type is 'mutable'.

        This allows systems like the ORM to know if a column value can
        be considered 'not changed' by comparing the identity of
        objects alone.  Values such as dicts, lists which
        are serialized into strings are examples of "mutable" 
        column structures.

        .. note:: This functionality is now superseded by the
          ``sqlalchemy.ext.mutable`` extension described in 
          :ref:`mutable_toplevel`.

        """
        return self.impl.is_mutable()

    def _adapt_expression(self, op, othertype):
        op, typ =self.impl._adapt_expression(op, othertype)
        if typ is self.impl:
            return op, self
        else:
            return op, typ

class Variant(TypeDecorator):
    """A wrapping type that selects among a variety of
    implementations based on dialect in use.
    
    The :class:`.Variant` type is typically constructed
    using the :meth:`.TypeEngine.with_variant` method.
    
    New in 0.7.2.
    
    """

    def __init__(self, base, mapping):
        """Construct a new :class:`.Variant`.
        
        :param base: the base 'fallback' type
        :param mapping: dictionary of string dialect names to :class:`.TypeEngine` 
         instances.
         
        """
        self.impl = base
        self.mapping = mapping

    def load_dialect_impl(self, dialect):
        if dialect.name in self.mapping:
            return self.mapping[dialect.name]
        else:
            return self.impl

    def with_variant(self, type_, dialect_name):
        """Return a new :class:`.Variant` which adds the given
        type + dialect name to the mapping, in addition to the 
        mapping present in this :class:`.Variant`.
        
        :param type_: a :class:`.TypeEngine` that will be selected
         as a variant from the originating type, when a dialect
         of the given name is in use.
        :param dialect_name: base name of the dialect which uses 
         this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)

        New in 0.7.2.
        
        """

        if dialect_name in self.mapping:
            raise exc.ArgumentError(
                "Dialect '%s' is already present in "
                "the mapping for this Variant" % dialect_name)
        mapping = self.mapping.copy()
        mapping[dialect_name] = type_
        return Variant(self.impl, mapping)

class MutableType(object):
    """A mixin that marks a :class:`.TypeEngine` as representing
    a mutable Python object type.   This functionality is used
    only by the ORM.

    .. note:: :class:`.MutableType` is superseded as of SQLAlchemy 0.7
       by the ``sqlalchemy.ext.mutable`` extension described in
       :ref:`mutable_toplevel`.   This extension provides an event
       driven approach to in-place mutation detection that does not
       incur the severe performance penalty of the :class:`.MutableType`
       approach.

    "mutable" means that changes can occur in place to a value 
    of this type.   Examples includes Python lists, dictionaries,
    and sets, as well as user-defined objects.  The primary
    need for identification of "mutable" types is by the ORM, 
    which applies special rules to such values in order to guarantee 
    that changes are detected.  These rules may have a significant 
    performance impact, described below.

    A :class:`.MutableType` usually allows a flag called
    ``mutable=False`` to enable/disable the "mutability" flag,
    represented on this class by :meth:`is_mutable`.  Examples 
    include :class:`.PickleType` and 
    :class:`~sqlalchemy.dialects.postgresql.base.ARRAY`.  Setting
    this flag to ``True`` enables mutability-specific behavior
    by the ORM.

    The :meth:`copy_value` and :meth:`compare_values` functions
    represent a copy and compare function for values of this
    type - implementing subclasses should override these
    appropriately.

    .. warning:: The usage of mutable types has significant performance
        implications when using the ORM. In order to detect changes, the
        ORM must create a copy of the value when it is first
        accessed, so that changes to the current value can be compared
        against the "clean" database-loaded value. Additionally, when the
        ORM checks to see if any data requires flushing, it must scan
        through all instances in the session which are known to have
        "mutable" attributes and compare the current value of each
        one to its "clean"
        value. So for example, if the Session contains 6000 objects (a
        fairly large amount) and autoflush is enabled, every individual
        execution of :class:`.Query` will require a full scan of that subset of
        the 6000 objects that have mutable attributes, possibly resulting
        in tens of thousands of additional method calls for every query.

        As of SQLAlchemy 0.7, the ``sqlalchemy.ext.mutable`` is provided which
        allows an event driven approach to in-place mutation detection. This
        approach should now be favored over the usage of :class:`.MutableType`
        with ``mutable=True``. ``sqlalchemy.ext.mutable`` is described in
        :ref:`mutable_toplevel`.

    """

    def is_mutable(self):
        """Return True if the target Python type is 'mutable'.

        For :class:`.MutableType`, this method is set to 
        return ``True``.

        """
        return True

    def copy_value(self, value):
        """Unimplemented."""
        raise NotImplementedError()

    def compare_values(self, x, y):
        """Compare *x* == *y*."""
        return x == y

def to_instance(typeobj, *arg, **kw):
    if typeobj is None:
        return NULLTYPE

    if util.callable(typeobj):
        return typeobj(*arg, **kw)
    else:
        return typeobj

def adapt_type(typeobj, colspecs):
    if isinstance(typeobj, type):
        typeobj = typeobj()
    for t in typeobj.__class__.__mro__[0:-1]:
        try:
            impltype = colspecs[t]
            break
        except KeyError:
            pass
    else:
        # couldnt adapt - so just return the type itself
        # (it may be a user-defined type)
        return typeobj
    # if we adapted the given generic type to a database-specific type,
    # but it turns out the originally given "generic" type
    # is actually a subclass of our resulting type, then we were already
    # given a more specific type than that required; so use that.
    if (issubclass(typeobj.__class__, impltype)):
        return typeobj
    return typeobj.adapt(impltype)




class NullType(TypeEngine):
    """An unknown type.

    NullTypes will stand in if :class:`~sqlalchemy.Table` reflection
    encounters a column data type unknown to SQLAlchemy.  The
    resulting columns are nearly fully usable: the DB-API adapter will
    handle all translation to and from the database data type.

    NullType does not have sufficient information to particpate in a
    ``CREATE TABLE`` statement and will raise an exception if
    encountered during a :meth:`~sqlalchemy.Table.create` operation.

    """
    __visit_name__ = 'null'

    def _adapt_expression(self, op, othertype):
        if isinstance(othertype, NullType) or not operators.is_commutative(op):
            return op, self
        else:
            return othertype._adapt_expression(op, self)

NullTypeEngine = NullType

class Concatenable(object):
    """A mixin that marks a type as supporting 'concatenation',
    typically strings."""

    def _adapt_expression(self, op, othertype):
        if op is operators.add and issubclass(othertype._type_affinity,
                (Concatenable, NullType)):
            return operators.concat_op, self
        else:
            return op, self

class _DateAffinity(object):
    """Mixin date/time specific expression adaptations.

    Rules are implemented within Date,Time,Interval,DateTime, Numeric,
    Integer. Based on http://www.postgresql.org/docs/current/static
    /functions-datetime.html.

    """

    @property
    def _expression_adaptations(self):
        raise NotImplementedError()

    _blank_dict = util.immutabledict()
    def _adapt_expression(self, op, othertype):
        othertype = othertype._type_affinity
        return op, \
                self._expression_adaptations.get(op, self._blank_dict).\
                get(othertype, NULLTYPE)

class String(Concatenable, TypeEngine):
    """The base for all string and character types.

    In SQL, corresponds to VARCHAR.  Can also take Python unicode objects
    and encode to the database's encoding in bind params (and the reverse for
    result sets.)

    The `length` field is usually required when the `String` type is
    used within a CREATE TABLE statement, as VARCHAR requires a length
    on most databases.

    """

    __visit_name__ = 'string'

    def __init__(self, length=None, convert_unicode=False, 
                        assert_unicode=None, unicode_error=None,
                        _warn_on_bytestring=False
                        ):
        """
        Create a string-holding type.

        :param length: optional, a length for the column for use in
          DDL statements.  May be safely omitted if no ``CREATE
          TABLE`` will be issued.  Certain databases may require a
          ``length`` for use in DDL, and will raise an exception when
          the ``CREATE TABLE`` DDL is issued if a ``VARCHAR``
          with no length is included.  Whether the value is
          interpreted as bytes or characters is database specific.

        :param convert_unicode: When set to ``True``, the 
          :class:`.String` type will assume that
          input is to be passed as Python ``unicode`` objects,
          and results returned as Python ``unicode`` objects.
          If the DBAPI in use does not support Python unicode
          (which is fewer and fewer these days), SQLAlchemy
          will encode/decode the value, using the 
          value of the ``encoding`` parameter passed to 
          :func:`.create_engine` as the encoding.
          
          When using a DBAPI that natively supports Python
          unicode objects, this flag generally does not 
          need to be set.  For columns that are explicitly
          intended to store non-ASCII data, the :class:`.Unicode`
          or :class:`UnicodeText` 
          types should be used regardless, which feature
          the same behavior of ``convert_unicode`` but 
          also indicate an underlying column type that
          directly supports unicode, such as ``NVARCHAR``.

          For the extremely rare case that Python ``unicode``
          is to be encoded/decoded by SQLAlchemy on a backend
          that does natively support Python ``unicode``,
          the value ``force`` can be passed here which will
          cause SQLAlchemy's encode/decode services to be
          used unconditionally.

        :param assert_unicode: Deprecated.  A warning is emitted 
          when a non-``unicode`` object is passed to the 
          :class:`.Unicode` subtype of :class:`.String`, 
          or the :class:`.UnicodeText` subtype of :class:`.Text`.   
          See :class:`.Unicode` for information on how to 
          control this warning.

        :param unicode_error: Optional, a method to use to handle Unicode
          conversion errors. Behaves like the ``errors`` keyword argument to
          the standard library's ``string.decode()`` functions.   This flag
          requires that ``convert_unicode`` is set to ``force`` - otherwise,
          SQLAlchemy is not guaranteed to handle the task of unicode
          conversion.   Note that this flag adds significant performance
          overhead to row-fetching operations for backends that already
          return unicode objects natively (which most DBAPIs do).  This
          flag should only be used as a last resort for reading
          strings from a column with varied or corrupted encodings.

        """
        if unicode_error is not None and convert_unicode != 'force':
            raise exc.ArgumentError("convert_unicode must be 'force' "
                                        "when unicode_error is set.")

        if assert_unicode:
            util.warn_deprecated('assert_unicode is deprecated. '
                                 'SQLAlchemy emits a warning in all '
                                 'cases where it would otherwise like '
                                 'to encode a Python unicode object '
                                 'into a specific encoding but a plain '
                                 'bytestring is received. This does '
                                 '*not* apply to DBAPIs that coerce '
                                 'Unicode natively.')
        self.length = length
        self.convert_unicode = convert_unicode
        self.unicode_error = unicode_error
        self._warn_on_bytestring = _warn_on_bytestring

    def bind_processor(self, dialect):
        if self.convert_unicode or dialect.convert_unicode:
            if dialect.supports_unicode_binds and \
                self.convert_unicode != 'force':
                if self._warn_on_bytestring:
                    def process(value):
                        # Py3K
                        #if isinstance(value, bytes):
                        # Py2K
                        if isinstance(value, str):
                        # end Py2K
                            util.warn("Unicode type received non-unicode bind "
                                      "param value.")
                        return value
                    return process
                else:
                    return None
            else:
                encoder = codecs.getencoder(dialect.encoding)
                warn_on_bytestring = self._warn_on_bytestring
                def process(value):
                    if isinstance(value, unicode):
                        return encoder(value, self.unicode_error)[0]
                    elif warn_on_bytestring and value is not None:
                        util.warn("Unicode type received non-unicode bind "
                                  "param value")
                    return value
            return process
        else:
            return None

    def result_processor(self, dialect, coltype):
        wants_unicode = self.convert_unicode or dialect.convert_unicode
        needs_convert = wants_unicode and \
                        (dialect.returns_unicode_strings is not True or 
                        self.convert_unicode == 'force')

        if needs_convert:
            to_unicode = processors.to_unicode_processor_factory(
                                    dialect.encoding, self.unicode_error)

            if dialect.returns_unicode_strings:
                # we wouldn't be here unless convert_unicode='force'
                # was specified, or the driver has erratic unicode-returning
                # habits.  since we will be getting back unicode
                # in most cases, we check for it (decode will fail).
                def process(value):
                    if isinstance(value, unicode):
                        return value
                    else:
                        return to_unicode(value)
                return process
            else:
                # here, we assume that the object is not unicode,
                # avoiding expensive isinstance() check.
                return to_unicode
        else:
            return None

    @property
    def python_type(self):
        if self.convert_unicode:
            return unicode
        else:
            return str

    def get_dbapi_type(self, dbapi):
        return dbapi.STRING

class Text(String):
    """A variably sized string type.

    In SQL, usually corresponds to CLOB or TEXT. Can also take Python
    unicode objects and encode to the database's encoding in bind
    params (and the reverse for result sets.)

    """
    __visit_name__ = 'text'

class Unicode(String):
    """A variable length Unicode string type.

    The :class:`.Unicode` type is a :class:`.String` subclass
    that assumes input and output as Python ``unicode`` data,
    and in that regard is equivalent to the usage of the
    ``convert_unicode`` flag with the :class:`.String` type.
    However, unlike plain :class:`.String`, it also implies an 
    underlying column type that is explicitly supporting of non-ASCII
    data, such as ``NVARCHAR`` on Oracle and SQL Server.
    This can impact the output of ``CREATE TABLE`` statements 
    and ``CAST`` functions at the dialect level, and can 
    also affect the handling of bound parameters in some
    specific DBAPI scenarios.
    
    The encoding used by the :class:`.Unicode` type is usually
    determined by the DBAPI itself; most modern DBAPIs 
    feature support for Python ``unicode`` objects as bound
    values and result set values, and the encoding should
    be configured as detailed in the notes for the target
    DBAPI in the :ref:`dialect_toplevel` section.
    
    For those DBAPIs which do not support, or are not configured
    to accommodate Python ``unicode`` objects
    directly, SQLAlchemy does the encoding and decoding
    outside of the DBAPI.   The encoding in this scenario 
    is determined by the ``encoding`` flag passed to 
    :func:`.create_engine`.

    When using the :class:`.Unicode` type, it is only appropriate 
    to pass Python ``unicode`` objects, and not plain ``str``.
    If a plain ``str`` is passed under Python 2, a warning
    is emitted.  If you notice your application emitting these warnings but 
    you're not sure of the source of them, the Python 
    ``warnings`` filter, documented at 
    http://docs.python.org/library/warnings.html, 
    can be used to turn these warnings into exceptions 
    which will illustrate a stack trace::

      import warnings
      warnings.simplefilter('error')

    For an application that wishes to pass plain bytestrings
    and Python ``unicode`` objects to the ``Unicode`` type
    equally, the bytestrings must first be decoded into 
    unicode.  The recipe at :ref:`coerce_to_unicode` illustrates
    how this is done.

    See also:

        :class:`.UnicodeText` - unlengthed textual counterpart
        to :class:`.Unicode`.

    """

    __visit_name__ = 'unicode'

    def __init__(self, length=None, **kwargs):
        """
        Create a :class:`.Unicode` object.
        
        Parameters are the same as that of :class:`.String`,
        with the exception that ``convert_unicode``
        defaults to ``True``.

        """
        kwargs.setdefault('convert_unicode', True)
        kwargs.setdefault('_warn_on_bytestring', True)
        super(Unicode, self).__init__(length=length, **kwargs)

class UnicodeText(Text):
    """An unbounded-length Unicode string type.

    See :class:`.Unicode` for details on the unicode
    behavior of this object.

    Like :class:`.Unicode`, usage the :class:`.UnicodeText` type implies a 
    unicode-capable type being used on the backend, such as 
    ``NCLOB``, ``NTEXT``.

    """

    __visit_name__ = 'unicode_text'

    def __init__(self, length=None, **kwargs):
        """
        Create a Unicode-converting Text type.

        Parameters are the same as that of :class:`.Text`,
        with the exception that ``convert_unicode``
        defaults to ``True``.

        """
        kwargs.setdefault('convert_unicode', True)
        kwargs.setdefault('_warn_on_bytestring', True)
        super(UnicodeText, self).__init__(length=length, **kwargs)


class Integer(_DateAffinity, TypeEngine):
    """A type for ``int`` integers."""

    __visit_name__ = 'integer'

    def get_dbapi_type(self, dbapi):
        return dbapi.NUMBER

    @property
    def python_type(self):
        return int

    @util.memoized_property
    def _expression_adaptations(self):
        # TODO: need a dictionary object that will
        # handle operators generically here, this is incomplete
        return {
            operators.add:{
                Date:Date,
                Integer:Integer,
                Numeric:Numeric,
            },
            operators.mul:{
                Interval:Interval,
                Integer:Integer,
                Numeric:Numeric,
            },
            # Py2K
            operators.div:{
                Integer:Integer,
                Numeric:Numeric,
            },
            # end Py2K
            operators.truediv:{
                Integer:Integer,
                Numeric:Numeric,
            },
            operators.sub:{
                Integer:Integer,
                Numeric:Numeric,
            },
        }

class SmallInteger(Integer):
    """A type for smaller ``int`` integers.

    Typically generates a ``SMALLINT`` in DDL, and otherwise acts like
    a normal :class:`.Integer` on the Python side.

    """

    __visit_name__ = 'small_integer'


class BigInteger(Integer):
    """A type for bigger ``int`` integers.

    Typically generates a ``BIGINT`` in DDL, and otherwise acts like
    a normal :class:`.Integer` on the Python side.

    """

    __visit_name__ = 'big_integer'


class Numeric(_DateAffinity, TypeEngine):
    """A type for fixed precision numbers.

    Typically generates DECIMAL or NUMERIC.  Returns
    ``decimal.Decimal`` objects by default, applying
    conversion as needed.

    .. note:: The `cdecimal <http://pypi.python.org/pypi/cdecimal/>`_ library
       is a high performing alternative to Python's built-in
       ``decimal.Decimal`` type, which performs very poorly in high volume
       situations. SQLAlchemy 0.7 is tested against ``cdecimal`` and supports
       it fully. The type is not necessarily supported by DBAPI
       implementations however, most of which contain an import for plain
       ``decimal`` in their source code, even though some such as psycopg2
       provide hooks for alternate adapters. SQLAlchemy imports ``decimal``
       globally as well. While the alternate ``Decimal`` class can be patched
       into SQLA's ``decimal`` module, overall the most straightforward and
       foolproof way to use "cdecimal" given current DBAPI and Python support
       is to patch it directly into sys.modules before anything else is
       imported::

           import sys
           import cdecimal
           sys.modules["decimal"] = cdecimal

       While the global patch is a little ugly, it's particularly 
       important to use just one decimal library at a time since 
       Python Decimal and cdecimal Decimal objects 
       are not currently compatible *with each other*::

           >>> import cdecimal
           >>> import decimal
           >>> decimal.Decimal("10") == cdecimal.Decimal("10")
           False

       SQLAlchemy will provide more natural support of 
       cdecimal if and when it becomes a standard part of Python
       installations and is supported by all DBAPIs.

    """

    __visit_name__ = 'numeric'

    def __init__(self, precision=None, scale=None, asdecimal=True):
        """
        Construct a Numeric.

        :param precision: the numeric precision for use in DDL ``CREATE
          TABLE``.

        :param scale: the numeric scale for use in DDL ``CREATE TABLE``.

        :param asdecimal: default True.  Return whether or not
          values should be sent as Python Decimal objects, or
          as floats.   Different DBAPIs send one or the other based on
          datatypes - the Numeric type will ensure that return values
          are one or the other across DBAPIs consistently.

        When using the ``Numeric`` type, care should be taken to ensure
        that the asdecimal setting is apppropriate for the DBAPI in use -
        when Numeric applies a conversion from Decimal->float or float->
        Decimal, this conversion incurs an additional performance overhead
        for all result columns received. 

        DBAPIs that return Decimal natively (e.g. psycopg2) will have 
        better accuracy and higher performance with a setting of ``True``,
        as the native translation to Decimal reduces the amount of floating-
        point issues at play, and the Numeric type itself doesn't need
        to apply any further conversions.  However, another DBAPI which 
        returns floats natively *will* incur an additional conversion 
        overhead, and is still subject to floating point data loss - in 
        which case ``asdecimal=False`` will at least remove the extra
        conversion overhead.

        """
        self.precision = precision
        self.scale = scale
        self.asdecimal = asdecimal

    def get_dbapi_type(self, dbapi):
        return dbapi.NUMBER

    @property
    def python_type(self):
        if self.asdecimal:
            return decimal.Decimal
        else:
            return float

    def bind_processor(self, dialect):
        if dialect.supports_native_decimal:
            return None
        else:
            return processors.to_float

    def result_processor(self, dialect, coltype):
        if self.asdecimal:
            if dialect.supports_native_decimal:
                # we're a "numeric", DBAPI will give us Decimal directly
                return None
            else:
                util.warn('Dialect %s+%s does *not* support Decimal '
                          'objects natively, and SQLAlchemy must '
                          'convert from floating point - rounding '
                          'errors and other issues may occur. Please '
                          'consider storing Decimal numbers as strings '
                          'or integers on this platform for lossless '
                          'storage.' % (dialect.name, dialect.driver))

                # we're a "numeric", DBAPI returns floats, convert.
                if self.scale is not None:
                    return processors.to_decimal_processor_factory(
                                decimal.Decimal, self.scale)
                else:
                    return processors.to_decimal_processor_factory(
                                decimal.Decimal)
        else:
            if dialect.supports_native_decimal:
                return processors.to_float
            else:
                return None

    @util.memoized_property
    def _expression_adaptations(self):
        return {
            operators.mul:{
                Interval:Interval,
                Numeric:Numeric,
                Integer:Numeric,
            },
            # Py2K
            operators.div:{
                Numeric:Numeric,
                Integer:Numeric,
            },
            # end Py2K
            operators.truediv:{
                Numeric:Numeric,
                Integer:Numeric,
            },
            operators.add:{
                Numeric:Numeric,
                Integer:Numeric,
            },
            operators.sub:{
                Numeric:Numeric,
                Integer:Numeric,
            }
        }

class Float(Numeric):
    """A type for ``float`` numbers.

    Returns Python ``float`` objects by default, applying
    conversion as needed.

    """

    __visit_name__ = 'float'

    scale = None

    def __init__(self, precision=None, asdecimal=False, **kwargs):
        """
        Construct a Float.

        :param precision: the numeric precision for use in DDL ``CREATE
           TABLE``.

        :param asdecimal: the same flag as that of :class:`.Numeric`, but
          defaults to ``False``.   Note that setting this flag to ``True``
          results in floating point conversion.

        :param \**kwargs: deprecated.  Additional arguments here are ignored
         by the default :class:`.Float` type.  For database specific 
         floats that support additional arguments, see that dialect's 
         documentation for details, such as :class:`sqlalchemy.dialects.mysql.FLOAT`.
         
        """
        self.precision = precision
        self.asdecimal = asdecimal
        if kwargs:
            util.warn_deprecated("Additional keyword arguments "
                                "passed to Float ignored.")

    def result_processor(self, dialect, coltype):
        if self.asdecimal:
            return processors.to_decimal_processor_factory(decimal.Decimal)
        else:
            return None

    @util.memoized_property
    def _expression_adaptations(self):
        return {
            operators.mul:{
                Interval:Interval,
                Numeric:Float,
            },
            # Py2K
            operators.div:{
                Numeric:Float,
            },
            # end Py2K
            operators.truediv:{
                Numeric:Float,
            },
            operators.add:{
                Numeric:Float,
            },
            operators.sub:{
                Numeric:Float,
            }
        }


class DateTime(_DateAffinity, TypeEngine):
    """A type for ``datetime.datetime()`` objects.

    Date and time types return objects from the Python ``datetime``
    module.  Most DBAPIs have built in support for the datetime
    module, with the noted exception of SQLite.  In the case of
    SQLite, date and time types are stored as strings which are then
    converted back to datetime objects when rows are returned.

    """

    __visit_name__ = 'datetime'

    def __init__(self, timezone=False):
        """Construct a new :class:`.DateTime`.
        
        :param timezone: boolean.  If True, and supported by the
        backend, will produce 'TIMESTAMP WITH TIMEZONE'. For backends
        that don't support timezone aware timestamps, has no
        effect.
        
        """
        self.timezone = timezone

    def get_dbapi_type(self, dbapi):
        return dbapi.DATETIME

    @property
    def python_type(self):
        return dt.datetime

    @util.memoized_property
    def _expression_adaptations(self):
        return {
            operators.add:{
                Interval:DateTime,
            },
            operators.sub:{
                Interval:DateTime,
                DateTime:Interval,
            },
        }


class Date(_DateAffinity,TypeEngine):
    """A type for ``datetime.date()`` objects."""

    __visit_name__ = 'date'

    def get_dbapi_type(self, dbapi):
        return dbapi.DATETIME

    @property
    def python_type(self):
        return dt.date

    @util.memoized_property
    def _expression_adaptations(self):
        return {
            operators.add:{
                Integer:Date,
                Interval:DateTime,
                Time:DateTime,
            },
            operators.sub:{
                # date - integer = date
                Integer:Date,

                # date - date = integer.
                Date:Integer,

                Interval:DateTime,

                # date - datetime = interval,
                # this one is not in the PG docs 
                # but works
                DateTime:Interval,
            },
        }


class Time(_DateAffinity,TypeEngine):
    """A type for ``datetime.time()`` objects."""

    __visit_name__ = 'time'

    def __init__(self, timezone=False):
        self.timezone = timezone

    def get_dbapi_type(self, dbapi):
        return dbapi.DATETIME

    @property
    def python_type(self):
        return dt.time

    @util.memoized_property
    def _expression_adaptations(self):
        return {
            operators.add:{
                Date:DateTime,
                Interval:Time
            },
            operators.sub:{
                Time:Interval,
                Interval:Time,
            },
        }


class _Binary(TypeEngine):
    """Define base behavior for binary types."""

    def __init__(self, length=None):
        self.length = length

    @property
    def python_type(self):
        # Py3K
        #return bytes
        # Py2K
        return str
        # end Py2K

    # Python 3 - sqlite3 doesn't need the `Binary` conversion
    # here, though pg8000 does to indicate "bytea"
    def bind_processor(self, dialect):
        DBAPIBinary = dialect.dbapi.Binary
        def process(value):
            x = self
            if value is not None:
                return DBAPIBinary(value)
            else:
                return None
        return process

    # Python 3 has native bytes() type 
    # both sqlite3 and pg8000 seem to return it
    # (i.e. and not 'memoryview')
    # Py2K
    def result_processor(self, dialect, coltype):
        if util.jython:
            def process(value):
                if value is not None:
                    if isinstance(value, array.array):
                        return value.tostring()
                    return str(value)
                else:
                    return None
        else:
            process = processors.to_str
        return process
    # end Py2K

    def _coerce_compared_value(self, op, value):
        """See :meth:`.TypeEngine._coerce_compared_value` for a description."""

        if isinstance(value, basestring):
            return self
        else:
            return super(_Binary, self)._coerce_compared_value(op, value)

    def get_dbapi_type(self, dbapi):
        return dbapi.BINARY

class LargeBinary(_Binary):
    """A type for large binary byte data.

    The Binary type generates BLOB or BYTEA when tables are created,
    and also converts incoming values using the ``Binary`` callable
    provided by each DB-API.

    """

    __visit_name__ = 'large_binary'

    def __init__(self, length=None):
        """
        Construct a LargeBinary type.

        :param length: optional, a length for the column for use in
          DDL statements, for those BLOB types that accept a length
          (i.e. MySQL).  It does *not* produce a small BINARY/VARBINARY
          type - use the BINARY/VARBINARY types specifically for those.
          May be safely omitted if no ``CREATE
          TABLE`` will be issued.  Certain databases may require a
          *length* for use in DDL, and will raise an exception when
          the ``CREATE TABLE`` DDL is issued.

        """
        _Binary.__init__(self, length=length)

class Binary(LargeBinary):
    """Deprecated.  Renamed to LargeBinary."""

    def __init__(self, *arg, **kw):
        util.warn_deprecated('The Binary type has been renamed to '
                             'LargeBinary.')
        LargeBinary.__init__(self, *arg, **kw)

class SchemaType(events.SchemaEventTarget):
    """Mark a type as possibly requiring schema-level DDL for usage.

    Supports types that must be explicitly created/dropped (i.e. PG ENUM type)
    as well as types that are complimented by table or schema level
    constraints, triggers, and other rules.

    :class:`.SchemaType` classes can also be targets for the 
    :meth:`.DDLEvents.before_parent_attach` and :meth:`.DDLEvents.after_parent_attach`
    events, where the events fire off surrounding the association of
    the type object with a parent :class:`.Column`.

    """

    def __init__(self, **kw):
        self.name = kw.pop('name', None)
        self.quote = kw.pop('quote', None)
        self.schema = kw.pop('schema', None)
        self.metadata = kw.pop('metadata', None)
        if self.metadata:
            event.listen(
                self.metadata,
                "before_create",
                util.portable_instancemethod(self._on_metadata_create)
            )
            event.listen(
                self.metadata,
                "after_drop",
                util.portable_instancemethod(self._on_metadata_drop)
            )

    def _set_parent(self, column):
        column._on_table_attach(util.portable_instancemethod(self._set_table))

    def _set_table(self, column, table):
        event.listen(
            table,
            "before_create",
              util.portable_instancemethod(
                    self._on_table_create)
        )
        event.listen(
            table,
            "after_drop",
            util.portable_instancemethod(self._on_table_drop)
        )
        if self.metadata is None:
            # TODO: what's the difference between self.metadata
            # and table.metadata here ?
            event.listen(
                table.metadata,
                "before_create",
                util.portable_instancemethod(self._on_metadata_create)
            )
            event.listen(
                table.metadata,
                "after_drop",
                util.portable_instancemethod(self._on_metadata_drop)
            )

    @property
    def bind(self):
        return self.metadata and self.metadata.bind or None

    def create(self, bind=None, checkfirst=False):
        """Issue CREATE ddl for this type, if applicable."""

        if bind is None:
            bind = schema._bind_or_error(self)
        t = self.dialect_impl(bind.dialect)
        if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
            t.create(bind=bind, checkfirst=checkfirst)

    def drop(self, bind=None, checkfirst=False):
        """Issue DROP ddl for this type, if applicable."""

        if bind is None:
            bind = schema._bind_or_error(self)
        t = self.dialect_impl(bind.dialect)
        if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
            t.drop(bind=bind, checkfirst=checkfirst)

    def _on_table_create(self, target, bind, **kw):
        t = self.dialect_impl(bind.dialect)
        if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
            t._on_table_create(target, bind, **kw)

    def _on_table_drop(self, target, bind, **kw):
        t = self.dialect_impl(bind.dialect)
        if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
            t._on_table_drop(target, bind, **kw)

    def _on_metadata_create(self, target, bind, **kw):
        t = self.dialect_impl(bind.dialect)
        if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
            t._on_metadata_create(target, bind, **kw)

    def _on_metadata_drop(self, target, bind, **kw):
        t = self.dialect_impl(bind.dialect)
        if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
            t._on_metadata_drop(target, bind, **kw)

class Enum(String, SchemaType):
    """Generic Enum Type.

    The Enum type provides a set of possible string values which the 
    column is constrained towards.

    By default, uses the backend's native ENUM type if available, 
    else uses VARCHAR + a CHECK constraint.
    
    See also:
    
        :class:`~.postgresql.ENUM` - PostgreSQL-specific type,
        which has additional functionality.
        
    """

    __visit_name__ = 'enum'

    def __init__(self, *enums, **kw):
        """Construct an enum.

        Keyword arguments which don't apply to a specific backend are ignored
        by that backend.

        :param \*enums: string or unicode enumeration labels. If unicode
           labels are present, the `convert_unicode` flag is auto-enabled.

        :param convert_unicode: Enable unicode-aware bind parameter and
           result-set processing for this Enum's data. This is set
           automatically based on the presence of unicode label strings.

        :param metadata: Associate this type directly with a ``MetaData``
           object. For types that exist on the target database as an
           independent schema construct (Postgresql), this type will be
           created and dropped within ``create_all()`` and ``drop_all()``
           operations. If the type is not associated with any ``MetaData``
           object, it will associate itself with each ``Table`` in which it is
           used, and will be created when any of those individual tables are
           created, after a check is performed for it's existence. The type is
           only dropped when ``drop_all()`` is called for that ``Table``
           object's metadata, however.

        :param name: The name of this type. This is required for Postgresql
           and any future supported database which requires an explicitly
           named type, or an explicitly named constraint in order to generate
           the type and/or a table that uses it.

        :param native_enum: Use the database's native ENUM type when
           available. Defaults to True. When False, uses VARCHAR + check
           constraint for all backends.

        :param schema: Schemaname of this type. For types that exist on the
           target database as an independent schema construct (Postgresql),
           this parameter specifies the named schema in which the type is
           present.

        :param quote: Force quoting to be on or off on the type's name. If
           left as the default of `None`, the usual schema-level "case
           sensitive"/"reserved name" rules are used to determine if this
           type's name should be quoted.

        """
        self.enums = enums
        self.native_enum = kw.pop('native_enum', True)
        convert_unicode= kw.pop('convert_unicode', None)
        if convert_unicode is None:
            for e in enums:
                if isinstance(e, unicode):
                    convert_unicode = True
                    break
            else:
                convert_unicode = False

        if self.enums:
            length =max(len(x) for x in self.enums)
        else:
            length = 0
        String.__init__(self, 
                        length =length,
                        convert_unicode=convert_unicode, 
                        )
        SchemaType.__init__(self, **kw)

    def _should_create_constraint(self, compiler):
        return not self.native_enum or \
                    not compiler.dialect.supports_native_enum

    def _set_table(self, column, table):
        if self.native_enum:
            SchemaType._set_table(self, column, table)


        e = schema.CheckConstraint(
                        column.in_(self.enums),
                        name=self.name,
                        _create_rule=util.portable_instancemethod(
                                        self._should_create_constraint)
                    )
        table.append_constraint(e)

    def adapt(self, impltype, **kw):
        if issubclass(impltype, Enum):
            return impltype(name=self.name, 
                        quote=self.quote, 
                        schema=self.schema, 
                        metadata=self.metadata,
                        convert_unicode=self.convert_unicode,
                        native_enum=self.native_enum,
                        *self.enums,
                        **kw
                        )
        else:
            return super(Enum, self).adapt(impltype, **kw)

class PickleType(MutableType, TypeDecorator):
    """Holds Python objects, which are serialized using pickle.

    PickleType builds upon the Binary type to apply Python's
    ``pickle.dumps()`` to incoming objects, and ``pickle.loads()`` on
    the way out, allowing any pickleable Python object to be stored as
    a serialized binary field.

    """

    impl = LargeBinary

    def __init__(self, protocol=pickle.HIGHEST_PROTOCOL, 
                    pickler=None, mutable=False, comparator=None):
        """
        Construct a PickleType.

        :param protocol: defaults to ``pickle.HIGHEST_PROTOCOL``.

        :param pickler: defaults to cPickle.pickle or pickle.pickle if
          cPickle is not available.  May be any object with
          pickle-compatible ``dumps` and ``loads`` methods.

        :param mutable: defaults to False; implements
          :meth:`AbstractType.is_mutable`.   When ``True``, incoming
          objects will be compared against copies of themselves 
          using the Python "equals" operator, unless the 
          ``comparator`` argument is present.   See
          :class:`.MutableType` for details on "mutable" type
          behavior. (default changed from ``True`` in 
          0.7.0).

          .. note:: This functionality is now superseded by the
             ``sqlalchemy.ext.mutable`` extension described in 
             :ref:`mutable_toplevel`.

        :param comparator: a 2-arg callable predicate used
          to compare values of this type.  If left as ``None``, 
          the Python "equals" operator is used to compare values.

        """
        self.protocol = protocol
        self.pickler = pickler or pickle
        self.mutable = mutable
        self.comparator = comparator
        super(PickleType, self).__init__()

    def __reduce__(self):
        return PickleType, (self.protocol, 
                            None, 
                            self.mutable, 
                            self.comparator)

    def bind_processor(self, dialect):
        impl_processor = self.impl.bind_processor(dialect)
        dumps = self.pickler.dumps
        protocol = self.protocol
        if impl_processor:
            def process(value):
                if value is not None:
                    value = dumps(value, protocol)
                return impl_processor(value)
        else:
            def process(value):
                if value is not None:
                    value = dumps(value, protocol)
                return value
        return process

    def result_processor(self, dialect, coltype):
        impl_processor = self.impl.result_processor(dialect, coltype)
        loads = self.pickler.loads
        if impl_processor:
            def process(value):
                value = impl_processor(value)
                if value is None:
                    return None
                return loads(value)
        else:
            def process(value):
                if value is None:
                    return None
                return loads(value)
        return process

    def copy_value(self, value):
        if self.mutable:
            return self.pickler.loads(
                        self.pickler.dumps(value, self.protocol))
        else:
            return value

    def compare_values(self, x, y):
        if self.comparator:
            return self.comparator(x, y)
        else:
            return x == y

    def is_mutable(self):
        """Return True if the target Python type is 'mutable'.

        When this method is overridden, :meth:`copy_value` should
        also be supplied.   The :class:`.MutableType` mixin
        is recommended as a helper.

        """
        return self.mutable


class Boolean(TypeEngine, SchemaType):
    """A bool datatype.

    Boolean typically uses BOOLEAN or SMALLINT on the DDL side, and on
    the Python side deals in ``True`` or ``False``.

    """

    __visit_name__ = 'boolean'

    def __init__(self, create_constraint=True, name=None):
        """Construct a Boolean.

        :param create_constraint: defaults to True.  If the boolean 
          is generated as an int/smallint, also create a CHECK constraint
          on the table that ensures 1 or 0 as a value.

        :param name: if a CHECK constraint is generated, specify
          the name of the constraint.

        """
        self.create_constraint = create_constraint
        self.name = name

    def _should_create_constraint(self, compiler):
        return not compiler.dialect.supports_native_boolean

    def _set_table(self, column, table):
        if not self.create_constraint:
            return

        e = schema.CheckConstraint(
                        column.in_([0, 1]),
                        name=self.name,
                        _create_rule=util.portable_instancemethod(
                                    self._should_create_constraint)
                    )
        table.append_constraint(e)

    @property
    def python_type(self):
        return bool

    def bind_processor(self, dialect):
        if dialect.supports_native_boolean:
            return None
        else:
            return processors.boolean_to_int

    def result_processor(self, dialect, coltype):
        if dialect.supports_native_boolean:
            return None
        else:
            return processors.int_to_boolean

class Interval(_DateAffinity, TypeDecorator):
    """A type for ``datetime.timedelta()`` objects.

    The Interval type deals with ``datetime.timedelta`` objects.  In
    PostgreSQL, the native ``INTERVAL`` type is used; for others, the
    value is stored as a date which is relative to the "epoch"
    (Jan. 1, 1970).

    Note that the ``Interval`` type does not currently provide date arithmetic
    operations on platforms which do not support interval types natively. Such
    operations usually require transformation of both sides of the expression
    (such as, conversion of both sides into integer epoch values first) which
    currently is a manual procedure (such as via
    :attr:`~sqlalchemy.sql.expression.func`).

    """

    impl = DateTime
    epoch = dt.datetime.utcfromtimestamp(0)

    def __init__(self, native=True, 
                        second_precision=None, 
                        day_precision=None):
        """Construct an Interval object.

        :param native: when True, use the actual
          INTERVAL type provided by the database, if
          supported (currently Postgresql, Oracle).
          Otherwise, represent the interval data as 
          an epoch value regardless.

        :param second_precision: For native interval types
          which support a "fractional seconds precision" parameter,
          i.e. Oracle and Postgresql

        :param day_precision: for native interval types which 
          support a "day precision" parameter, i.e. Oracle.

        """
        super(Interval, self).__init__()
        self.native = native
        self.second_precision = second_precision
        self.day_precision = day_precision

    def adapt(self, cls, **kw):
        if self.native and hasattr(cls, '_adapt_from_generic_interval'):
            return cls._adapt_from_generic_interval(self, **kw)
        else:
            return self.__class__(
                        native=self.native, 
                        second_precision=self.second_precision, 
                        day_precision=self.day_precision,
                        **kw)

    @property
    def python_type(self):
        return dt.timedelta

    def bind_processor(self, dialect):
        impl_processor = self.impl.bind_processor(dialect)
        epoch = self.epoch
        if impl_processor:
            def process(value):
                if value is not None:
                    value = epoch + value
                return impl_processor(value)
        else:
            def process(value):
                if value is not None:
                    value = epoch + value
                return value
        return process

    def result_processor(self, dialect, coltype):
        impl_processor = self.impl.result_processor(dialect, coltype)
        epoch = self.epoch
        if impl_processor:
            def process(value):
                value = impl_processor(value)
                if value is None:
                    return None
                return value - epoch
        else:
            def process(value):
                if value is None:
                    return None
                return value - epoch
        return process

    @util.memoized_property
    def _expression_adaptations(self):
        return {
            operators.add:{
                Date:DateTime,
                Interval:Interval,
                DateTime:DateTime,
                Time:Time,
            },
            operators.sub:{
                Interval:Interval
            },
            operators.mul:{
                Numeric:Interval
            },
            operators.truediv: {
                Numeric:Interval
            },
            # Py2K
            operators.div: {
                Numeric:Interval
            }
            # end Py2K
        }

    @property
    def _type_affinity(self):
        return Interval

    def _coerce_compared_value(self, op, value):
        """See :meth:`.TypeEngine._coerce_compared_value` for a description."""

        return self.impl._coerce_compared_value(op, value)


class REAL(Float):
    """The SQL REAL type."""

    __visit_name__ = 'REAL'

class FLOAT(Float):
    """The SQL FLOAT type."""

    __visit_name__ = 'FLOAT'

class NUMERIC(Numeric):
    """The SQL NUMERIC type."""

    __visit_name__ = 'NUMERIC'


class DECIMAL(Numeric):
    """The SQL DECIMAL type."""

    __visit_name__ = 'DECIMAL'


class INTEGER(Integer):
    """The SQL INT or INTEGER type."""

    __visit_name__ = 'INTEGER'
INT = INTEGER


class SMALLINT(SmallInteger):
    """The SQL SMALLINT type."""

    __visit_name__ = 'SMALLINT'


class BIGINT(BigInteger):
    """The SQL BIGINT type."""

    __visit_name__ = 'BIGINT'

class TIMESTAMP(DateTime):
    """The SQL TIMESTAMP type."""

    __visit_name__ = 'TIMESTAMP'

    def get_dbapi_type(self, dbapi):
        return dbapi.TIMESTAMP

class DATETIME(DateTime):
    """The SQL DATETIME type."""

    __visit_name__ = 'DATETIME'


class DATE(Date):
    """The SQL DATE type."""

    __visit_name__ = 'DATE'


class TIME(Time):
    """The SQL TIME type."""

    __visit_name__ = 'TIME'

class TEXT(Text):
    """The SQL TEXT type."""

    __visit_name__ = 'TEXT'

class CLOB(Text):
    """The CLOB type.

    This type is found in Oracle and Informix.
    """

    __visit_name__ = 'CLOB'

class VARCHAR(String):
    """The SQL VARCHAR type."""

    __visit_name__ = 'VARCHAR'

class NVARCHAR(Unicode):
    """The SQL NVARCHAR type."""

    __visit_name__ = 'NVARCHAR'

class CHAR(String):
    """The SQL CHAR type."""

    __visit_name__ = 'CHAR'


class NCHAR(Unicode):
    """The SQL NCHAR type."""

    __visit_name__ = 'NCHAR'


class BLOB(LargeBinary):
    """The SQL BLOB type."""

    __visit_name__ = 'BLOB'

class BINARY(_Binary):
    """The SQL BINARY type."""

    __visit_name__ = 'BINARY'

class VARBINARY(_Binary):
    """The SQL VARBINARY type."""

    __visit_name__ = 'VARBINARY'


class BOOLEAN(Boolean):
    """The SQL BOOLEAN type."""

    __visit_name__ = 'BOOLEAN'

NULLTYPE = NullType()
BOOLEANTYPE = Boolean()
STRINGTYPE = String()

_type_map = {
    str: String(),
    # Py3K
    #bytes : LargeBinary(),
    # Py2K
    unicode : Unicode(),
    # end Py2K
    int : Integer(),
    float : Numeric(),
    bool: BOOLEANTYPE,
    decimal.Decimal : Numeric(),
    dt.date : Date(),
    dt.datetime : DateTime(),
    dt.time : Time(),
    dt.timedelta : Interval(),
    NoneType: NULLTYPE
}