django-mssql / sqlserver_ado / dbapi.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
"""A DB API 2.0 interface to SQL Server for Django

Forked from: adodbapi v2.1
Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole
* http://adodbapi.sourceforge.net/
* http://sourceforge.net/projects/pywin32/

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

* Version 2.1D by Adam Vandenberg, forked for Django backend use.
  This module is a db-api 2 interface for ADO, but is Django & SQL Server.
  It won't work against other ADO sources (like Access.)

DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/
"""

import sys
import time
import datetime
import re

try:
    import decimal
except ImportError:
    from django.utils import _decimal as decimal

from django.conf import settings
from django.db.utils import IntegrityError as DjangoIntegrityError, \
    DatabaseError as DjangoDatabaseError

try:
    from django.utils import timezone
except ImportError:
    # timezone added in Django 1.4
    timezone = None

import pythoncom
import win32com.client

from ado_consts import *

# DB API default values
apilevel = '2.0'

# 1: Threads may share the module, but not connections.
threadsafety = 1

# The underlying ADO library expects parameters as '?', but this wrapper
# expects '%s' parameters. This wrapper takes care of the conversion.
paramstyle = 'format'

# Set defaultIsolationLevel on module level before creating the connection.
# It may be one of "adXact..." consts.
defaultIsolationLevel = adXactReadCommitted

# Set defaultCursorLocation on module level before creating the connection.
# It may be one of the "adUse..." consts.
defaultCursorLocation = adUseServer

# Used for COM to Python date conversions.
_ordinal_1899_12_31 = datetime.date(1899,12,31).toordinal()-1
_milliseconds_per_day = 24*60*60*1000


class MultiMap(object):
    def __init__(self, mapping, default=None):
        """Defines a mapping with multiple keys per value.

        mapping is a dict of: tuple(key, key, key...) => value
        """
        self.storage = dict()
        self.default = default

        for keys, value in mapping.iteritems():
            for key in keys:
                self.storage[key] = value

    def __getitem__(self, key):
        return self.storage.get(key, self.default)


def standardErrorHandler(connection, cursor, errorclass, errorvalue):
    err = (errorclass, errorvalue)
    connection.messages.append(err)
    if cursor is not None:
        cursor.messages.append(err)
    raise errorclass(errorvalue)


class Error(StandardError): pass
class Warning(StandardError): pass

class InterfaceError(Error): pass

class DatabaseError(DjangoDatabaseError, Error): pass

class InternalError(DatabaseError): pass
class OperationalError(DatabaseError): pass
class ProgrammingError(DatabaseError): pass
class IntegrityError(DatabaseError, DjangoIntegrityError): pass
class DataError(DatabaseError): pass
class NotSupportedError(DatabaseError): pass

class FetchFailedError(Error): 
    """
    Error is used by RawStoredProcedureQuerySet to determine when a fetch
    failed due to a connection being closed or there is no record set 
    returned.
    """
    pass

class _DbType(object):
    def __init__(self,valuesTuple):
        self.values = valuesTuple

    def __eq__(self, other): return other in self.values
    def __ne__(self, other): return other not in self.values


def connect(connection_string, timeout=30, use_transactions=None):
    """Connect to a database.

    connection_string -- An ADODB formatted connection string, see:
        http://www.connectionstrings.com/?carrier=sqlserver2005
    timeout -- A command timeout value, in seconds (default 30 seconds)
    """
    try:
        pythoncom.CoInitialize()
        c = win32com.client.Dispatch('ADODB.Connection')
        c.CommandTimeout = timeout
        c.ConnectionString = connection_string
        c.Open()
        if use_transactions is None:
            useTransactions = _use_transactions(c)
        else:
            useTransactions = use_transactions
        return Connection(c, useTransactions)
    except Exception, e:
        raise OperationalError(e, "Error opening connection: " + connection_string)

def _use_transactions(c):
    """Return True if the given ADODB.Connection supports transactions."""
    for prop in c.Properties:
        if prop.Name == 'Transaction DDL':
            return prop.Value > 0
    return False

def format_parameters(parameters, show_value=False):
    """Format a collection of ADO Command Parameters.

    Used by error reporting in _execute_command.
    """
    directions = {
        0: 'Unknown',
        1: 'Input',
        2: 'Output',
        3: 'In/Out',
        4: 'Return',
    }

    if show_value:
        desc = [
            "Name: %s, Dir.: %s, Type: %s, Size: %s, Value: \"%s\", Precision: %s, NumericScale: %s" %\
            (p.Name, directions[p.Direction], adTypeNames.get(p.Type, str(p.Type)+' (unknown type)'), p.Size, p.Value, p.Precision, p.NumericScale)
            for p in parameters ]
    else:
        desc = [
            "Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s" %\
            (p.Name, directions[p.Direction], adTypeNames.get(p.Type, str(p.Type)+' (unknown type)'), p.Size, p.Precision, p.NumericScale)
            for p in parameters ]

    return '[' + ', '.join(desc) + ']'

