pypy / pypy / module / oracle / interp_variable.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
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
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.typedef import TypeDef
from pypy.interpreter.typedef import interp_attrproperty
from pypy.interpreter.gateway import interp2app, unwrap_spec
from pypy.interpreter.error import OperationError
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.rlib.rarithmetic import ovfcheck

import sys
from pypy.module.oracle import roci, config, transform
from pypy.module.oracle import interp_lob, interp_object
from pypy.module.oracle.interp_error import W_Error, get
from pypy.module.oracle.config import string_w, StringBuffer

def define(cursor, position, numElements):
    paramptr = lltype.malloc(roci.Ptr(roci.OCIParam).TO, 1, flavor='raw')
    try:
        status = roci.OCIParamGet(
            cursor.handle, roci.OCI_HTYPE_STMT,
            cursor.environment.errorHandle,
            paramptr, position)
        cursor.environment.checkForError(
            status,
            "Variable_Define(): parameter")

        param = paramptr[0]
    finally:
        lltype.free(paramptr, flavor='raw')

    # call the helper to do the actual work
    var = _defineHelper(cursor, param, position, numElements)

    roci.OCIDescriptorFree(param, roci.OCI_DTYPE_PARAM)

    return var

def _defineHelper(cursor, param, position, numElements):
    # determine data type
    varType = typeByOracleDescriptor(param, cursor.environment)
    if cursor.numbersAsStrings and varType is VT_Float:
        varType = VT_NumberAsString

    # retrieve size of the parameter
    size = varType.size
    if varType.isVariableLength:

        # determine the maximum length from Oracle
        attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO, 1, flavor='raw')
        try:
            status = roci.OCIAttrGet(
                param, roci.OCI_HTYPE_DESCRIBE,
                rffi.cast(roci.dvoidp, attrptr),
                lltype.nullptr(roci.Ptr(roci.ub4).TO),
                roci.OCI_ATTR_DATA_SIZE,
                cursor.environment.errorHandle)

            cursor.environment.checkForError(
                status, "Variable_Define(): data size")
            sizeFromOracle = rffi.cast(lltype.Signed, attrptr[0])
        finally:
            lltype.free(attrptr, flavor='raw')

        # use the length from Oracle directly if available
        if sizeFromOracle:
            size = rffi.cast(lltype.Signed, sizeFromOracle)

        # otherwise, use the value set with the setoutputsize() parameter
        elif cursor.outputSize >= 0:
            if (cursor.outputSizeColumn < 0 or
                position == cursor.outputSizeColumn):
                size = cursor.outputSize

    # call the procedure to set values prior to define
    varType2 = varType.preDefine(varType, param, cursor.environment)

    # create a variable of the correct type
    if 0 and cursor.w_outputTypeHandler: # XXX
        var = newByOutputTypeHandler(
            cursor, param,
            cursor.w_outputTypeHandler,
            varType2, size, numElements)
    elif 0 and cursor.connection.w_outputTypeHandler: # XXX
        var = newByOutputTypeHandler(
            cursor, param,
            cursor.connection.w_outputTypeHandler,
            varType2, size, numElements)
    else:
        var = varType2(cursor, numElements, size)

    assert isinstance(var, W_Variable)

    # perform the define
    handleptr = lltype.malloc(roci.Ptr(roci.OCIDefine).TO, 1, flavor='raw')
    try:
        status = roci.OCIDefineByPos(
            cursor.handle,
            handleptr,
            var.environment.errorHandle,
            position,
            var.data, var.bufferSize,
            var.oracleType,
            rffi.cast(roci.dvoidp, var.indicator),
            var.actualLength,
            var.returnCode,
            roci.OCI_DEFAULT)
        var.environment.checkForError(
            status,
            "Variable_Define(): define")
        var.defineHandle = handleptr[0]
    finally:
        lltype.free(handleptr, flavor='raw')

    # call the procedure to set values after define
    var.postDefine(param)

    return var


