Index: db/models/base.py
===================================================================
--- db/models/base.py	(revision 3545)
+++ db/models/base.py	(working copy)
@@ -171,8 +171,9 @@
         record_exists = True
         if pk_set:
             # Determine whether a record with the primary key already exists.
-            cursor.execute("SELECT 1 FROM %s WHERE %s=%%s LIMIT 1" % \
-                (backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column)), [pk_val])
+            lim = settings.DATABASE_ENGINE != 'oracle' and ' LIMIT 1' or ''
+            cursor.execute("SELECT 1 FROM %s WHERE %s=%%s %s" % \
+                (backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column), lim), [pk_val])
             # If it does already exist, do an UPDATE.
             if cursor.fetchone():
                 db_values = [f.get_db_prep_save(f.pre_save(self, False)) for f in non_pks]
Index: db/models/fields/__init__.py
===================================================================
--- db/models/fields/__init__.py	(revision 3545)
+++ db/models/fields/__init__.py	(working copy)
@@ -158,6 +158,10 @@
 
     def get_db_prep_save(self, value):
         "Returns field's value prepared for saving into a database."
+        # Oracle treats empty strings ('') the same as NULLs. 
+        # To get around this wart, we need to change it to something else... 
+        if settings.DATABASE_ENGINE == 'oracle' and  value == '':
+            value = ' '
         return value
 
     def get_db_prep_lookup(self, lookup_type, value):
@@ -449,7 +453,9 @@
     def get_db_prep_save(self, value):
         # Casts dates into string format for entry into database.
         if value is not None:
-            value = value.strftime('%Y-%m-%d')
+            if settings.DATABASE_ENGINE != 'oracle':
+                #Oracle does not need a string conversion
+                value = value.strftime('%Y-%m-%d')
         return Field.get_db_prep_save(self, value)
 
     def get_manipulator_field_objs(self):
@@ -479,14 +485,18 @@
     def get_db_prep_save(self, value):
         # Casts dates into string format for entry into database.
         if value is not None:
-            # MySQL will throw a warning if microseconds are given, because it
+            # MySQL/Oracle will throw a warning if microseconds are given, because it
             # doesn't support microseconds.
-            if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'):
+            if (settings.DATABASE_ENGINE == 'mysql' or settings.DATABASE_ENGINE=='oracle') and hasattr(value, 'microsecond'):
                 value = value.replace(microsecond=0)
             value = str(value)
         return Field.get_db_prep_save(self, value)
 
     def get_db_prep_lookup(self, lookup_type, value):
+        # Oracle will throw an error if microseconds are given, because it
+        # doesn't support microseconds.
+        if (settings.DATABASE_ENGINE=='oracle') and hasattr(value, 'microsecond'):
+            value = value.replace(microsecond=0)
         if lookup_type == 'range':
             value = [str(v) for v in value]
         else:
@@ -514,8 +524,13 @@
     def flatten_data(self,follow, obj = None):
         val = self._get_val_from_obj(obj)
         date_field, time_field = self.get_manipulator_field_names('')
-        return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''),
-                time_field: (val is not None and val.strftime("%H:%M:%S") or '')}
+        #cx_Oracle does not support strftime
+        if (settings.DATABASE_ENGINE=='oracle'):
+            return {date_field: (val is not None or ''),
+                    time_field: (val is not None or '')}
+	else:
+            return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''),
+                    time_field: (val is not None and val.strftime("%H:%M:%S") or '')}
 
 class EmailField(CharField):
     def __init__(self, *args, **kwargs):
@@ -747,7 +762,11 @@
             # doesn't support microseconds.
             if settings.DATABASE_ENGINE == 'mysql':
                 value = value.replace(microsecond=0)
-            value = str(value)
+                value = str(value)
+            elif settings.DATABASE_ENGINE == 'oracle':
+                value = value.replace(microsecond=0)
+            else:
+                value = str(value)
         return Field.get_db_prep_save(self, value)
 
     def get_manipulator_field_objs(self):
Index: db/models/query.py
===================================================================
--- db/models/query.py	(revision 3545)
+++ db/models/query.py	(working copy)
@@ -3,6 +3,7 @@
 from django.db.models import signals
 from django.dispatch import dispatcher
 from django.utils.datastructures import SortedDict
