web/lib/django/db/backends/oracle/introspection.py
changeset 0 0d40e90630ef
child 29 cc9b7e14412b
equal deleted inserted replaced
-1:000000000000 0:0d40e90630ef
       
     1 from django.db.backends import BaseDatabaseIntrospection
       
     2 import cx_Oracle
       
     3 import re
       
     4 
       
     5 foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
       
     6 
       
     7 class DatabaseIntrospection(BaseDatabaseIntrospection):
       
     8     # Maps type objects to Django Field types.
       
     9     data_types_reverse = {
       
    10         cx_Oracle.CLOB: 'TextField',
       
    11         cx_Oracle.DATETIME: 'DateField',
       
    12         cx_Oracle.FIXED_CHAR: 'CharField',
       
    13         cx_Oracle.NCLOB: 'TextField',
       
    14         cx_Oracle.NUMBER: 'DecimalField',
       
    15         cx_Oracle.STRING: 'CharField',
       
    16         cx_Oracle.TIMESTAMP: 'DateTimeField',
       
    17     }
       
    18 
       
    19     try:
       
    20         data_types_reverse[cx_Oracle.NATIVE_FLOAT] = 'FloatField'
       
    21     except AttributeError:
       
    22         pass
       
    23 
       
    24     try:
       
    25         data_types_reverse[cx_Oracle.UNICODE] = 'CharField'
       
    26     except AttributeError:
       
    27         pass
       
    28 
       
    29     def get_field_type(self, data_type, description):
       
    30         # If it's a NUMBER with scale == 0, consider it an IntegerField
       
    31         if data_type == cx_Oracle.NUMBER and description[5] == 0:
       
    32             return 'IntegerField'
       
    33         else:
       
    34             return super(DatabaseIntrospection, self).get_field_type(
       
    35                 data_type, description)
       
    36 
       
    37     def get_table_list(self, cursor):
       
    38         "Returns a list of table names in the current database."
       
    39         cursor.execute("SELECT TABLE_NAME FROM USER_TABLES")
       
    40         return [row[0].lower() for row in cursor.fetchall()]
       
    41 
       
    42     def get_table_description(self, cursor, table_name):
       
    43         "Returns a description of the table, with the DB-API cursor.description interface."
       
    44         cursor.execute("SELECT * FROM %s WHERE ROWNUM < 2" % self.connection.ops.quote_name(table_name))
       
    45         description = []
       
    46         for desc in cursor.description:
       
    47             description.append((desc[0].lower(),) + desc[1:])
       
    48         return description
       
    49 
       
    50     def table_name_converter(self, name):
       
    51         "Table name comparison is case insensitive under Oracle"
       
    52         return name.lower()
       
    53 
       
    54     def _name_to_index(self, cursor, table_name):
       
    55         """
       
    56         Returns a dictionary of {field_name: field_index} for the given table.
       
    57         Indexes are 0-based.
       
    58         """
       
    59         return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))])
       
    60 
       
    61     def get_relations(self, cursor, table_name):
       
    62         """
       
    63         Returns a dictionary of {field_index: (field_index_other_table, other_table)}
       
    64         representing all relationships to the given table. Indexes are 0-based.
       
    65         """
       
    66         cursor.execute("""
       
    67     SELECT ta.column_id - 1, tb.table_name, tb.column_id - 1
       
    68     FROM   user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
       
    69            user_tab_cols ta, user_tab_cols tb
       
    70     WHERE  user_constraints.table_name = %s AND
       
    71            ta.table_name = %s AND
       
    72            ta.column_name = ca.column_name AND
       
    73            ca.table_name = %s AND
       
    74            user_constraints.constraint_name = ca.constraint_name AND
       
    75            user_constraints.r_constraint_name = cb.constraint_name AND
       
    76            cb.table_name = tb.table_name AND
       
    77            cb.column_name = tb.column_name AND
       
    78            ca.position = cb.position""", [table_name, table_name, table_name])
       
    79 
       
    80         relations = {}
       
    81         for row in cursor.fetchall():
       
    82             relations[row[0]] = (row[2], row[1])
       
    83         return relations
       
    84 
       
    85     def get_indexes(self, cursor, table_name):
       
    86         """
       
    87         Returns a dictionary of fieldname -> infodict for the given table,
       
    88         where each infodict is in the format:
       
    89             {'primary_key': boolean representing whether it's the primary key,
       
    90              'unique': boolean representing whether it's a unique index}
       
    91         """
       
    92         # This query retrieves each index on the given table, including the
       
    93         # first associated field name
       
    94         # "We were in the nick of time; you were in great peril!"
       
    95         sql = """\
       
    96 SELECT LOWER(all_tab_cols.column_name) AS column_name,
       
    97        CASE user_constraints.constraint_type
       
    98            WHEN 'P' THEN 1 ELSE 0
       
    99        END AS is_primary_key,
       
   100        CASE user_indexes.uniqueness
       
   101            WHEN 'UNIQUE' THEN 1 ELSE 0
       
   102        END AS is_unique
       
   103 FROM   all_tab_cols, user_cons_columns, user_constraints, user_ind_columns, user_indexes
       
   104 WHERE  all_tab_cols.column_name = user_cons_columns.column_name (+)
       
   105   AND  all_tab_cols.table_name = user_cons_columns.table_name (+)
       
   106   AND  user_cons_columns.constraint_name = user_constraints.constraint_name (+)
       
   107   AND  user_constraints.constraint_type (+) = 'P'
       
   108   AND  user_ind_columns.column_name (+) = all_tab_cols.column_name
       
   109   AND  user_ind_columns.table_name (+) = all_tab_cols.table_name
       
   110   AND  user_indexes.uniqueness (+) = 'UNIQUE'
       
   111   AND  user_indexes.index_name (+) = user_ind_columns.index_name
       
   112   AND  all_tab_cols.table_name = UPPER(%s)
       
   113 """
       
   114         cursor.execute(sql, [table_name])
       
   115         indexes = {}
       
   116         for row in cursor.fetchall():
       
   117             indexes[row[0]] = {'primary_key': row[1], 'unique': row[2]}
       
   118         return indexes