class W_Variable(Wrappable):
    charsetForm = roci.SQLCS_IMPLICIT
    isVariableLength = False
    canBeInArray = True

    def __init__(self, cursor, numElements, size=0):
        self.environment = cursor.environment
        self.boundCursorHandle = lltype.nullptr(roci.OCIStmt.TO)
        self.boundName = None
        self.boundPos = 0
        self.isArray = False
        self.actualElementsPtr = lltype.malloc(roci.Ptr(roci.ub4).TO, 1,
                                               zero=True, flavor='raw')

        if numElements < 1:
            self.allocatedElements = 1
        else:
            self.allocatedElements = numElements
        self.internalFetchNum = 0
        self.actualLength = lltype.nullptr(rffi.CArrayPtr(roci.ub2).TO)
        self.returnCode = lltype.nullptr(rffi.CArrayPtr(roci.ub2).TO)

        # set the maximum length of the variable, ensure that a minimum of
        # 2 bytes is allocated to ensure that the array size check works
        if self.isVariableLength:
            size = max(size, rffi.sizeof(roci.ub2))
            if self.size != size:
                self.size = size

        # allocate the data for the variable
        self.allocateData(self.environment.space)

        # allocate the indicator for the variable
        self.indicator = lltype.malloc(rffi.CArrayPtr(roci.sb2).TO,
                                       self.allocatedElements,
                                       flavor='raw', zero=True)

        # ensure that all variable values start out NULL
        for i in range(self.allocatedElements):
            self.indicator[i] = rffi.cast(roci.sb2, roci.OCI_IND_NULL)

        # for variable length data, also allocate the return code
        if self.isVariableLength:
            self.returnCode = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO,
                                            self.allocatedElements,
                                            flavor='raw', zero=True)

        # perform extended initialization
        self.initialize(self.environment.space, cursor)

    def __del__(self):
        self.finalize()
        lltype.free(self.actualElementsPtr, flavor='raw')
        if self.actualLength:
            lltype.free(self.actualLength, flavor='raw')
        if self.data:
            lltype.free(self.data, flavor='raw')
        if self.returnCode:
            lltype.free(self.returnCode, flavor='raw')
        if self.indicator:
            lltype.free(self.indicator, flavor='raw')

    def getBufferSize(self):
        return self.size

    def allocateData(self, space):
        # set the buffer size for the variable
        self.bufferSize = self.getBufferSize()

        # allocate the data as long as it is small enough
        try:
            dataLength = ovfcheck(self.allocatedElements * self.bufferSize)
        except OverflowError:
            too_large = True
        else:
            too_large = False

        if too_large or dataLength >= roci.INT_MAX:
            raise OperationError(
                space.w_ValueError,
                space.wrap("array size too large"))

        self.data = lltype.malloc(rffi.CCHARP.TO, int(dataLength),
                                  flavor='raw', zero=True)

    def resize(self, space, size):
        # allocate the data for the new array
        orig_data = self.data
        orig_size = self.bufferSize
        self.size = size
        self.allocateData(space)

        # copy the data from the original array to the new array
        for i in range(self.allocatedElements):
            for j in range(orig_size):
                self.data[self.bufferSize * i + j] = \
                                          orig_data[orig_size * i + j]

        lltype.free(orig_data, flavor='raw')

        # force rebinding
        if self.boundName or self.boundPos:
            self._internalBind(space)

    def makeArray(self, space):
        if not self.canBeInArray:
            raise OperationError(
                get(space).w_NotSupportedError,
                space.wrap(
                    "Variable_MakeArray(): type does not support arrays"))
        self.isArray = True

    def initialize(self, space, cursor):
        pass

    def finalize(self):
        pass

    @staticmethod
    def preDefine(cls, param, environment):
        return cls

    def postDefine(self, param):
        pass

    def bind(self, space, cursor, w_name, pos):
        # nothing to do if already bound
        if (cursor.handle == self.boundCursorHandle and
            w_name == self.w_boundName and pos == self.boundPos):
            return

        # set the instance variables specific for binding
        self.boundCursorHandle = cursor.handle
        self.boundPos = pos
        self.w_boundName = w_name

        # perform the bind
        self._internalBind(space)

    def _internalBind(self, space):
        bindHandlePtr = lltype.malloc(roci.Ptr(roci.OCIBind).TO, 1,
                                      flavor='raw')
        if self.isArray:
            allocatedElements = self.allocatedElements
            actualElementsPtr = self.actualElementsPtr
        else:
            allocatedElements = 0
            actualElementsPtr = lltype.nullptr(roci.Ptr(roci.ub4).TO)

        try:
            if self.w_boundName:
                nameBuffer = config.StringBuffer()
                nameBuffer.fill(space, self.w_boundName)
                status = roci.OCIBindByName(
                    self.boundCursorHandle, bindHandlePtr,
                    self.environment.errorHandle,
                    nameBuffer.ptr, nameBuffer.size,
                    self.data, self.bufferSize,
                    self.oracleType,
                    rffi.cast(roci.dvoidp, self.indicator),
                    self.actualLength, self.returnCode,
                    allocatedElements, actualElementsPtr,
                    roci.OCI_DEFAULT)
                nameBuffer.clear()
            else:
                status = roci.OCIBindByPos(
                    self.boundCursorHandle, bindHandlePtr,
                    self.environment.errorHandle,
                    self.boundPos,
                    self.data, self.bufferSize,
                    self.oracleType,
                    rffi.cast(roci.dvoidp, self.indicator),
                    self.actualLength, self.returnCode,
                    allocatedElements, actualElementsPtr,
                    roci.OCI_DEFAULT)

            self.environment.checkForError(
                status, "NumberVar_InternalBind()")
            self.bindHandle = bindHandlePtr[0]
        finally:
            lltype.free(bindHandlePtr, flavor='raw')

        # set the charset form and id if applicable
        if self.charsetForm != roci.SQLCS_IMPLICIT:
            charsetformptr = lltype.malloc(roci.Ptr(roci.ub1).TO, 1,
                                           zero=True, flavor='raw')
            charsetformptr[0] = rffi.cast(roci.ub1, self.charsetForm)
            try:
                status = roci.OCIAttrSet(
                    self.bindHandle, roci.OCI_HTYPE_BIND,
                    rffi.cast(roci.dvoidp, charsetformptr), 0,
                    roci.OCI_ATTR_CHARSET_FORM,
                    self.environment.errorHandle)
                self.environment.checkForError(
                    status, "NumberVar_InternalBind(): set charset form")
            finally:
                lltype.free(charsetformptr, flavor='raw')

            charsetidptr = lltype.malloc(roci.Ptr(roci.ub2).TO, 1,
                                         zero=True, flavor='raw')
            charsetidptr[0] = rffi.cast(roci.ub2, roci.OCI_UTF16ID)
            try:
                status = roci.OCIAttrSet(
                    self.bindHandle, roci.OCI_HTYPE_BIND,
                    rffi.cast(roci.dvoidp, charsetidptr), 0,
                    roci.OCI_ATTR_CHARSET_ID,
                    self.environment.errorHandle)
                self.environment.checkForError(
                    status, "NumberVar_InternalBind(): set charset Id")
            finally:
                lltype.free(charsetidptr, flavor='raw')

        # set the max data size for strings
        buffersizeptr = lltype.malloc(roci.Ptr(roci.ub4).TO, 1,
                                      zero=True, flavor='raw')
        buffersizeptr[0] = rffi.cast(roci.ub4, self.size)
        try:
            status = roci.OCIAttrSet(
                self.bindHandle, roci.OCI_HTYPE_BIND,
                rffi.cast(roci.dvoidp, buffersizeptr), 0,
                roci.OCI_ATTR_MAXDATA_SIZE,
                self.environment.errorHandle)
            self.environment.checkForError(
                status, "NumberVar_InternalBind(): set max data size")
        finally:
            lltype.free(buffersizeptr, flavor='raw')


    def isNull(self, pos):
        return (rffi.cast(lltype.Signed, self.indicator[pos])
                ==
                rffi.cast(lltype.Signed, roci.OCI_IND_NULL))

    def verifyFetch(self, space, pos):
        # Verifies that truncation or other problems did not take place on
        # retrieve.
        if self.isVariableLength:
            if rffi.cast(lltype.Signed, self.returnCode[pos]) != 0:
                error = W_Error(space, self.environment,
                                "Variable_VerifyFetch()", 0)
                error.code = self.returnCode[pos]
                error.message = space.wrap(
                    "column at array pos %d fetched with error: %d" %
                    (pos,
                     rffi.cast(lltype.Signed, self.returnCode[pos])))
                w_error = get(space).w_DatabaseError

                raise OperationError(get(space).w_DatabaseError,
                                     space.wrap(error))

    def getSingleValue(self, space, pos):
        # ensure we do not exceed the number of allocated elements
        if pos >= self.allocatedElements:
            raise OperationError(
                space.w_IndexError,
                space.wrap("Variable_GetSingleValue: array size exceeded"))

        # check for a NULL value
        if self.isNull(pos):
            return space.wrap(None)

        # check for truncation or other problems on retrieve
        self.verifyFetch(space, pos)

        # calculate value to return
        value = self.getValueProc(space, pos)
        # XXX outConverter
        return value

    def getArrayValue(self, space, numElements):
        return space.newlist(
            [self.getSingleValue(space, i)
             for i in range(numElements)])

    @unwrap_spec(pos=int)
    def getValue(self, space, pos=0):
        if self.isArray:
            return self.getArrayValue(space, self.actualElementsPtr[0])
        return self.getSingleValue(space, pos)

    def setSingleValue(self, space, pos, w_value):
        # ensure we do not exceed the number of allocated elements
        if pos >= self.allocatedElements:
            raise OperationError(
                space.w_IndexError,
                space.wrap("Variable_SetSingleValue: array size exceeded"))

        # convert value, if necessary
        # XXX inConverter

        # check for a NULL value
        if space.is_w(w_value, space.w_None):
            self.indicator[pos] = roci.OCI_IND_NULL
            return

        self.indicator[pos] = roci.OCI_IND_NOTNULL
        if self.isVariableLength:
            self.returnCode[pos] = rffi.cast(roci.ub2, 0)

        self.setValueProc(space, pos, w_value)

    def setArrayValue(self, space, w_value):
        # ensure we have an array to set
        if not space.is_true(space.isinstance(w_value, space.w_list)):
            raise OperationError(
                space.w_TypeError,
                space.wrap("expecting array data"))

        elements_w = space.listview(w_value)

        # ensure we haven't exceeded the number of allocated elements
        if len(elements_w) > self.allocatedElements:
            raise OperationError(
                space.w_IndexError,
                space.wrap("Variable_SetArrayValue: array size exceeded"))

        # set all of the values
        self.actualElementsPtr[0] = rffi.cast(roci.ub4, len(elements_w))
        for i in range(len(elements_w)):
            self.setSingleValue(space, i, elements_w[i])

    @unwrap_spec(pos=int)
    def setValue(self, space, pos, w_value):
        if self.isArray:
            self.setArrayValue(space, w_value)
        else:
            self.setSingleValue(space, pos, w_value)