+from django.conf import settings
 import operator
 import re
 
@@ -168,8 +169,12 @@
         extra_select = self._select.items()
 
         cursor = connection.cursor()
-        select, sql, params = self._get_sql_clause()
-        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
+        select, sql, params, full_query = self._get_sql_clause() 
+
+        if not full_query: 
+            cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) 
+        else: 
+            cursor.execute(full_query, params) 
         fill_cache = self._select_related
         index_end = len(self.model._meta.fields)
         while 1:
@@ -192,7 +197,7 @@
         counter._offset = None
         counter._limit = None
         counter._select_related = False
-        select, sql, params = counter._get_sql_clause()
+        select, sql, params, full_query = counter._get_sql_clause() 
         cursor = connection.cursor()
         if self._distinct:
             id_col = "%s.%s" % (backend.quote_name(self.model._meta.db_table),
@@ -501,13 +506,48 @@
             sql.append("ORDER BY " + ", ".join(order_by))
 
         # LIMIT and OFFSET clauses
-        if self._limit is not None:
-            sql.append("%s " % backend.get_limit_offset_sql(self._limit, self._offset))
+        if (settings.DATABASE_ENGINE != 'oracle'):             
+            if self._limit is not None:
+                sql.append("%s " % backend.get_limit_offset_sql(self._limit, self._offset))
+            else:
+                assert self._offset is None, "'offset' is not allowed without 'limit'"
+
+            return select, " ".join(sql), params
         else:
-            assert self._offset is None, "'offset' is not allowed without 'limit'"
+            # To support limits and offsets, Oracle requires some funky rewriting of an otherwise normal looking query. 
+            select_clause = ",".join(select) 
+            distinct = (self._distinct and "DISTINCT " or "") 
 
-        return select, " ".join(sql), params
+            if order_by:  
+                order_by_clause = " OVER (ORDER BY %s )" % (", ".join(order_by)) 
+            else:
+                #Oracle's row_number() function always requires an order-by clause. 
+                #So we need to define a default order-by, since none was provided. 
+                order_by_clause = " OVER (ORDER BY %s.%s)" % \
+                    (backend.quote_name(opts.db_table),  
+                    backend.quote_name(opts.fields[0].db_column or opts.fields[0].column)) 
+            # limit_and_offset_clause 
+            offset = self._offset and int(self._offset) or 0 
+            limit = self._limit and int(self._limit) or None 
+            limit_and_offset_clause = '' 
+            if limit: 
+                limit_and_offset_clause = "WHERE rn > %s AND rn <= %s" % (offset, limit+offset) 
+            elif offset:
+                limit_and_offset_clause = "WHERE rn > %s" % (offset) 
 
+            if len(limit_and_offset_clause) > 0: 
+                full_query = """SELECT * FROM  
+                    (SELECT %s    
+                    %s, 
+                    ROW_NUMBER() %s AS rn 
+                    %s 
+                    ) 
+                    %s 
+                    """ % (distinct, select_clause, order_by_clause, " ".join(sql), limit_and_offset_clause)
+            else:
+                full_query = None 
+             
+            return select, " ".join(sql), params, full_query
 class ValuesQuerySet(QuerySet):
     def iterator(self):
         # select_related and select aren't supported in values().
@@ -523,7 +563,7 @@
             field_names = [f.attname for f in self.model._meta.fields]
 
         cursor = connection.cursor()
-        select, sql, params = self._get_sql_clause()
+        select, sql, params, full_query = self._get_sql_clause() 
         select = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns]
         cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
         while 1:
@@ -636,6 +676,9 @@
     if table_prefix.endswith('.'):
         table_prefix = backend.quote_name(table_prefix[:-1])+'.'
     field_name = backend.quote_name(field_name)
+    #put some oracle exceptions here 
+    if lookup_type == "icontains" and settings.DATABASE_ENGINE == 'oracle': 
+        return 'lower(%s%s) %s' % (table_prefix, field_name, (backend.OPERATOR_MAPPING[lookup_type] % '%s')) 
     try:
         return '%s%s %s' % (table_prefix, field_name, (backend.OPERATOR_MAPPING[lookup_type] % '%s'))
     except KeyError:
@@ -667,6 +710,7 @@
     Helper function that recursively populates the select, tables and where (in
     place) for select_related queries.
     """
+    from django.db.models.fields import AutoField 
     qn = backend.quote_name
     for f in opts.fields:
         if f.rel and not f.null:
@@ -680,7 +724,10 @@
             cache_tables_seen.append(db_table)
             where.append('%s.%s = %s.%s' % \
                 (qn(old_prefix), qn(f.column), qn(db_table), qn(f.rel.get_related_field().column)))
-            select.extend(['%s.%s' % (qn(db_table), qn(f2.column)) for f2 in f.rel.to._meta.fields])
+            if settings.DATABASE_ENGINE == 'oracle':
+                select.extend(['%s.%s' % (backend.quote_name(db_table), backend.quote_name(f2.column)) for f2 in f.rel.to._meta.fields if not isinstance(f2, AutoField)]) 
+            else:
+                select.extend(['%s.%s' % (backend.quote_name(db_table), backend.quote_name(f2.column)) for f2 in f.rel.to._meta.fields]) 
             fill_table_cache(f.rel.to._meta, select, tables, where, db_table, cache_tables_seen)
 
 def parse_lookup(kwarg_items, opts):
Index: db/backends/oracle/base.py
===================================================================
--- db/backends/oracle/base.py	(revision 3545)
+++ db/backends/oracle/base.py	(working copy)
@@ -39,6 +39,10 @@
             else:
                 conn_string = "%s/%s@%s" % (settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME)
                 self.connection = Database.connect(conn_string)
+        # set oracle date to ansi date format
+        cursor =  self.connection.cursor()
+        cursor.execute("alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'")
+        cursor.close()					     
         return FormatStylePlaceholderCursor(self.connection)
 
     def _commit(self):
@@ -67,11 +71,19 @@
     def execute(self, query, params=None):
         if params is None: params = []
         query = self.convert_arguments(query, len(params))
-        return Database.Cursor.execute(self, query, params)
+        # cx can not execute the query with the closing ';' 
+        if query.endswith(';') :
+            query = query[0:len(query)-1]			
+	print query
+	print params	
+	return Database.Cursor.execute(self, query, params)
 
     def executemany(self, query, params=None):
         if params is None: params = []
         query = self.convert_arguments(query, len(params[0]))
+        # cx can not execute the query with the closing ';' 
+        if query.endswith(';') :
+            query = query[0:len(query)-1]						    
         return Database.Cursor.executemany(self, query, params)
 
     def convert_arguments(self, query, num_params):
Index: core/management.py
===================================================================
--- core/management.py	(revision 3545)
+++ core/management.py	(working copy)
@@ -6,6 +6,7 @@
 import os, re, shutil, sys, textwrap
 from optparse import OptionParser
 from django.utils import termcolors
+from django.conf import settings
 
 # For Python 2.3
 if not hasattr(__builtins__, 'set'):
@@ -83,7 +84,7 @@
 
 def get_sql_create(app):
     "Returns a list of the CREATE TABLE SQL statements for the given app."
-    from django.db import get_creation_module, models
+    from django.db import models,get_creation_module, backend
     data_types = get_creation_module().DATA_TYPES
 
     if not data_types:
@@ -187,7 +188,20 @@
         full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
     full_statement.append(');')
     final_output.append('\n'.join(full_statement))
-
+    # To simulate auto-incrementing primary keys in Oracle -- creating primary tables
+    if (settings.DATABASE_ENGINE == 'oracle') & (opts.has_auto_field):
+        sequence_statement = 'CREATE SEQUENCE %s_sq;' % opts.db_table
+        final_output.append(sequence_statement)
+        trigger_statement = '' + \
+        'CREATE OR REPLACE trigger %s_tr\n'    % opts.db_table + \
+        '  before insert on %s\n'           % backend.quote_name(opts.db_table) + \
+        '    for each row\n'  + \
+        '      when (new.id is NULL)\n' + \
+        '        begin\n' + \
+        '         select %s_sq.NEXTVAL into :new.id from DUAL;\n' % opts.db_table + \
+        '      end;\n'                                                                       
+        final_output.append(trigger_statement)
+                              
     return final_output, pending_references
 
 def _get_sql_for_pending_references(model, pending_references):
@@ -210,7 +224,13 @@
                 # For MySQL, r_name must be unique in the first 64 characters.
                 # So we are careful with character usage here.
                 r_name = '%s_refs_%s_%x' % (r_col, col, abs(hash((r_table, table))))
-                final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s);' % \
+		# if constraint name size is over 29 char and db is oracle, chop it
+		if settings.DATABASE_ENGINE == 'oracle' and len(r_name) > 29:
+		    final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s);' % \
+		    (backend.quote_name(r_table), r_name[0:29],
+		    backend.quote_name(r_col), backend.quote_name(table), backend.quote_name(col)))
+	        else:
+                    final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s);' % \
                     (backend.quote_name(r_table), r_name,
                     backend.quote_name(r_col), backend.quote_name(table), backend.quote_name(col)))
             del pending_references[model]
@@ -250,6 +270,20 @@
                 style.SQL_FIELD(backend.quote_name(f.m2m_reverse_name()))))
             table_output.append(');')
             final_output.append('\n'.join(table_output))
+        # To simulate auto-incrementing primary keys in Oracle -- creating m2m tables
+        if (settings.DATABASE_ENGINE == 'oracle'):
+            m_table = f.m2m_db_table()
+            sequence_statement = 'CREATE SEQUENCE %s_sq;' % m_table
+            final_output.append(sequence_statement)
+            trigger_statement = '' + \
+            'CREATE OR REPLACE trigger %s_tr\n'    % m_table + \
+            '  before insert on %s\n'           % backend.quote_name(m_table) + \
+            '    for each row\n'  + \
+            '      when (new.id is NULL)\n' + \
+            '        begin\n' + \
+            '         select %s_sq.NEXTVAL into :new.id from DUAL;\n' % m_table + \
+            '      end;\n'
+            final_output.append(trigger_statement)
     return final_output
 
 def get_sql_delete(app):
@@ -473,7 +507,12 @@
             sql.extend(_get_sql_for_pending_references(model, pending_references))
             print "Creating table %s" % model._meta.db_table
             for statement in sql:
-                cursor.execute(statement)
+            #    go on if one table could not be created
+                try:
+                    cursor.execute(statement)
+                except Exception, e:
+                    print statement
+                    print e
             table_list.append(model._meta.db_table)
 
         for model in model_list:
@@ -1289,13 +1328,15 @@
         if not mod_list:
             parser.print_usage_and_exit()
         if action not in NO_SQL_TRANSACTION:
-            print style.SQL_KEYWORD("BEGIN;")
+            if settings.DATABASE_ENGINE != 'oracle':
+                print style.SQL_KEYWORD("BEGIN;")
         for mod in mod_list:
             output = action_mapping[action](mod)
             if output:
                 print '\n'.join(output)
         if action not in NO_SQL_TRANSACTION:
-            print style.SQL_KEYWORD("COMMIT;")
+            if settings.DATABASE_ENGINE != 'oracle':
+                print style.SQL_KEYWORD("COMMIT;")
 
 def setup_environ(settings_mod):
     """
Index: contrib/sessions/models.py
===================================================================
--- contrib/sessions/models.py	(revision 3545)
+++ contrib/sessions/models.py	(working copy)
@@ -51,6 +51,7 @@
     session_key = models.CharField(_('session key'), maxlength=40, primary_key=True)
     session_data = models.TextField(_('session data'))
     expire_date = models.DateTimeField(_('expire date'))
+
     objects = SessionManager()
     class Meta:
         db_table = 'django_session'
Index: contrib/admin/models.py
===================================================================
--- contrib/admin/models.py	(revision 3545)
+++ contrib/admin/models.py	(working copy)
@@ -16,7 +16,8 @@
     action_time = models.DateTimeField(_('action time'), auto_now=True)
     user = models.ForeignKey(User)
     content_type = models.ForeignKey(ContentType, blank=True, null=True)
-    object_id = models.TextField(_('object id'), blank=True, null=True)
+    #changed for Oracle support
+    object_id = models.CharField(_('object id'), maxlength=200, blank=True, null=True)
     object_repr = models.CharField(_('object repr'), maxlength=200)
     action_flag = models.PositiveSmallIntegerField(_('action flag'))
     change_message = models.TextField(_('change message'), blank=True)
