-
-
Save datavudeja/91a7cddaffa9f188ef09e89a368296e8 to your computer and use it in GitHub Desktop.
Dump Schema from SQLITE database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Dump schema from table | |
""" | |
Credit to Wilfredo Sánchez Vega who posted this answer | |
on stackoverflow | |
https://stackoverflow.com/questions/11996394/is-there-a-way-to-get-a-schema-of-a-database-from-within-python | |
""" | |
import sqlite3 | |
import re | |
import os | |
from pathlib import Path | |
cwd = Path.cwd() | |
db_path = os.path.join(cwd, <dbname>) | |
conn = sqlite3.connect(db_path) | |
def printSchema(connection): | |
for (tableName,) in connection.execute( | |
""" | |
select NAME from SQLITE_MASTER where TYPE='table' order by NAME; | |
""" | |
): | |
print("{}:".format(tableName)) | |
for ( | |
columnID, columnName, columnType, | |
columnNotNull, columnDefault, columnPK, | |
) in connection.execute("pragma table_info('{}');".format(tableName)): | |
print(" {id}: {name}({type}){null}{default}{pk}".format( | |
id=columnID, | |
name=columnName, | |
type=columnType, | |
null=" not null" if columnNotNull else "", | |
default=" [{}]".format(columnDefault) if columnDefault else "", | |
pk=" *{}".format(columnPK) if columnPK else "", | |
)) | |
printSchema(conn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment