app/django/db/backends/oracle/introspection.py
changeset 323 ff1a9aa48cfd
parent 54 03e267d67478
equal deleted inserted replaced
322:6641e941ef1e 323:ff1a9aa48cfd
     1 from django.db.backends.oracle.base import DatabaseOperations
     1 from django.db.backends import BaseDatabaseIntrospection
       
     2 import cx_Oracle
     2 import re
     3 import re
     3 import cx_Oracle
       
     4 
     4 
     5 quote_name = DatabaseOperations().quote_name
       
     6 foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
     5 foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
     7 
     6 
     8 def get_table_list(cursor):
     7 class DatabaseIntrospection(BaseDatabaseIntrospection):
     9     "Returns a list of table names in the current database."
     8     # Maps type objects to Django Field types.
    10     cursor.execute("SELECT TABLE_NAME FROM USER_TABLES")
     9     data_types_reverse = {
    11     return [row[0].upper() for row in cursor.fetchall()]
    10         cx_Oracle.CLOB: 'TextField',
       
    11         cx_Oracle.DATETIME: 'DateTimeField',
       
    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     }
    12 
    18 
    13 def get_table_description(cursor, table_name):
    19     def get_table_list(self, cursor):
    14     "Returns a description of the table, with the DB-API cursor.description interface."
    20         "Returns a list of table names in the current database."
    15     cursor.execute("SELECT * FROM %s WHERE ROWNUM < 2" % quote_name(table_name))
    21         cursor.execute("SELECT TABLE_NAME FROM USER_TABLES")
    16     return cursor.description
    22         return [row[0].upper() for row in cursor.fetchall()]
    17 
    23 
    18 def _name_to_index(cursor, table_name):
    24     def get_table_description(self, cursor, table_name):
    19     """
    25         "Returns a description of the table, with the DB-API cursor.description interface."
    20     Returns a dictionary of {field_name: field_index} for the given table.
    26         cursor.execute("SELECT * FROM %s WHERE ROWNUM < 2" % self.connection.ops.quote_name(table_name))
    21     Indexes are 0-based.
    27         return cursor.description
    22     """
       
    23     return dict([(d[0], i) for i, d in enumerate(get_table_description(cursor, table_name))])
       
    24 
    28 
    25 def get_relations(cursor, table_name):
    29     def table_name_converter(self, name):
    26     """
    30         "Table name comparison is case insensitive under Oracle"
    27     Returns a dictionary of {field_index: (field_index_other_table, other_table)}
    31         return name.upper()
    28     representing all relationships to the given table. Indexes are 0-based.
    32         
    29     """
    33     def _name_to_index(self, cursor, table_name):
    30     cursor.execute("""
    34         """
    31 SELECT ta.column_id - 1, tb.table_name, tb.column_id - 1
    35         Returns a dictionary of {field_name: field_index} for the given table.
    32 FROM   user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
    36         Indexes are 0-based.
    33        user_tab_cols ta, user_tab_cols tb
    37         """
    34 WHERE  user_constraints.table_name = %s AND
    38         return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))])
    35        ta.table_name = %s AND
       
    36        ta.column_name = ca.column_name AND
       
    37        ca.table_name = %s AND
       
    38        user_constraints.constraint_name = ca.constraint_name AND
       
    39        user_constraints.r_constraint_name = cb.constraint_name AND
       
    40        cb.table_name = tb.table_name AND
       
    41        cb.column_name = tb.column_name AND
       
    42        ca.position = cb.position""", [table_name, table_name, table_name])
       
    43 
    39 
    44     relations = {}
    40     def get_relations(self, cursor, table_name):
    45     for row in cursor.fetchall():
    41         """
    46         relations[row[0]] = (row[2], row[1])
    42         Returns a dictionary of {field_index: (field_index_other_table, other_table)}
    47     return relations
    43         representing all relationships to the given table. Indexes are 0-based.
       
    44         """
       
    45         cursor.execute("""
       
    46     SELECT ta.column_id - 1, tb.table_name, tb.column_id - 1
       
    47     FROM   user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
       
    48            user_tab_cols ta, user_tab_cols tb
       
    49     WHERE  user_constraints.table_name = %s AND
       
    50            ta.table_name = %s AND
       
    51            ta.column_name = ca.column_name AND
       
    52            ca.table_name = %s AND
       
    53            user_constraints.constraint_name = ca.constraint_name AND
       
    54            user_constraints.r_constraint_name = cb.constraint_name AND
       
    55            cb.table_name = tb.table_name AND
       
    56            cb.column_name = tb.column_name AND
       
    57            ca.position = cb.position""", [table_name, table_name, table_name])
    48 
    58 
    49 def get_indexes(cursor, table_name):
    59         relations = {}
    50     """
    60         for row in cursor.fetchall():
    51     Returns a dictionary of fieldname -> infodict for the given table,
    61             relations[row[0]] = (row[2], row[1])
    52     where each infodict is in the format:
    62         return relations
    53         {'primary_key': boolean representing whether it's the primary key,
       
    54          'unique': boolean representing whether it's a unique index}
       
    55     """
       
    56     # This query retrieves each index on the given table, including the
       
    57     # first associated field name
       
    58     # "We were in the nick of time; you were in great peril!"
       
    59     sql = """
       
    60 WITH primarycols AS (
       
    61  SELECT user_cons_columns.table_name, user_cons_columns.column_name, 1 AS PRIMARYCOL
       
    62  FROM   user_cons_columns, user_constraints
       
    63  WHERE  user_cons_columns.constraint_name = user_constraints.constraint_name AND
       
    64         user_constraints.constraint_type = 'P' AND
       
    65         user_cons_columns.table_name = %s),
       
    66  uniquecols AS (
       
    67  SELECT user_ind_columns.table_name, user_ind_columns.column_name, 1 AS UNIQUECOL
       
    68  FROM   user_indexes, user_ind_columns
       
    69  WHERE  uniqueness = 'UNIQUE' AND
       
    70         user_indexes.index_name = user_ind_columns.index_name AND
       
    71         user_ind_columns.table_name = %s)
       
    72 SELECT allcols.column_name, primarycols.primarycol, uniquecols.UNIQUECOL
       
    73 FROM   (SELECT column_name FROM primarycols UNION SELECT column_name FROM
       
    74 uniquecols) allcols,
       
    75       primarycols, uniquecols
       
    76 WHERE  allcols.column_name = primarycols.column_name (+) AND
       
    77       allcols.column_name = uniquecols.column_name (+)
       
    78     """
       
    79     cursor.execute(sql, [table_name, table_name])
       
    80     indexes = {}
       
    81     for row in cursor.fetchall():
       
    82         # row[1] (idx.indkey) is stored in the DB as an array. It comes out as
       
    83         # a string of space-separated integers. This designates the field
       
    84         # indexes (1-based) of the fields that have indexes on the table.
       
    85         # Here, we skip any indexes across multiple fields.
       
    86         indexes[row[0]] = {'primary_key': row[1], 'unique': row[2]}
       
    87     return indexes
       
    88 
    63 
    89 # Maps type objects to Django Field types.
    64     def get_indexes(self, cursor, table_name):
    90 DATA_TYPES_REVERSE = {
    65         """
    91     cx_Oracle.CLOB: 'TextField',
    66         Returns a dictionary of fieldname -> infodict for the given table,
    92     cx_Oracle.DATETIME: 'DateTimeField',
    67         where each infodict is in the format:
    93     cx_Oracle.FIXED_CHAR: 'CharField',
    68             {'primary_key': boolean representing whether it's the primary key,
    94     cx_Oracle.NCLOB: 'TextField',
    69              'unique': boolean representing whether it's a unique index}
    95     cx_Oracle.NUMBER: 'DecimalField',
    70         """
    96     cx_Oracle.STRING: 'CharField',
    71         # This query retrieves each index on the given table, including the
    97     cx_Oracle.TIMESTAMP: 'DateTimeField',
    72         # first associated field name
    98 }
    73         # "We were in the nick of time; you were in great peril!"
       
    74         sql = """
       
    75     WITH primarycols AS (
       
    76      SELECT user_cons_columns.table_name, user_cons_columns.column_name, 1 AS PRIMARYCOL
       
    77      FROM   user_cons_columns, user_constraints
       
    78      WHERE  user_cons_columns.constraint_name = user_constraints.constraint_name AND
       
    79             user_constraints.constraint_type = 'P' AND
       
    80             user_cons_columns.table_name = %s),
       
    81      uniquecols AS (
       
    82      SELECT user_ind_columns.table_name, user_ind_columns.column_name, 1 AS UNIQUECOL
       
    83      FROM   user_indexes, user_ind_columns
       
    84      WHERE  uniqueness = 'UNIQUE' AND
       
    85             user_indexes.index_name = user_ind_columns.index_name AND
       
    86             user_ind_columns.table_name = %s)
       
    87     SELECT allcols.column_name, primarycols.primarycol, uniquecols.UNIQUECOL
       
    88     FROM   (SELECT column_name FROM primarycols UNION SELECT column_name FROM
       
    89     uniquecols) allcols,
       
    90           primarycols, uniquecols
       
    91     WHERE  allcols.column_name = primarycols.column_name (+) AND
       
    92           allcols.column_name = uniquecols.column_name (+)
       
    93         """
       
    94         cursor.execute(sql, [table_name, table_name])
       
    95         indexes = {}
       
    96         for row in cursor.fetchall():
       
    97             # row[1] (idx.indkey) is stored in the DB as an array. It comes out as
       
    98             # a string of space-separated integers. This designates the field
       
    99             # indexes (1-based) of the fields that have indexes on the table.
       
   100             # Here, we skip any indexes across multiple fields.
       
   101             indexes[row[0]] = {'primary_key': row[1], 'unique': row[2]}
       
   102         return indexes
       
   103