W_Variable.typedef = TypeDef(
    'Variable',
    getvalue = interp2app(W_Variable.getValue),
    setvalue = interp2app(W_Variable.setValue),

    maxlength  = interp_attrproperty('bufferSize', W_Variable),
    bufferSize = interp_attrproperty('bufferSize', W_Variable),
    size = interp_attrproperty('size', W_Variable),
    )

class VT_String(W_Variable):
    oracleType = roci.SQLT_CHR
    size = config.MAX_STRING_CHARS
    isVariableLength = True

    def getBufferSize(self):
        if config.WITH_UNICODE:
            return self.size * BYTES_PER_CHAR
        else:
            if self.charsetForm == roci.SQLCS_IMPLICIT:
                return self.size * self.environment.maxBytesPerCharacter
            else:
                return self.size * 2

    def initialize(self, space, cursor):
        self.actualLength = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO,
                                          self.allocatedElements,
                                          zero=True, flavor='raw')

    def getValueProc(self, space, pos):
        offset = pos * self.bufferSize
        dataptr = rffi.ptradd(self.data, offset)
        length = rffi.cast(lltype.Signed, self.actualLength[pos])

        i = 0
        if config.WITH_UNICODE:
            if isinstance(self, VT_Binary):
                return space.wrap(rffi.charpsize2str(dataptr, length))
            else:
                l = []
                while i < length:
                    l.append(unichr((ord(dataptr[i + 1]) << 8) +
                                    ord(dataptr[i])))
                    i += 2
                return space.wrap(u''.join(l))
        else:
            if self.charsetForm == roci.SQLCS_IMPLICIT:
                return space.wrap(rffi.charpsize2str(dataptr, length))
            else:
                l = []
                while i < length:
                    l.append(unichr((ord(dataptr[i + 1]) << 8) +
                                    ord(dataptr[i])))
                    i += 2
                return space.wrap(u''.join(l))

    def setValueProc(self, space, pos, w_value):
        if config.WITH_UNICODE:
            wantBytes = not self.isCharacterData
        else:
            wantBytes = self.charsetForm == roci.SQLCS_IMPLICIT

        if wantBytes:
            if space.is_true(space.isinstance(w_value, space.w_str)):
                buf = config.StringBuffer()
                buf.fill(space, w_value)
                size = buf.size
            else:
                raise OperationError(
                    space.w_TypeError,
                    space.wrap("expecting string or buffer data"))
        else:
            if space.is_true(space.isinstance(w_value, space.w_unicode)):
                buf = config.StringBuffer()
                buf.fill_with_unicode(space, w_value)
                size = buf.size
            else:
                raise OperationError(
                    space.w_TypeError,
                    space.wrap("expecting unicode data"))

        try:
            if wantBytes:
                if buf.size > self.environment.maxStringBytes:
                    raise OperationError(
                        space.w_ValueError,
                        space.wrap("string data too large"))
            else:
                if buf.size > config.MAX_STRING_CHARS * 2:
                    raise OperationError(
                        space.w_ValueError,
                        space.wrap("unicode data too large"))

            # ensure that the buffer is large enough
            if buf.size > self.bufferSize:
                self.resize(space, size)

            # keep a copy of the string
            self.actualLength[pos] = rffi.cast(roci.ub2, buf.size)
            offset = pos * self.bufferSize
            for index in range(buf.size):
                self.data[offset + index] = buf.ptr[index]
        finally:
            buf.clear()

class VT_FixedChar(VT_String):
    oracleType = roci.SQLT_AFC
    size = 2000

class VT_NationalCharString(VT_String):
    charsetForm = roci.SQLCS_NCHAR

    def postDefine(self, param):
        charsetformptr = lltype.malloc(roci.Ptr(roci.ub1).TO, 1,
                                       zero=True, flavor='raw')
        charsetformptr[0] = rffi.cast(roci.ub1, self.charsetForm)
        try:
            status = roci.OCIAttrSet(
                self.defineHandle, roci.OCI_HTYPE_DEFINE,
                rffi.cast(roci.dvoidp, charsetformptr), 0,
                roci.OCI_ATTR_CHARSET_FORM,
                self.environment.errorHandle)
            self.environment.checkForError(
                status, "StringVar_PostDefine(): set charset form")
        finally:
            lltype.free(charsetformptr, flavor='raw')

        charsetidptr = lltype.malloc(roci.Ptr(roci.ub2).TO, 1,
                                     zero=True, flavor='raw')
        charsetidptr[0] = rffi.cast(roci.ub2, roci.OCI_UTF16ID)
        try:
            status = roci.OCIAttrSet(
                self.defineHandle, roci.OCI_HTYPE_DEFINE,
                rffi.cast(roci.dvoidp, charsetidptr), 0,
                roci.OCI_ATTR_CHARSET_ID,
                self.environment.errorHandle)
            self.environment.checkForError(
                status, "StringVar_PostDefine(): set charset Id")
        finally:
            lltype.free(charsetidptr, flavor='raw')


class VT_FixedNationalChar(VT_NationalCharString):
    oracleType = roci.SQLT_AFC
    size = 2000

