Skip to content

Instantly share code, notes, and snippets.

@jmoy
Created February 25, 2011 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmoy/843379 to your computer and use it in GitHub Desktop.
Save jmoy/843379 to your computer and use it in GitHub Desktop.
Create Asciidoc table of MySQL database schema
"""
Create Asciidoc table of MySQL database schema
Usage:
pretty-schema.py <database> <username> [password]
If you have AsciiDoc installed you can use the following to produce a pretty HTML file of your database schema:
pretty-schema.py mydb myusr | asciidoc -a toc - > schema.html
"""
import MySQLdb as mysqldb
import sys
if len(sys.argv)<3 or len(sys.argv)>4:
sys.stderr.write("Usage: pretty-schema.py <database> <user> [passwd]\n")
sys.exit(1)
DB=sys.argv[1]
connargs={"user":sys.argv[2],
"use_unicode":True}
if len(sys.argv)==4:
connargs["passwd"]=sys.argv[3]
db=mysqldb.connect(**connargs)
c=db.cursor()
c.execute("""SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema=%s
ORDER BY table_name
""",(DB,))
tables=[r[0] for r in c.fetchall()]
print DB
print "="*len(DB)
print
for t in tables:
print "== %s ==\n"%(t,)
print '[frame="all",grid="all"]'
print '`40`20`5`5`5~~~~'
print 'Name,Type,NULL,Default,Key\n~~~~'
#print "Field","Type","Null","Key","Default","Extra"
c.execute("""SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE,
COLUMN_DEFAULT,COLUMN_KEY
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = %s
AND table_schema = %s
ORDER BY ORDINAL_POSITION
""",(t,DB))
for r in c.fetchall():
print ",".join(str(x) for x in r)
print "~"*4+"\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment