Django

Code

Ticket #87: oracle.py

File oracle.py, 5.1 kB (added by Jason Huggins, 3 years ago)

New db backend for Oracle.

Line 
1 """
2 Oracle database backend for Django.
3
4 Requires cx_Oracle: http://www.computronix.com/utilities.shtml
5 """
6
7 from django.core.db import base, typecasts
8 import cx_Oracle  as Database
9
10 #needed for fetchone, fetchmany, fetchall support
11 from django.core.db.dicthelpers import *
12
13
14 DatabaseError = Database.DatabaseError
15
16 class DatabaseWrapper:
17     def __init__(self):
18         self.connection = None
19         self.queries = []
20
21     def cursor(self):
22         from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PASSWORD, DEBUG
23         if self.connection is None:
24             if DATABASE_NAME == '' or DATABASE_USER == '' or DATABASE_PASSWORD == '':
25                 from django.core.exceptions import ImproperlyConfigured
26                 raise ImproperlyConfigured, "You need to specify DATABASE_NAME, DATABASE_USER, and DATABASE_PASSWORD in your Django settings file."
27             conn_string = "%s/%s@%s" % (DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)
28             self.connection = Database.connect(conn_string)               
29         return FormatStylePlaceholderCursor(self.connection)
30
31     def commit(self):
32         self.connection.commit()
33
34     def rollback(self):
35         if self.connection:
36             self.connection.rollback()
37
38     def close(self):
39         if self.connection is not None:
40             self.connection.close()
41             self.connection = None
42
43 class FormatStylePlaceholderCursor(Database.Cursor):
44     """
45     Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var" style.
46     This fixes it -- but note that if you want to use a literal "%s" in a query,
47     you'll need to use "%%s" (which I belive is true of other wrappers as well).
48     """
49    
50     def execute(self, query, params=[]):
51         query = self.convert_arguments(query, len(params))
52         return Database.Cursor.execute(self, query, params)
53        
54     def executemany(self, query, params=[]):         
55         query = self.convert_arguments(query, len(params[0]))
56         return Database.Cursor.executemany(self, query, params)
57        
58     def convert_arguments(self, query, num_params):
59         # replace occurances of "%s" with ":arg" - Oracle requires colons for parameter placeholders.
60         args = [':arg' for i in range(num_params)]
61         return query % tuple(args)
62
63 def get_last_insert_id(cursor, table_name, pk_name):
64     query = "SELECT %s_sq.currval from dual" % table_name
65     cursor.execute(query)
66     return cursor.fetchone()[0]
67
68 def get_date_extract_sql(lookup_type, table_name):
69     raise NotImplementedError
70
71 def get_date_trunc_sql(lookup_type, field_name):
72     raise NotImplementedError
73    
74 def get_table_list(cursor):
75     "Returns a list of table names in the current database."
76     raise NotImplementedError
77
78 def get_relations(cursor, table_name):
79     """
80     Returns a dictionary of {field_index: (field_index_other_table, other_table)}
81     representing all relationships to the given table. Indexes are 0-based.
82     """
83     raise NotImplementedError
84
85
86 OPERATOR_MAPPING = {
87     'exact': '=',
88     'iexact': 'LIKE',
89     'contains': 'LIKE',
90     'icontains': 'LIKE',
91     'ne': '!=',
92     'gt': '>',
93     'gte': '>=',
94     'lt': '<',
95     'lte': '<=',
96     'startswith': 'LIKE',
97     'endswith': 'LIKE',
98     'istartswith': 'LIKE',
99     'iendswith': 'LIKE',
100 }
101
102 # This dictionary maps Field objects to their associated MySQL column
103 # types, as strings. Column-type strings can contain format strings; they'll
104 # be interpolated against the values of Field.__dict__ before being output.
105 # If a column type is set to None, it won't be included in the output.
106 DATA_TYPES = {
107     'AutoField':         'number(38)',
108     'BooleanField':      'number(1)',
109     'CharField':         'varchar2(%(maxlength)s)',
110     'CommaSeparatedIntegerField': 'varchar2(%(maxlength)s)',
111     'DateField':         'date',
112     'DateTimeField':     'date',
113     'EmailField':        'varchar2(75)',
114     'FileField':         'varchar2(100)',
115     'FloatField':        'number(%(max_digits)s, %(decimal_places)s)',
116     'ImageField':        'varchar2(100)',
117     'IntegerField':      'integer',
118     'IPAddressField':    'char(15)',
119     'ManyToManyField':   None,
120     'NullBooleanField':  'integer',
121     'OneToOneField':     'integer',
122     'PhoneNumberField':  'varchar(20)',
123     'PositiveIntegerField': 'integer',
124     'PositiveSmallIntegerField': 'smallint',
125     'SlugField':         'varchar(50)',
126     'SmallIntegerField': 'smallint',
127     'TextField':         'long',
128     'TimeField':         'timestamp',
129     'URLField':          'varchar(200)',
130     'USStateField':      'varchar(2)',
131     'XMLField':          'long',
132 }
133
134 # Maps type codes to Django Field types.
135 DATA_TYPES_REVERSE = {
136     16: 'BooleanField',
137     21: 'SmallIntegerField',
138     23: 'IntegerField',
139     25: 'TextField',
140     869: 'IPAddressField',
141     1043: 'CharField',
142     1082: 'DateField',
143     1083: 'TimeField',
144     1114: 'DateTimeField',
145     1184: 'DateTimeField',
146     1266: 'TimeField',
147     1700: 'FloatField',
148 }
149
150 EMPTY_STR_EQUIV = ' '