class VT_LongString(W_Variable):
    oracleType = roci.SQLT_LVC
    isVariableLength = True
    size = 128 * 1024

    def getBufferSize(self):
        return self.size + rffi.sizeof(roci.ub4)

    def getValueProc(self, space, pos):
        ptr = rffi.ptradd(self.data, pos * self.bufferSize)
        length = rffi.cast(roci.Ptr(roci.ub4), ptr)[0]
        length = rffi.cast(lltype.Signed, length)

        ptr = rffi.ptradd(ptr, rffi.sizeof(roci.ub4))
        return space.wrap(rffi.charpsize2str(ptr, length))

    def setValueProc(self, space, pos, w_value):
        buf = config.StringBuffer()
        buf.fill(space, w_value)

        try:
            # ensure that the buffer is large enough
            if buf.size + rffi.sizeof(roci.ub4) > self.bufferSize:
                self.resize(space, buf.size + rffi.sizeof(roci.ub4))

            # copy the string to the Oracle buffer
            ptr = rffi.ptradd(self.data, pos * self.bufferSize)
            rffi.cast(roci.Ptr(roci.ub4), ptr)[0] = rffi.cast(roci.ub4, buf.size)
            for index in range(buf.size):
                ptr[index + rffi.sizeof(roci.ub4)] = buf.ptr[index]
        finally:
            buf.clear()

class VT_Rowid(VT_String):
    oracleType = roci.SQLT_CHR
    size = 18
    isVariableLength = False

class VT_Binary(VT_String):
    oracleType = roci.SQLT_BIN
    size = config.MAX_BINARY_BYTES

class VT_LongBinary(VT_LongString):
    oracleType = roci.SQLT_LVB

class VT_NativeFloat(W_Variable):
    pass

class VT_Float(W_Variable):
    oracleType = roci.SQLT_VNU
    size = rffi.sizeof(roci.OCINumber)

    @staticmethod
    def preDefine(cls, param, environment):
        # if the return type has not already been specified, check to
        # see if the number can fit inside an integer by looking at
        # the precision and scale
        if cls is VT_Float:
            attrptr = lltype.malloc(rffi.CArrayPtr(roci.sb1).TO, 1,
                                    flavor='raw')
            try:
                status = roci.OCIAttrGet(
                    param, roci.OCI_HTYPE_DESCRIBE,
                    rffi.cast(roci.dvoidp, attrptr),
                    lltype.nullptr(roci.Ptr(roci.ub4).TO),
                    roci.OCI_ATTR_SCALE,
                    environment.errorHandle)
                environment.checkForError(
                    status,
                    "NumberVar_PreDefine(): scale")
                scale = rffi.cast(lltype.Signed, attrptr[0])
            finally:
                lltype.free(attrptr, flavor='raw')

            attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO, 1,
                                    flavor='raw')
            try:
                status = roci.OCIAttrGet(
                    param, roci.OCI_HTYPE_DESCRIBE,
                    rffi.cast(roci.dvoidp, attrptr),
                    lltype.nullptr(roci.Ptr(roci.ub4).TO),
                    roci.OCI_ATTR_PRECISION,
                    environment.errorHandle)
                environment.checkForError(
                    status,
                    "NumberVar_PreDefine(): precision")
                precision = rffi.cast(lltype.Signed, attrptr[0])
            finally:
                lltype.free(attrptr, flavor='raw')

            if scale == 0 or (scale == -127 and precision == 0):
                if precision > 0 and precision < 10:
                    return VT_Integer
                else:
                    return VT_LongInteger

        return cls

    def getValueProc(self, space, pos):
        dataptr = rffi.ptradd(
            rffi.cast(roci.Ptr(roci.OCINumber), self.data),
            pos)
        if isinstance(self, VT_Integer):
            integerValuePtr = lltype.malloc(roci.Ptr(lltype.Signed).TO, 1,
                                            flavor='raw')
            try:
                status = roci.OCINumberToInt(
                    self.environment.errorHandle,
                    dataptr,
                    rffi.sizeof(rffi.LONG),
                    roci.OCI_NUMBER_SIGNED,
                    rffi.cast(roci.dvoidp, integerValuePtr))
                self.environment.checkForError(
                    status, "NumberVar_GetValue(): as integer")
                if isinstance(self, VT_Boolean):
                    return space.newbool(bool(integerValuePtr[0]))
                else:
                    return space.wrap(integerValuePtr[0])
            finally:
                lltype.free(integerValuePtr, flavor='raw')
        elif isinstance(self, VT_NumberAsString) or isinstance(self, VT_LongInteger):
            format_buf = config.StringBuffer()
            format_buf.fill(space, space.wrap("TM9"))
            sizeptr = lltype.malloc(rffi.CArray(roci.ub4), 1, flavor='raw')
            BUFSIZE = 200
            sizeptr[0] = rffi.cast(roci.ub4, BUFSIZE)
            textbuf, text = rffi.alloc_buffer(BUFSIZE)
            try:
                status = roci.OCINumberToText(
                    self.environment.errorHandle,
                    dataptr,
                    format_buf.ptr, format_buf.size,
                    None, 0,
                    sizeptr, textbuf);
                self.environment.checkForError(
                    status, "NumberVar_GetValue(): as string")
                w_strvalue = space.wrap(
                    rffi.str_from_buffer(textbuf, text,
                                         BUFSIZE,
                                         rffi.cast(lltype.Signed, sizeptr[0])))
            finally:
                rffi.keep_buffer_alive_until_here(textbuf, text)
                lltype.free(sizeptr, flavor='raw')
                format_buf.clear()

            if isinstance(self, VT_NumberAsString):
                return w_strvalue

            try:
                return space.call_function(space.w_int, w_strvalue)
            except OperationError, e:
                if e.match(space, space.w_ValueError):
                    return space.call_function(space.w_float, w_strvalue)
                raise
        else:
            return transform.OracleNumberToPythonFloat(
                self.environment, dataptr)

    def setValueProc(self, space, pos, w_value):
        dataptr = rffi.ptradd(
            rffi.cast(roci.Ptr(roci.OCINumber), self.data),
            pos)

        if space.is_true(space.isinstance(w_value, space.w_int)):
            integerValuePtr = lltype.malloc(roci.Ptr(lltype.Signed).TO, 1,
                                            flavor='raw')
            try:
                integerValuePtr[0] = space.int_w(w_value)
                status = roci.OCINumberFromInt(
                    self.environment.errorHandle,
                    rffi.cast(roci.dvoidp, integerValuePtr),
                    rffi.sizeof(lltype.Signed),
                    roci.OCI_NUMBER_SIGNED,
                    dataptr)
                self.environment.checkForError(
                    status, "NumberVar_SetValue(): from integer")
            finally:
                lltype.free(integerValuePtr, flavor='raw')
            return
        elif space.is_true(space.isinstance(w_value, space.w_long)):
            text_buf = config.StringBuffer()
            text_buf.fill(space, space.str(w_value))
            format_buf = config.StringBuffer()
            format_buf.fill(space, space.wrap("9" * 63))
            status = roci.OCINumberFromText(
                self.environment.errorHandle,
                text_buf.ptr, text_buf.size,
                format_buf.ptr, format_buf.size,
                None, 0,
                dataptr)
            text_buf.clear()
            format_buf.clear()
            self.environment.checkForError(
                status, "NumberVar_SetValue(): from long")
            return
        # XXX The bool case was already processed above
        elif space.is_true(space.isinstance(w_value, space.w_float)):
            doubleValuePtr = lltype.malloc(roci.Ptr(lltype.Float).TO, 1,
                                           flavor='raw')
            try:
                doubleValuePtr[0] = space.float_w(w_value)
                status = roci.OCINumberFromReal(
                    self.environment.errorHandle,
                    rffi.cast(roci.dvoidp, doubleValuePtr),
                    rffi.sizeof(lltype.Float),
                    dataptr)
                self.environment.checkForError(
                    status, "NumberVar_SetValue(): from float")
            finally:
                lltype.free(doubleValuePtr, flavor='raw')
            return
        elif space.is_true(space.isinstance(w_value, get(space).w_DecimalType)):
            w_text, w_format = transform.DecimalToFormatAndText(self.environment, w_value)
            text_buf = config.StringBuffer()
            text_buf.fill(space, w_text)
            format_buf = config.StringBuffer()
            format_buf.fill(space, w_format)
            nls_params = "NLS_NUMERIC_CHARACTERS='.,'"
            status = roci.OCINumberFromText(
                self.environment.errorHandle,
                text_buf.ptr, text_buf.size,
                format_buf.ptr, format_buf.size,
                nls_params, len(nls_params),
                dataptr)
            text_buf.clear()
            format_buf.clear()
            self.environment.checkForError(
                status, "NumberVar_SetValue(): from decimal")
            return
        raise OperationError(
            space.w_TypeError,
            space.wrap("expecting numeric data"))

