Alex Rivera | Logout

Is there a way to get the constraints of a table in SQLite?

Asked 2012-03-09T14:51:40.757
28

The command pragma table_info('tablename') lists the columns information and pragma foreign_key_list('tablename') the foreign keys. How can I display other constraints (check, unique) of a table? Only parsing the field "sql" of the table "sqlite_master"?

Edit
Report

1 Answer

18

I think the only way is to do this is the way you suggested, parse the sql column of the sqlite_master database.

Python code to do this:

import sqlite3

con = sqlite3.connect("example.sqlite3")
cur = con.cursor()
cur.execute("select sql from sqlite_master where type='table' and name='example_table'")
schema = cur.fetchone()
con.close()

entries = [ tmp.strip() for tmp in schema[0].splitlines() if tmp.find("constraint")>=0 or tmp.find("unique")>=0 ]
for i in entries: print(i)
answered 2012-08-27T13:00:51.333

Your Answer