def _configure_parameter(p, value):
    """Configure the given ADO Parameter 'p' with the Python 'value'."""
    if p.Direction not in [adParamInput, adParamInputOutput, adParamUnknown]:
        return

    if isinstance(value, basestring):
        p.Value = value
        p.Size = len(value)

    elif isinstance(value, buffer):
        p.Size = len(value)
        p.AppendChunk(value)

    elif isinstance(value, decimal.Decimal):
        p.Value = value
        exponent = value.as_tuple()[2]
        digit_count = len(value.as_tuple()[1])
        
        if exponent == 0:
            p.NumericScale = 0
            p.Precision =  digit_count
        elif exponent < 0:
            p.NumericScale = -exponent
            p.Precision = digit_count
            if p.Precision < p.NumericScale:
                p.Precision = p.NumericScale            
        elif exponent > 0:
            p.NumericScale = 0
            p.Precision = digit_count + exponent

    elif isinstance(value, datetime.time):
            p.Value = datetime.datetime(1,1,1, value.hour, value.minute, value.second)
    else:
        # For any other type, set the value and let pythoncom do the right thing.
        p.Value = value

    # Use -1 instead of 0 for empty strings and buffers
    if p.Size == 0:
        p.Size = -1

VERSION_SQL2005 = 9
VERSION_SQL2008 = 10

class Connection(object):
    def __init__(self, adoConn, useTransactions=False):
        self.adoConn = adoConn
        self.errorhandler = None
        self.messages = []
        self.adoConn.CursorLocation = defaultCursorLocation
        self.supportsTransactions = useTransactions

        self.adoConnProperties = dict([(x.Name, x.Value) for x in self.adoConn.Properties])

        if self.supportsTransactions:
            self.adoConn.IsolationLevel = defaultIsolationLevel
            self.adoConn.BeginTrans() # Disables autocommit per DBPAI

    @property
    def is_sql2005(self):
        v = self.adoConnProperties.get('DBMS Version', '')
        return v.startswith(unicode(VERSION_SQL2005))
    
    @property
    def is_sql2008(self):
        v = self.adoConnProperties.get('DBMS Version', '')
        return v.startswith(unicode(VERSION_SQL2008))

    def _raiseConnectionError(self, errorclass, errorvalue):
        eh = self.errorhandler
        if eh is None:
            eh = standardErrorHandler
        eh(self, None, errorclass, errorvalue)

    def _close_connection(self):
        """Close the underlying ADO Connection object, rolling back an active transaction if supported."""
        if self.supportsTransactions:
            self.adoConn.RollbackTrans()
        self.adoConn.Close()

    def close(self):
        """Close the database connection."""
        self.messages = []
        try:
            self._close_connection()
        except Exception, e:
            self._raiseConnectionError(InternalError, e)
        self.adoConn = None
        pythoncom.CoUninitialize()

    def commit(self):
        """Commit a pending transaction to the database.

        Note that if the database supports an auto-commit feature, this must
        be initially off.
        """
        self.messages = []
        if not self.supportsTransactions:
            return

        try:
            self.adoConn.CommitTrans()
            if not(self.adoConn.Attributes & adXactCommitRetaining):
                #If attributes has adXactCommitRetaining it performs retaining commits that is,
                #calling CommitTrans automatically starts a new transaction. Not all providers support this.
                #If not, we will have to start a new transaction by this command:
                self.adoConn.BeginTrans()
        except Exception, e:
            self._raiseConnectionError(Error, e)

    def rollback(self):
        """Abort a pending transaction."""
        self.messages = []
        if not self.supportsTransactions:
            self._raiseConnectionError(NotSupportedError, None)

        self.adoConn.RollbackTrans()
        if not(self.adoConn.Attributes & adXactAbortRetaining):
            #If attributes has adXactAbortRetaining it performs retaining aborts that is,
            #calling RollbackTrans automatically starts a new transaction. Not all providers support this.
            #If not, we will have to start a new transaction by this command:
            self.adoConn.BeginTrans()

    def cursor(self):
        """Return a new Cursor object using the current connection."""
        self.messages = []
        return Cursor(self)

    def printADOerrors(self):
        print 'ADO Errors (%i):' % self.adoConn.Errors.Count
        for e in self.adoConn.Errors:
            print 'Description: %s' % e.Description
            print 'Error: %s %s ' % (e.Number, adoErrors.get(e.Number, "unknown"))
            if e.Number == ado_error_TIMEOUT:
                print 'Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)'
            print 'Source: %s' % e.Source
            print 'NativeError: %s' % e.NativeError
            print 'SQL State: %s' % e.SQLState
            
    def _suggest_error_class(self):
        """Introspect the current ADO Errors and determine an appropriate error class.
        
        Error.SQLState is a SQL-defined error condition, per the SQL specification:
        http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt
        
        The 23000 class of errors are integrity errors.
        Error 40002 is a transactional integrity error.
        """
        if self.adoConn is not None:
            for e in self.adoConn.Errors:
                state = str(e.SQLState)
                if state.startswith('23') or state=='40002':
                    return IntegrityError
            
        return DatabaseError

    def __del__(self):
        try:
            self._close_connection()
        except: pass
        self.adoConn = None


class Cursor(object):
##    This read-only attribute is a sequence of 7-item sequences.
##    Each of these sequences contains information describing one result column:
##        (name, type_code, display_size, internal_size, precision, scale, null_ok).
##    This attribute will be None for operations that do not return rows or if the
##    cursor has not had an operation invoked via the executeXXX() method yet.
##    The type_code can be interpreted by comparing it to the Type Objects specified in the section below.
    description = None

##    This read-only attribute specifies the number of rows that the last executeXXX() produced
##    (for DQL statements like select) or affected (for DML statements like update or insert).
##    The attribute is -1 in case no executeXXX() has been performed on the cursor or
##    the rowcount of the last operation is not determinable by the interface.[7]
##    NOTE: -- adodbapi returns "-1" by default for all select statements
    rowcount = -1

    # Arraysize specifies the number of rows to fetch at a time with fetchmany().
    arraysize = 1

    def __init__(self, connection):
        self.messages = []
        self.connection = connection
        self.rs = None
        self.description = None
        self.errorhandler = connection.errorhandler

    def __iter__(self):
        return iter(self.fetchone, None)
        
    def __enter__(self):
        "Allow database cursors to be used with context managers."
        return self
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        "Allow database cursors to be used with context managers."
        self.close()

    def _raiseCursorError(self, errorclass, errorvalue):
        eh = self.errorhandler
        if eh is None:
            eh = standardErrorHandler
        eh(self.connection, self, errorclass, errorvalue)

    def _description_from_recordset(self, recordset):
    	# Abort if closed or no recordset.
        if (recordset is None) or (recordset.State == adStateClosed):
            self.rs = None
            self.description = None
            return

        # Since we use a forward-only cursor, rowcount will always return -1
        self.rowcount = -1
        self.rs = recordset
        desc = list()
        
        for f in self.rs.Fields:
            display_size = None
            if not(self.rs.EOF or self.rs.BOF):
                display_size = f.ActualSize

            null_ok = bool(f.Attributes & adFldMayBeNull)

            desc.append( (f.Name, f.Type, display_size, f.DefinedSize, f.Precision, f.NumericScale, null_ok) )
            
        self.description = desc

    def close(self):
        """Close the cursor."""
        self.messages = []
        self.connection = None
        if self.rs and self.rs.State != adStateClosed:
            self.rs.Close()
            self.rs = None

    def _new_command(self, command_type=adCmdText):
        self.cmd = None
        self.messages = []

        if self.connection is None:
            self._raiseCursorError(Error, None)
            return

        try:
            self.cmd = win32com.client.Dispatch("ADODB.Command")
            self.cmd.ActiveConnection = self.connection.adoConn
            self.cmd.CommandTimeout = self.connection.adoConn.CommandTimeout
            self.cmd.CommandType = command_type
        except:
            self._raiseCursorError(DatabaseError, None)

    def _execute_command(self):
        # Sprocs may have an integer return value
        self.return_value = None

        try:
            recordset = self.cmd.Execute()
            self.rowcount = recordset[1]
            self._description_from_recordset(recordset[0])
        except Exception, e:
            _message = ""
            if hasattr(e, 'args'): _message += str(e.args)+"\n"
            _message += "Command:\n%s\nParameters:\n%s" %  (self.cmd.CommandText, format_parameters(self.cmd.Parameters, True))
            klass = self.connection._suggest_error_class()
            self._raiseCursorError(klass, _message)


    def callproc(self, procname, parameters=None):
        """Call a stored database procedure with the given name.

        The sequence of parameters must contain one entry for each
        argument that the sproc expects. The result of the
        call is returned as modified copy of the input
        sequence. Input parameters are left untouched, output and
        input/output parameters replaced with possibly new values.

        The sproc may also provide a result set as output,
        which is available through the standard .fetch*() methods.

        Extension: A "return_value" property may be set on the
        cursor if the sproc defines an integer return value.
        """
        self._new_command(adCmdStoredProc)
        self.cmd.CommandText = procname
        self.cmd.Parameters.Refresh()

        try:
            # Return value is 0th ADO parameter. Skip it.
            for i, p in enumerate(tuple(self.cmd.Parameters)[1:]):
                _configure_parameter(p, parameters[i])
        except:
            _message = u'Converting Parameter %s: %s, %s\n' %\
                (p.Name, ado_type_name(p.Type), repr(parameters[i]))

            self._raiseCursorError(DataError, _message)

        self._execute_command()

        p_return_value = self.cmd.Parameters(0)
        self.return_value = _convert_to_python(p_return_value.Value, p_return_value.Type)

        return [_convert_to_python(p.Value, p.Type)
            for p in tuple(self.cmd.Parameters)[1:] ]


    def execute(self, operation, parameters=None):
        """Prepare and execute a database operation (query or command).

        Return value is not defined.
        """
        self._new_command()

        if parameters is None:
            parameters = list()

        parameter_replacements = list()
        for i, value in enumerate(parameters):
            if value is None:
                parameter_replacements.append('NULL')
                continue
                
            if isinstance(value, basestring) and value == "":
                parameter_replacements.append("''")
                continue

            # Otherwise, process the non-NULL, non-empty string parameter.
            parameter_replacements.append('?')
            try:
                p = self.cmd.CreateParameter('p%i' % i, _ado_type(value))
            except KeyError:
                _message = u'Failed to map python type "%s" to an ADO type' % (value.__class__.__name__,)
                self._raiseCursorError(DataError, _message)
            except:
                _message = u'Creating Parameter p%i, %s' % (i, _ado_type(value))
                self._raiseCursorError(DataError, _message)

            try:
                _configure_parameter(p, value)
                self.cmd.Parameters.Append(p)
            except Exception as e:
                _message = u'Converting Parameter %s: %s, %s\n' %\
                    (p.Name, ado_type_name(p.Type), repr(value))

                self._raiseCursorError(DataError, _message)

        # Replace params with ? or NULL
        if parameter_replacements:
            operation = operation % tuple(parameter_replacements)

        self.cmd.CommandText = operation
        self._execute_command()

    def executemany(self, operation, seq_of_parameters):
        """Execute the given command against all parameter sequences or mappings given in seq_of_parameters."""
        self.messages = list()
        total_recordcount = 0

        for params in seq_of_parameters:
            self.execute(operation, params)

            if self.rowcount == -1:
                total_recordcount = -1

            if total_recordcount != -1:
                total_recordcount += self.rowcount

        self.rowcount = total_recordcount

    def _fetch(self, rows=None):
        """Fetch rows from the current recordset.

        rows -- Number of rows to fetch, or None (default) to fetch all rows.
        """
        if self.connection is None or self.rs is None:
            self._raiseCursorError(FetchFailedError, 'Attempting to fetch from a closed connection or empty record set')
            return

        if self.rs.State == adStateClosed or self.rs.BOF or self.rs.EOF:
            if rows == 1: # fetchone returns None
                return None
            else: # fetchall and fetchmany return empty lists
                return list()

        if rows:
            ado_results = self.rs.GetRows(rows)
        else:
            ado_results = self.rs.GetRows()

        py_columns = list()
        column_types = [column_desc[1] for column_desc in self.description]
        for ado_type, column in zip(column_types, ado_results):
            py_columns.append( [_convert_to_python(cell, ado_type) for cell in column] )

        return tuple(zip(*py_columns))

    def fetchone(self):
        """Fetch the next row of a query result set, returning a single sequence, or None when no more data is available.

        An Error (or subclass) exception is raised if the previous call to executeXXX()
        did not produce any result set or no call was issued yet.
        """
        self.messages = list()
        result = self._fetch(1)
        if result: # return record (not list of records)
            return result[0]
        return None

    def fetchmany(self, size=None):
        """Fetch the next set of rows of a query result, returning a list of tuples. An empty sequence is returned when no more rows are available."""
        self.messages = list()
        if size is None:
            size = self.arraysize
        return self._fetch(size)

    def fetchall(self):
        """Fetch all remaining rows of a query result, returning them as a sequence of sequences."""
        self.messages = list()
        return self._fetch()

    def nextset(self):
        """Skip to the next available recordset, discarding any remaining rows from the current recordset.

        If there are no more sets, the method returns None. Otherwise, it returns a true
        value and subsequent calls to the fetch methods will return rows from the next result set.
        """
        self.messages = list()
        if self.connection is None or self.rs is None:
            self._raiseCursorError(Error, None)
            return None

        recordset = self.rs.NextRecordset()[0]
        if recordset is None:
            return None
            
        self._description_from_recordset(recordset)
        return True

    def setinputsizes(self, sizes): pass
    def setoutputsize(self, size, column=None): pass

