def persist_database(metamodel, path, mode='w'):
    '''
    Persist all instances, class definitions and association definitions in a
    *metamodel* by serializing them and saving to a *path* on disk.
    '''
    with open(path, mode) as f:
        for kind in sorted(metamodel.metaclasses.keys()):
            metaclass = metamodel.metaclasses[kind]
            s = serialize_class(metaclass.clazz)
            f.write(s)
            
            for index_name, attribute_names in metaclass.indices.items():
                attribute_names = ', '.join(attribute_names)
                s = 'CREATE UNIQUE INDEX %s ON %s (%s);\n' % (index_name,
                                                              metaclass.kind,
                                                              attribute_names)
                f.write(s)
                
        for ass in sorted(metamodel.associations, key=lambda x: x.rel_id):
            s = serialize_association(ass)
            f.write(s)

        for inst in metamodel.instances:
            s = serialize_instance(inst)
            f.write(s)
Persist all instances, class definitions and association definitions in a
    *metamodel* by serializing them and saving to a *path* on disk.