class VT_Integer(VT_Float):
    pass

class VT_Boolean(VT_Integer):
    pass

class VT_NumberAsString(VT_Float):
    pass

class VT_LongInteger(VT_Float):
    pass

class VT_DateTime(W_Variable):
    oracleType = roci.SQLT_ODT
    size = rffi.sizeof(roci.OCIDate)

    def getValueProc(self, space, pos):
        dataptr = rffi.ptradd(
            rffi.cast(roci.Ptr(roci.OCIDate), self.data),
            pos)
        return transform.OracleDateToPythonDateTime(self.environment, dataptr)

    def setValueProc(self, space, pos, w_value):
        dataptr = rffi.ptradd(
            rffi.cast(roci.Ptr(roci.OCIDate), self.data),
            pos)
        if space.is_true(space.isinstance(w_value, get(space).w_DateTimeType)):
            year = space.int_w(space.getattr(w_value, space.wrap('year')))
            month = space.int_w(space.getattr(w_value, space.wrap('month')))
            day = space.int_w(space.getattr(w_value, space.wrap('day')))
            hour = space.int_w(space.getattr(w_value, space.wrap('hour')))
            minute = space.int_w(space.getattr(w_value, space.wrap('minute')))
            second = space.int_w(space.getattr(w_value, space.wrap('second')))
        elif space.is_true(space.isinstance(w_value, get(space).w_DateType)):
            year = space.int_w(space.getattr(w_value, space.wrap('year')))
            month = space.int_w(space.getattr(w_value, space.wrap('month')))
            day = space.int_w(space.getattr(w_value, space.wrap('day')))
            hour = minute = second = 0
        else:
            raise OperationError(
                space.w_TypeError,
                space.wrap("expecting date data"))

        # store a copy of the value
        value = dataptr[0]
        timePart = value.c_OCIDateTime
        rffi.setintfield(timePart, 'c_OCITimeHH', hour)
        rffi.setintfield(timePart, 'c_OCITimeMI', minute)
        rffi.setintfield(timePart, 'c_OCITimeSS', second)
        rffi.setintfield(dataptr[0], 'c_OCIDateYYYY', year)
        rffi.setintfield(dataptr[0], 'c_OCIDateMM', month)
        rffi.setintfield(dataptr[0], 'c_OCIDateDD', day)

class VT_Date(VT_DateTime):
    oracleType = roci.SQLT_ODT
    size = rffi.sizeof(roci.OCIDate)

    def getValueProc(self, space, pos):
        dataptr = rffi.ptradd(
            rffi.cast(roci.Ptr(roci.OCIDate), self.data),
            pos)
        return transform.OracleDateToPythonDate(self.environment, dataptr)

class W_VariableWithDescriptor(W_Variable):
    size = rffi.sizeof(roci.dvoidp)

    def initialize(self, space, cursor):
        # initialize the descriptors
        for i in range(self.allocatedElements):
            dataptr = rffi.ptradd(
                rffi.cast(roci.Ptr(roci.dvoidp), self.data),
                i)
            status = roci.OCIDescriptorAlloc(
                self.environment.handle,
                dataptr,
                self.descriptorType,
                0, None)
            self.environment.checkForError(
                status, self.descriptionText + "_Initialize()")

    def finalize(self):
        dataptr = rffi.cast(roci.Ptr(roci.dvoidp), self.data)
        for i in range(self.allocatedElements):
            if dataptr[i]:
                roci.OCIDescriptorFree(
                    dataptr[i], self.descriptorType)

    def getDataptr(self, pos):
        return rffi.ptradd(
            rffi.cast(roci.Ptr(roci.dvoidp), self.data),
            pos)

class VT_Timestamp(W_VariableWithDescriptor):
    oracleType = roci.SQLT_TIMESTAMP
    descriptorType = roci.OCI_DTYPE_TIMESTAMP
    descriptionText = "TimestampVar"

    def getValueProc(self, space, pos):
        return transform.OracleTimestampToPythonDate(
            self.environment, self.getDataptr(pos))

    def setValueProc(self, space, pos, w_value):
        # make sure a timestamp is being bound
        if not space.is_true(space.isinstance(w_value, get(space).w_DateTimeType)):
            raise OperationError(
                space.w_TypeError,
                space.wrap("expecting timestamp data"))

        year = space.int_w(space.getattr(w_value, space.wrap('year')))
        month = space.int_w(space.getattr(w_value, space.wrap('month')))
        day = space.int_w(space.getattr(w_value, space.wrap('day')))
        hour = space.int_w(space.getattr(w_value, space.wrap('hour')))
        minute = space.int_w(space.getattr(w_value, space.wrap('minute')))
        second = space.int_w(space.getattr(w_value, space.wrap('second')))
        microsecond = space.int_w(space.getattr(w_value, space.wrap('microsecond')))

        status = roci.OCIDateTimeConstruct(
            self.environment.handle,
            self.environment.errorHandle,
            self.getDataptr(pos)[0],
            year, month, day, hour, minute, second, microsecond * 1000,
            None, 0)

        self.environment.checkForError(
            status, "TimestampVar_SetValue(): create structure")

        validptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1, flavor='raw')
        try:
            status = roci.OCIDateTimeCheck(
                self.environment.handle,
                self.environment.errorHandle,
                self.getDataptr(pos)[0],
                validptr);
            self.environment.checkForError(
                status,
                "TimestampVar_SetValue()")
            valid = rffi.cast(lltype.Signed, validptr[0])
        finally:
            lltype.free(validptr, flavor='raw')

        if valid != 0:
            raise OperationError(
                get(space).w_DataError,
                space.wrap("invalid date"))

class VT_Interval(W_VariableWithDescriptor):
    oracleType = roci.SQLT_INTERVAL_DS
    descriptorType = roci.OCI_DTYPE_INTERVAL_DS
    descriptionText = "TimestampVar"

    def getValueProc(self, space, pos):
        return transform.OracleIntervalToPythonDelta(
            self.environment, self.getDataptr(pos))

    def setValueProc(self, space, pos, w_value):
        if not space.is_true(space.isinstance(w_value,
                                              get(space).w_TimedeltaType)):
            raise OperationError(
                space.w_TypeError,
                space.wrap("expecting timedelta data"))

        days = space.int_w(space.getattr(w_value, space.wrap('days')))
        seconds = space.int_w(space.getattr(w_value, space.wrap('seconds')))
        hours = seconds / 3600
        seconds -= hours * 3600
        minutes = seconds / 60
        seconds -= minutes * 60
        microseconds = space.int_w(
            space.getattr(w_value, space.wrap('microseconds')))

        status = roci.OCIIntervalSetDaySecond(
            self.environment.handle,
            self.environment.errorHandle,
            days, hours, minutes, seconds, microseconds,
            self.getDataptr(pos)[0])

        self.environment.checkForError(
            status, "IntervalVar_SetValue()")

class W_LobVariable(W_VariableWithDescriptor):
    descriptorType = roci.OCI_DTYPE_LOB
    descriptionText = "LobVar"
    temporaryLobType = roci.OCI_TEMP_CLOB

    def initialize(self, space, cursor):
        W_VariableWithDescriptor.initialize(self, space, cursor)
        self.connection = cursor.connection

    def ensureTemporary(self, space, pos):
        # make sure we have a temporary LOB set up
        temporaryptr = lltype.malloc(rffi.CArrayPtr(roci.boolean).TO, 1, flavor='raw')
        try:
            status = roci.OCILobIsTemporary(
                self.environment.handle,
                self.environment.errorHandle,
                self.getDataptr(pos)[0],
                temporaryptr);
            self.environment.checkForError(
                status,
                "LobVar_SetValue(): check temporary")
            temporary = rffi.cast(lltype.Signed, temporaryptr[0])
        finally:
            lltype.free(temporaryptr, flavor='raw')

        if temporary:
            return

        status = roci.OCILobCreateTemporary(
            self.connection.handle,
            self.environment.errorHandle,
            self.getDataptr(pos)[0],
            roci.OCI_DEFAULT,
            roci.OCI_DEFAULT,
            self.temporaryLobType,
            False,
            roci.OCI_DURATION_SESSION)
        self.environment.checkForError(
            status,
            "LobVar_SetValue(): create temporary")


    def setValueProc(self, space, pos, w_value):
        self.ensureTemporary(space, pos)
        self.trim(space, pos, 0)
        self.write(space, pos, w_value, 1)

    def getLength(self, space, pos):
        "Return the size of the LOB variable for internal comsumption."
        lengthptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1, flavor='raw')
        try:
            status = roci.OCILobGetLength(
                self.connection.handle,
                self.environment.errorHandle,
                self.getDataptr(pos)[0],
                lengthptr)
            self.environment.checkForError(
                status,
                "LobVar_GetLength()")
            return rffi.cast(lltype.Signed,
                             lengthptr[0]) # XXX test overflow
        finally:
            lltype.free(lengthptr, flavor='raw')

    def trim(self, space, pos, newSize):
        status = roci.OCILobTrim(
            self.connection.handle,
            self.environment.errorHandle,
            self.getDataptr(pos)[0],
            newSize)
        self.environment.checkForError(
            status,
            "LobVar_Trim()")

    def read(self, space, pos, offset, amount):
        # modify the arguments
        if offset <= 0:
            offset = 1
        if amount < 0:
            amount = self.getLength(space, pos) - offset + 1
            if amount <= 0:
                amount = 1

        bufferSize = amount
        raw_buffer, gc_buffer = rffi.alloc_buffer(bufferSize)
        amountptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1, flavor='raw')
        amountptr[0] = rffi.cast(roci.ub4, amount)
        try:
            status = roci.OCILobRead(
                self.connection.handle,
                self.environment.errorHandle,
                self.getDataptr(pos)[0],
                amountptr, offset,
                raw_buffer, bufferSize,
                None, None,
                config.CHARSETID, self.charsetForm)
            self.environment.checkForError(
                status,
                "LobVar_Read()")
            amount = rffi.cast(lltype.Signed,
                               amountptr[0]) # XXX test overflow
            value = rffi.str_from_buffer(raw_buffer, gc_buffer, bufferSize, amount)
            return space.wrap(value)
        finally:
            lltype.free(amountptr, flavor='raw')
            rffi.keep_buffer_alive_until_here(raw_buffer, gc_buffer)

    def write(self, space, pos, w_value, offset):
        databuf = config.StringBuffer()
        databuf.fill(space, w_value)
        amountptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1, flavor='raw')
        amountptr[0] = rffi.cast(roci.ub4, databuf.size)

        try:
            # nothing to do if no data to write
            if databuf.size == 0:
                return 0

            status = roci.OCILobWrite(
                self.connection.handle,
                self.environment.errorHandle,
                self.getDataptr(pos)[0],
                amountptr, offset,
                databuf.ptr, databuf.size,
                roci.OCI_ONE_PIECE,
                None, None,
                config.CHARSETID, self.charsetForm)
            self.environment.checkForError(
                status,
                "LobVar_Write()")
            amount = amountptr[0]
        finally:
            lltype.free(amountptr, flavor='raw')
            databuf.clear()

        return amount

    def getValueProc(self, space, pos):
        return space.wrap(interp_lob.W_ExternalLob(self, pos))

class VT_CLOB(W_LobVariable):
    oracleType = roci.SQLT_CLOB

class VT_NCLOB(W_LobVariable):
    oracleType = roci.SQLT_CLOB

class VT_BLOB(W_LobVariable):
    oracleType = roci.SQLT_BLOB
    temporaryLobType = roci.OCI_TEMP_BLOB

class VT_BFILE(W_LobVariable):
    oracleType = roci.SQLT_BFILE

    def write(self, space, pos, w_value, offset):
        raise OperationError(
            space.w_TypeError,
            space.wrap("BFILEs are read only"))

    def read(self, space, pos, offset, amount):
        self.openFile()
        try:
            return W_LobVariable.read(self, space, pos, offset, amount)
        finally:
            self.closeFile()

    def openFile(self):
        pass # XXX

    def closeFile(self):
        pass # XXX

class VT_Cursor(W_Variable):
    oracleType = roci.SQLT_RSET
    size = rffi.sizeof(roci.OCIStmt)
    canBeInArray = False

    def initialize(self, space, cursor):
        from pypy.module.oracle import interp_cursor
        self.connection = cursor.connection
        self.cursors_w = [None] * self.allocatedElements
        for i in range(self.allocatedElements):
            tempCursor = interp_cursor.W_Cursor(space, self.connection)
            tempCursor.allocateHandle()
            self.cursors_w[i] = space.wrap(tempCursor)

            dataptr = rffi.ptradd(
                rffi.cast(roci.Ptr(roci.OCIStmt), self.data),
                i)
            dataptr[0] = tempCursor.handle

    def getValueProc(self, space, pos):
        from pypy.module.oracle import interp_cursor
        w_cursor = self.cursors_w[pos]
        space.interp_w(interp_cursor.W_Cursor, w_cursor).statementType = -1
        return w_cursor

    def setValueProc(self, space, pos, w_value):
        from pypy.module.oracle import interp_cursor
        w_CursorType = space.gettypeobject(interp_cursor.W_Cursor.typedef)
        if not space.is_true(space.isinstance(w_value, w_CursorType)):
            raise OperationError(
                space.w_TypeError,
                space.wrap("expecting cursor"))

        self.cursors_w[pos] = w_value

        cursor = space.interp_w(interp_cursor.W_Cursor, w_value)
        if not cursor.isOwned:
            cursor.freeHandle(space, raiseError=True)
            cursor.isOwned = True
            cursor.allocateHandle()

        dataptr = rffi.ptradd(
            rffi.cast(roci.Ptr(roci.OCIStmt), self.data),
            pos)
        dataptr[0] = cursor.handle
        cursor.statementType = -1


class VT_Object(W_Variable):
    oracleType = roci.SQLT_NTY
    size = rffi.sizeof(roci.dvoidp)
    canBeInArray = False

    objectIndicator = lltype.nullptr(rffi.CArrayPtr(roci.dvoidp).TO)

    def initialize(self, space, cursor):
        self.connection = cursor.connection
        self.objectType = None
        self.objectIndicator = lltype.malloc(
            rffi.CArrayPtr(roci.dvoidp).TO,
            self.allocatedElements,
            flavor='raw', zero=True)

    def finalize(self):
        for i in range(self.allocatedElements):
            data = rffi.cast(roci.Ptr(roci.dvoidp), self.data)
            roci.OCIObjectFree(
                self.environment.handle,
                self.environment.errorHandle,
                data[i],
                roci.OCI_OBJECTFREE_FORCE)
        if self.objectIndicator:
            lltype.free(self.objectIndicator, flavor='raw')

    def postDefine(self, param):
        # XXX this used to be in preDefine
        self.objectType = interp_object.W_ObjectType(self.connection, param)

        data = rffi.cast(roci.Ptr(roci.dvoidp), self.data)

        status = roci.OCIDefineObject(
            self.defineHandle,
            self.environment.errorHandle,
            self.objectType.tdo,
            data,
            0,
            self.objectIndicator,
            0)
        self.environment.checkForError(
            status,
            "ObjectVar_PostDefine(): define object")

    def isNull(self, pos):
        # look at our own indicator array
        if not self.objectIndicator[pos]:
            return True
        return (rffi.cast(lltype.Signed,
                          rffi.cast(roci.Ptr(roci.OCIInd),
                                    self.objectIndicator[pos])[0])
                ==
                rffi.cast(lltype.Signed, roci.OCI_IND_NULL))

    def getValueProc(self, space, pos):
        data = rffi.cast(roci.Ptr(roci.dvoidp), self.data)
        # only allowed to get the value once (for now)
        if not data[pos]:
            raise OperationError(
                get(space).w_ProgrammingError,
                space.wrap("variable value can only be acquired once"))


        # for collections, return the list rather than the object
        if self.objectType.isCollection:
            return interp_object.convertCollection(
                space, self.environment, data[pos], self, self.objectType)

        # for objects, return a representation of the object
        var = interp_object.W_ExternalObject(
            self, self.objectType, data[pos], self.objectIndicator[pos])

        data[pos] = lltype.nullptr(roci.dvoidp.TO)
        self.objectIndicator[pos] = lltype.nullptr(roci.dvoidp.TO)
        return space.wrap(var)

all_variable_types = []
for name, cls in globals().items():
    if not name.startswith('VT_') or not isinstance(cls, type):
        continue
    def register_variable_class(cls):
        def clone(self, cursor, numElements, size):
            return cls(cursor, numElements, size)
        cls.clone = clone
        cls.typedef = TypeDef(
            cls.__name__, W_Variable.typedef,
            )
        all_variable_types.append(cls)
    register_variable_class(cls)

def typeByOracleDescriptor(param, environment):
    # retrieve datatype of the parameter
    attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO, 1, flavor='raw')
    try:
        status = roci.OCIAttrGet(
            param, roci.OCI_HTYPE_DESCRIBE,
            rffi.cast(roci.dvoidp, attrptr),
            lltype.nullptr(roci.Ptr(roci.ub4).TO),
            roci.OCI_ATTR_DATA_TYPE,
            environment.errorHandle)
        environment.checkForError(
            status,
            "Variable_TypeByOracleDescriptor(): data type")
        dataType = rffi.cast(lltype.Signed, attrptr[0])
    finally:
        lltype.free(attrptr, flavor='raw')

    # retrieve character set form of the parameter
    if dataType not in (roci.SQLT_CHR, roci.SQLT_AFC, roci.SQLT_CLOB):
        charsetForm = roci.SQLCS_IMPLICIT
    else:
        attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub1).TO, 1, flavor='raw')
        try:
            status = roci.OCIAttrGet(
                param, roci.OCI_HTYPE_DESCRIBE,
                rffi.cast(roci.dvoidp, attrptr),
                lltype.nullptr(roci.Ptr(roci.ub4).TO),
                roci.OCI_ATTR_CHARSET_FORM,
                environment.errorHandle)
            environment.checkForError(
                status,
                "Variable_TypeByOracleDescriptor(): charset form")
            charsetForm = rffi.cast(lltype.Signed, attrptr[0])
        finally:
            lltype.free(attrptr, flavor='raw')

    return _typeByOracleDataType(dataType, charsetForm)