# Type specific constructors as required by the DB-API 2 specification.
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
Binary = buffer

def DateFromTicks(ticks):
    """Construct an object holding a date value from the given # of ticks."""
    return Date(*time.localtime(ticks)[:3])

def TimeFromTicks(ticks):
    """Construct an object holding a time value from the given # of ticks."""
    return Time(*time.localtime(ticks)[3:6])

def TimestampFromTicks(ticks):
    """Construct an object holding a timestamp value from the given # of ticks."""
    return Timestamp(*time.localtime(ticks)[:6])

adoIntegerTypes = (adInteger,adSmallInt,adTinyInt,adUnsignedInt,adUnsignedSmallInt,adUnsignedTinyInt,adError)
adoRowIdTypes = (adChapter,)
adoLongTypes = (adBigInt, adUnsignedBigInt, adFileTime)
adoExactNumericTypes = (adDecimal, adNumeric, adVarNumeric, adCurrency)
adoApproximateNumericTypes = (adDouble, adSingle)
adoStringTypes = (adBSTR,adChar,adLongVarChar,adLongVarWChar,adVarChar,adVarWChar,adWChar,adGUID)
adoBinaryTypes = (adBinary, adLongVarBinary, adVarBinary)
adoDateTimeTypes = (adDBTime, adDBTimeStamp, adDate, adDBDate)

# Required DBAPI type specifiers
STRING   = _DbType(adoStringTypes)
BINARY   = _DbType(adoBinaryTypes)
NUMBER   = _DbType((adBoolean,) + adoIntegerTypes + adoLongTypes + adoExactNumericTypes + adoApproximateNumericTypes)
DATETIME = _DbType(adoDateTimeTypes)
# Not very useful for SQL Server, as normal row ids are usually just integers.
ROWID    = _DbType(adoRowIdTypes)


# Mapping ADO data types to Python objects.
def _convert_to_python(variant, adType):
    if variant is None:
        return None
    return _variantConversions[adType](variant)

def _cvtDecimal(variant):
    return _convertNumberWithCulture(variant, decimal.Decimal)

def _cvtFloat(variant):
    return _convertNumberWithCulture(variant, float)

def _convertNumberWithCulture(variant, f):
    try:
        return f(variant)
    except (ValueError,TypeError,decimal.InvalidOperation):
        try:
            europeVsUS = str(variant).replace(",",".")
            return f(europeVsUS)
        except (ValueError,TypeError): pass

def _cvtComDate(comDate):
    date_as_float = float(comDate)
    day_count = int(date_as_float)
    fraction_of_day = abs(date_as_float - day_count)

    dt = (datetime.datetime.fromordinal(day_count + _ordinal_1899_12_31) +
        datetime.timedelta(milliseconds=fraction_of_day * _milliseconds_per_day))
    
    if timezone and getattr(settings, 'USE_TZ', False):
        dt = dt.replace(tzinfo=timezone.utc)
    return dt

_variantConversions = MultiMap(
    {
        adoDateTimeTypes : _cvtComDate,
        adoExactNumericTypes: _cvtDecimal,
        adoApproximateNumericTypes: _cvtFloat,
        (adBoolean,): bool,
        adoLongTypes+adoRowIdTypes : long,
        adoIntegerTypes: int,
        adoBinaryTypes: buffer, 
    }, 
    lambda x: x)

# Mapping Python data types to ADO type codes
def _ado_type(data):
    if isinstance(data, basestring):
        return adBSTR
    return _map_to_adotype[type(data)]

_map_to_adotype = {
    buffer: adBinary,
    float: adDouble,
    int: adInteger,
    long: adBigInt,
    bool: adBoolean,
    decimal.Decimal: adDecimal,
    datetime.date: adDate,
    datetime.datetime: adDate,
    datetime.time: adDate, 
}
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.