Skip to content

Instantly share code, notes, and snippets.

@jdowner
Last active November 14, 2023 13:23
Show Gist options
  • Save jdowner/a485ee9ddf8433ef8682 to your computer and use it in GitHub Desktop.
Save jdowner/a485ee9ddf8433ef8682 to your computer and use it in GitHub Desktop.
Print a sqlite database file as YAML
#!/usr/bin/env python2
import argparse
import sys
import sqlalchemy
import yaml
def sqlite2yaml(filename):
engine = sqlalchemy.create_engine('sqlite:///{}'.format(filename))
metadata = sqlalchemy.MetaData(bind=engine)
metadata.reflect()
tables = {}
for table in engine.table_names():
columns = map(str, metadata.tables[table].columns.keys())
rows = engine.execute('select * from {}'.format(table)).fetchall()
tables[table] = []
for row in rows:
tables[table].append(dict(zip(columns, row)))
yaml.safe_dump(tables, sys.stdout, indent=4, default_flow_style=False)
def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('file')
args = parser.parse_args(argv)
sqlite2yaml(args.file)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment