Skip to content

Instantly share code, notes, and snippets.

@FauxFaux
Created November 17, 2018 11:35
Show Gist options
  • Save FauxFaux/edf710c041c36342d70ccabff96935e3 to your computer and use it in GitHub Desktop.
Save FauxFaux/edf710c041c36342d70ccabff96935e3 to your computer and use it in GitHub Desktop.
Dump a firebird database to json (and never look back)
import fdb
import json
import sys
import decimal
import datetime
def js(val):
if type(val) == int:
return val
if type(val) == str:
return val
if val is None:
return val
if type(val) == decimal.Decimal:
return str(val)
if type(val) == datetime.datetime:
return val.isoformat()
raise Exception(type(val))
con = fdb.connect(dsn='sdr.fdb', user='sysdba', password='masterkey')
cur = con.cursor()
cur.execute("SELECT a.RDB$RELATION_NAME FROM RDB$RELATIONS a WHERE RDB$SYSTEM_FLAG=0")
tables = [row[0].strip() for row in cur.fetchall()]
db={}
for table in tables:
db[table] = {}
cur.execute("select rdb$field_name from rdb$relation_fields where rdb$relation_name='{}' order by rdb$field_position".format(table))
db[table]['cols']=[head[0].strip() for head in cur.fetchall()]
cur.execute("select * from {}".format(table))
db[table]['rows']=[[js(field) for field in row] for row in cur.fetchall()]
json.dump(db, sys.stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment