adamv avatar adamv committed 90c2b9d

- Changed column types to unicode (nvarchar) where appropriate

Comments (0)

Files changed (2)

src/sqlserver_ado/adodb_django.py

 import datetime
 import re
 
-rx_datetime=re.compile(r'^(\d{4}-\d\d?-\d\d? \d\d?:\d\d?:\d\d?.\d{3})\d{3}$')
+rx_datetime = re.compile(r'^(\d{4}-\d\d?-\d\d? \d\d?:\d\d?:\d\d?.\d{3})\d{3}$')
 
 try:
     import decimal
 # 3... = Really really on for real
 verbose = False
 
-defaultIsolationLevel=adXactReadCommitted
+defaultIsolationLevel = adXactReadCommitted
 #  Set defaultIsolationLevel on module level before creating the connection.
 #   It may be one of "adXact..." consts.
 #   if you simply "import adodbapi", you'll say:
 #   "adodbapi.adodbapi.defaultIsolationLevel=adodbapi.adodbapi.adXactBrowse", for example
 
-defaultCursorLocation=adUseServer
+defaultCursorLocation = adUseServer
 #  Set defaultCursorLocation on module level before creating the connection.
 #   It may be one of the "adUse..." consts.
 
 def connect(connstr, timeout=30):
     "Connection string as in the ADO documentation, SQL timeout in seconds"
     pythoncom.CoInitialize()
-    conn=win32com.client.Dispatch('ADODB.Connection')
-    conn.CommandTimeout=timeout
-    conn.ConnectionString=connstr
+    conn = win32com.client.Dispatch('ADODB.Connection')
+    conn.CommandTimeout = timeout
+    conn.ConnectionString = connstr
 
     _logger('%s attempting: "%s"' % (version,connstr))
     try:
         return Cursor(self)
 
     def printADOerrors(self):
-        error_count = self.adoConn.Errors.Count
-        print 'ADO Errors:(%i)' % error_count
-        for i in range(error_count):
-            e = self.adoConn.Errors(i)
+        print 'ADO Errors:(%i)' % self.adoConn.Errors.Count
+        for e in self.adoConn.Errors:
             print 'Description: %s' % e.Description
             print 'Number: %s ' % e.Number
-            try:
-                print 'Number constant:' % adoErrors[e.Number]
-            except:
-                pass
-            print 'Source: %s' %e.Source
-            print 'NativeError: %s' %e.NativeError
-            print 'SQL State: %s' %e.SQLState
+            print 'Number constant:' % adoErrors.get(e.Number, "unknown")
+            print 'Source: %s' % e.Source
+            print 'NativeError: %s' % e.NativeError
+            print 'SQL State: %s' % e.SQLState
             if e.Number == ado_error_TIMEOUT:
                 print ' Error means that the Query timed out.\n Try using adodbpi.connect(constr,timeout=Nseconds)'
 
 
 def _log_parameters(parameters):
     """Log parameters for debugging queries."""
-    for i in range(parameters.Count):
-        param = parameters(i)
+    for param in parameters:
         print 'adodbapi parameter attributes before=', param.Name, param.Type, param.Direction, param.Size
 
 def _findReturnValueIndex(isStoredProcedureCall, parameters):
 	if not isStoredProcedureCall:
 		return -1
 		
-	if parameters.Count != len(parameters):
-		for i in range(parameters.Count):
-			if parameters(i).Direction == adParamReturnValue:
-				return i
-	return -1;
-        
+	if parameters.Count == len(parameters):
+		return -1
+		
+	for i,param in enumerate(parameters):
+		if param.Direction == adParamReturnValue:
+			return i
+			
+	return -1
+
 class Cursor(object):
     description = None
 ##    This read-only attribute is a sequence of 7-item sequences.
     if type(variant) == bool and adType == adBoolean:
         return variant
 
-    res = variantConversions[adType](variant)
+    converted = variantConversions[adType](variant)
     
-    # If the type is float, but there is no decimal part,
-    # then return an integer. 
+    # If the type is float, but there is no decimal part, then return an integer. 
     # --Adam V: Why does Django want this?
-    if type(res) == float and str(res)[-2:] == ".0":
-        return int(res) # If float but int, then int.
+    if type(converted) == float and str(converted)[-2:] == ".0":
+        return int(converted) # If float but int, then int.
 
-    return res
+    return converted
 
 
 class DBAPITypeObject:
 
 def identity(x): return x
 
-class VariantConversionMap(dict):
-    def __init__(self, aDict):
-        for k, v in aDict.iteritems():
-            self[k] = v # we must call __setitem__
-
-    def __setitem__(self, adoType, cvtFn):
-        "don't make adoType a string :-)"
-        try: # user passed us a tuple, set them individually
-           for type in adoType:
-               dict.__setitem__(self, type, cvtFn)
-        except TypeError: # single value
-           dict.__setitem__(self, adoType, cvtFn)
-
-    def __getitem__(self, fromType):
-        try:
-            return dict.__getitem__(self, fromType)
-        except KeyError:
-            return identity
-
 mapPythonTypesToAdoTypes = {
 	buffer: adBinary,
 	float: adNumeric,
 	datetime.time: adDate,
 }
 
+class VariantConversionMap(object):
+    def __init__(self, mapping):
+    	self.storage = dict()
+    	
+    	# mapping is a dict of tuple(ado Type) => convert function
+    	for adoType_list, convert_function in mapping.iteritems():
+    		for adoType in adoType_list:
+    			self.storage[adoType] = convert_function
+
+    def __getitem__(self, key):
+    	return self.storage.get(key, identity)
+
 variantConversions = VariantConversionMap({
     adoDateTimeTypes : datetimeFromCOMDate,
     adoApproximateNumericTypes: cvtFloat,
-    adCurrency: cvtCurrency,
+    (adCurrency,): cvtCurrency,
     adoExactNumericTypes: identity, # use cvtNumeric to force decimal rather than unicode
     adoLongTypes : long,
     adoIntegerTypes: int,

src/sqlserver_ado/creation.py

 DATA_TYPES = {
     'AutoField':         'int IDENTITY (1, 1)',
     'BooleanField':      'bit',
-    'CharField':         'varchar(%(max_length)s)',
-    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
+    'CharField':         'nvarchar(%(max_length)s)',
+    'CommaSeparatedIntegerField': 'nvarchar(%(max_length)s)',
     'DateField':         'datetime',
     'DateTimeField':     'datetime',
     'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)',
-    'FileField':         'varchar(%(max_length)s)',
-    'FilePathField':     'varchar(%(max_length)s)',
+    'FileField':         'nvarchar(%(max_length)s)',
+    'FilePathField':     'nvarchar(%(max_length)s)',
     'FloatField':        'double precision',
-    'ImageField':        'varchar(%(max_length)s)',
+    'ImageField':        'nvarchar(%(max_length)s)',
     'IntegerField':      'int',
-    'IPAddressField':    'char(15)',
+    'IPAddressField':    'nvarchar(15)',
     'NullBooleanField':  'bit',
     'OneToOneField':     'int',
-    'PhoneNumberField':  'varchar(20)',
+    'PhoneNumberField':  'nvarchar(20)',
     'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)',
     'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)',
-    'SlugField':         'varchar(%(max_length)s)',
+    'SlugField':         'nvarchar(%(max_length)s)',
     'SmallIntegerField': 'smallint',
-    'TextField':         'varchar(max)', # SQL Server 2005 and up!
+    'TextField':         'nvarchar(max)', # SQL Server 2005 and up!
     'TimeField':         'time',
-    'USStateField':      'char(2)',
+    'USStateField':      'nchar(2)',
 }
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.