From 64153ef4d5ecd838c61eaa785e79856469afa83b Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Sat, 18 Feb 2006 22:04:52 +0000 Subject: [PATCH] Implemented get_indexes() for Postgres backend, which means 'inspectdb' can introspect primary keys and unique indexes for Postgres now. git-svn-id: http://code.djangoproject.com/svn/django/trunk@2349 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/db/backends/postgresql.py | 29 ++++++++++++++++++++++++++- docs/django-admin.txt | 2 +- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/django/core/db/backends/postgresql.py b/django/core/db/backends/postgresql.py index e4094f31f5..dbc0cd0677 100644 --- a/django/core/db/backends/postgresql.py +++ b/django/core/db/backends/postgresql.py @@ -127,7 +127,34 @@ def get_relations(cursor, table_name): return relations def get_indexes(cursor, table_name): - raise NotImplementedError + """ + Returns a dictionary of fieldname -> infodict for the given table, + where each infodict is in the format: + {'primary_key': boolean representing whether it's the primary key, + 'unique': boolean representing whether it's a unique index} + """ + # Get the table description because we only have the column indexes, and we + # need the column names. + desc = get_table_description(cursor, table_name) + # This query retrieves each index on the given table. + cursor.execute(""" + SELECT idx.indkey, idx.indisunique, idx.indisprimary + FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, + pg_catalog.pg_index idx + WHERE c.oid = idx.indrelid + AND idx.indexrelid = c2.oid + AND c.relname = %s""", [table_name]) + indexes = {} + for row in cursor.fetchall(): + # row[0] (idx.indkey) is stored in the DB as an array. It comes out as + # a string of space-separated integers. This designates the field + # indexes (1-based) of the fields that have indexes on the table. + # Here, we skip any indexes across multiple fields. + if ' ' in row[0]: + continue + col_name = desc[int(row[0])-1][0] + indexes[col_name] = {'primary_key': row[2], 'unique': row[1]} + return indexes # Register these custom typecasts, because Django expects dates/times to be # in Python's native (standard-library) datetime/time format, whereas psycopg diff --git a/docs/django-admin.txt b/docs/django-admin.txt index 9600a72acf..45cc2363dc 100644 --- a/docs/django-admin.txt +++ b/docs/django-admin.txt @@ -117,7 +117,7 @@ models that refer to other models are ordered properly. If you're using Django 0.90 or 0.91, you'll need to add ``primary_key=True`` to one field in each model. In the Django development version, primary keys are -automatically introspected for MySQL, and Django puts in the +automatically introspected for PostgreSQL and MySQL, and Django puts in the ``primary_key=True`` where needed. ``inspectdb`` works with PostgreSQL, MySQL and SQLite. Foreign-key detection