I have an update script that takes in some parameters, one of which is a tuple of primary keys to identify the correct row. However, I don't check to make sure that the keys are primary in my code, and I'd like to. I don't want to leave it up to whoever implements the script. It's fine if I have to run an extra query, I'd just like to check that every key in this tuple is a primary key before moving forward in the code. Thanks!

EDIT: (adding some clarity). So, imagine I have a script that takes in a table name and a list of keys. I'd like to check that each of these keys are primary in the given table.

有帮助吗?

解决方案 2

The general way to find out the primary key columns of a table, which should work in any SQL database, is something like:

SELECT column_name
FROM information_schema.table_constraints
     JOIN information_schema.key_column_usage
         USING (constraint_catalog, constraint_schema, constraint_name,
                table_catalog, table_schema, table_name)
WHERE constraint_type = 'PRIMARY KEY'
  AND (table_schema, table_name) = ('yourschema', 'yourtable')
ORDER BY ordinal_position;

which returns something like

┌─────────────┐
│ column_name │
├─────────────┤
│ a           │
│ b           │
└─────────────┘

其他提示

Well, I found one answer, maybe not the best. I was looking for some sort of function/query that would return a boolean indicating whether or not the key was a primary_key. This way, I return a list of primary keys and check to see if my keys are in that list.

Some code:

sql = "select indexdef from pg_indexes where tablename = '%s';" % (table,)
self.cursor.execute(sql)
rows = self.cursor.fetchall()
row = rows[0][0]

From there, you can cut up the result string as you see fit. I basically just stripped away the useless text until I had my primary keys separated by commas and did a string.split(",") on it. Then, you can check.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top