Building an automated form based on sql data schema in python (with Flask)

Viewed 30

Edit: added solution

I have a data schema for my SQL database, which has several tables, related with foreign keys and several constraints.

The code below is used to build a custom form that is based on the SQL schema itself:

First: getting all the table names the database:

def get_table_names(db):
    #   https://stackoverflow.com/questions/947215/how-to-get-a-list-of-column-names-on-sqlite3-database
    
    list = db.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tablenames = list(d['name'] for d in list)
    return tablenames

Secondly: getting the column information for a specific table by using PRAGMA

def get_table_columns(db,tablename):
    #   https://stackoverflow.com/questions/604939/how-can-i-get-the-list-of-a-columns-in-a-table-for-a-sqlite-database
    
    list = db.execute("SELECT * FROM PRAGMA_TABLE_INFO(?);",tablename)
    # returning a list of dicts. One for each column
    return list

These two enable me to have dynamically generated forms based on my schema (and thus when expanding my schema do not require code rework). This works fine, but i'd also like to add intelligence in the schema's:

  • links to foreign keys (that i can use to populate autocomplete in js)
def get_foreign_keys(db,tablename):
     list = db.execute("SELECT * FROM PRAGMA_FOREIGN_KEY_LIST(?);",tablename)
    # returning a list of foreign keys if any are referenced
    return list

If there is a useful library available, that would be even nicer of course!

0 Answers
Related