variableType = {
    roci.SQLT_LNG: VT_LongString,
    roci.SQLT_AFC: VT_FixedChar,
    roci.SQLT_CHR: VT_String,
    roci.SQLT_RDD: VT_Rowid,
    roci.SQLT_BIN: VT_Binary,
    roci.SQLT_LBI: VT_LongBinary,
    roci.SQLT_BFLOAT: VT_NativeFloat,
    roci.SQLT_IBFLOAT: VT_NativeFloat,
    roci.SQLT_BDOUBLE: VT_NativeFloat,
    roci.SQLT_IBDOUBLE: VT_NativeFloat,
    roci.SQLT_NUM: VT_Float,
    roci.SQLT_VNU: VT_Float,
    roci.SQLT_DAT: VT_DateTime,
    roci.SQLT_ODT: VT_DateTime,
    roci.SQLT_DATE: VT_Timestamp,
    roci.SQLT_TIMESTAMP: VT_Timestamp,
    roci.SQLT_TIMESTAMP_TZ: VT_Timestamp,
    roci.SQLT_TIMESTAMP_LTZ: VT_Timestamp,
    roci.SQLT_INTERVAL_DS: VT_Interval,
    roci.SQLT_CLOB: VT_CLOB,
    roci.SQLT_BLOB: VT_BLOB,
    roci.SQLT_BFILE: VT_BFILE,
    roci.SQLT_RSET: VT_Cursor,
    roci.SQLT_NTY: VT_Object,
    }
variableTypeNChar = {
    roci.SQLT_AFC: VT_FixedNationalChar,
    roci.SQLT_CHR: VT_NationalCharString,
    roci.SQLT_CLOB: VT_NCLOB,
    }
# remove eventual undefined types
try:
    del variableType[None]
except KeyError:
    pass
try:
    del variableTypeNChar[None]
except KeyError:
    pass

def _typeByOracleDataType(dataType, charsetForm):
    if charsetForm == roci.SQLCS_NCHAR:
        varType = variableTypeNChar.get(dataType, None)
    else:
        varType = variableType.get(dataType, None)

    if varType is None:
        raise ValueError("Variable_TypeByOracleDataType: "
                         "unhandled data type %d" % (dataType,))

    return varType

def typeByPythonType(space, cursor, w_type):
    """Return a variable type given a Python type object"""
    from pypy.objspace.std.typeobject import W_TypeObject

    moduledict = get(space)
    if not space.is_true(space.isinstance(w_type, space.w_type)):
        raise OperationError(
            space.w_TypeError,
            space.wrap("Variable_TypeByPythonType(): type expected"))
    assert isinstance(w_type, W_TypeObject)
    if w_type in get(space).variableTypeByPythonType:
        return get(space).variableTypeByPythonType[w_type]
    if space.is_w(w_type, space.w_int):
        return VT_Integer
    raise OperationError(
        moduledict.w_NotSupportedError,
        space.wrap("Variable_TypeByPythonType(): unhandled data type"))

def typeByValue(space, w_value, numElements):
    "Return a variable type given a Python object"
    moduledict = get(space)

    # handle scalars
    if space.is_w(w_value, space.w_None):
        return VT_String, 1, numElements

    if space.is_true(space.isinstance(w_value, space.w_str)):
        size = space.len_w(w_value)
        if size > config.MAX_STRING_CHARS:
            return VT_LongString, size, numElements
        else:
            return VT_String, size, numElements

    if space.is_true(space.isinstance(w_value, space.w_unicode)):
        size = space.len_w(w_value)
        return VT_NationalCharString, size, numElements

    if space.is_true(space.isinstance(w_value, space.w_int)):
        return VT_Integer, 0, numElements

    if space.is_true(space.isinstance(w_value, space.w_long)):
        return VT_LongInteger, 0, numElements

    if space.is_true(space.isinstance(w_value, space.w_float)):
        return VT_Float, 0, numElements

    # XXX cxBinary

    # XXX bool

    if space.is_true(space.isinstance(w_value, get(space).w_DateTimeType)):
        return VT_DateTime, 0, numElements

    if space.is_true(space.isinstance(w_value, get(space).w_DateType)):
        return VT_Date, 0, numElements

    # XXX Delta

    from pypy.module.oracle import interp_cursor
    if space.is_true(space.isinstance( # XXX is there an easier way?
        w_value,
        space.gettypeobject(interp_cursor.W_Cursor.typedef))):
        return VT_Cursor, 0, numElements

    if space.is_true(space.isinstance(w_value, get(space).w_DecimalType)):
        return VT_NumberAsString, 0, numElements

    # handle arrays
    if space.is_true(space.isinstance(w_value, space.w_list)):
        elements_w = space.listview(w_value)
        for w_element in elements_w:
            if not space.is_w(w_element, space.w_None):
                break
        else:
            w_element = space.w_None
        varType, size, _ = typeByValue(space, w_element, numElements)
        return varType, size, len(elements_w)

    raise OperationError(
        moduledict.w_NotSupportedError,
        space.wrap("Variable_TypeByValue(): unhandled data type %s" %
                   (space.type(w_value).getname(space, '?'),)))

def newByInputTypeHandler(space, cursor, w_inputTypeHandler, w_value, numElements):
    w_var = space.call(w_inputTypeHandler,
                       space.wrap(cursor),
                       w_value,
                       space.wrap(numElements))
    if not space.is_true(space.isinstance(w_var,
                                          get(space).w_Variable)):
        raise OperationError(
            space.w_TypeError,
            space.wrap("expecting variable from input type handler"))
    return space.interp_w(W_Variable, w_var)

def newVariableByValue(space, cursor, w_value, numElements):
    var = space.w_None

    if cursor.w_inputTypeHandler:
        var = newByInputTypeHandler(
            space, cursor, cursor.w_inputTypeHandler,
            w_value, numElements)
    elif cursor.connection.w_inputTypeHandler:
        var =  newByInputTypeHandler(
            space, cursor, cursor.connection.w_inputTypeHandler,
            w_value, numElements)

    if space.is_w(var, space.w_None):
        varType, size, numElements = typeByValue(space, w_value, numElements)
        var = varType(cursor, numElements, size)
        if space.is_true(space.isinstance(w_value, space.w_list)):
            var.makeArray(space)

    assert isinstance(var, W_Variable)
    return var

def newArrayVariableByType(space, cursor, w_value):
    "Allocate a new PL/SQL array by looking at the Python data type."

    w_type, w_numElements = space.fixedview(w_value, 2)

    numElements = space.int_w(w_numElements)
    varType = typeByPythonType(space, cursor, w_type)

    var = varType(cursor, numElements)
    var.makeArray(space)
    return var

def newVariableByType(space, cursor, w_value, numElements):
    # passing an integer is assumed to be a string
    if space.is_true(space.isinstance(w_value, space.w_int)):
        size = space.int_w(w_value)
        if size > config.MAX_STRING_CHARS:
            varType = VT_LongString
        else:
            varType = VT_String
        return varType(cursor, numElements, size)

    # passing an array of two elements define an array
    if space.is_true(space.isinstance(w_value, space.w_list)):
        return newArrayVariableByType(space, cursor, w_value)

    # handle directly bound variables
    if space.is_true(space.isinstance(w_value,
                                      get(space).w_Variable)):
        return space.interp_w(W_Variable, w_value)

    # everything else ought to be a Python type
    varType = typeByPythonType(space, cursor, w_value)
    return varType(cursor, numElements, varType.size)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.