def json2schema(schema_json, commit = True, destdb = None): """ Creates Database, Table, and Column objects as needed to satisfy the incoming schema. If the table is already present, assume we are updating: delete all columns and recreate from the schema. Unless commit is false, call the required sql to create the incoming tables in the destination database. """ schema = json.loads(schema_json) for dbname, table_schema in schema.iteritems(): if destdb: dbname = destdb try: db = Database.objects.get(name=dbname) except Database.DoesNotExist: db = Database(name=dbname) db.save() for tablename, column_schema in table_schema.iteritems(): try: table = Table.objects.get(db=db, name=tablename) for column in Column.objects.filter(table=table): column.delete() except Table.DoesNotExist: table = Table(db=db, name=tablename) table.save() for columnname, columntype in column_schema.iteritems(): column = Column(table=table, name=columnname, type=columntype) column.save() if commit: model = ModelGenerator.getModel(dbname, tablename) cursor = connections[dbname].cursor() for sql in ModelGenerator.getSQL(model): cursor.execute(sql) return None