def emit_db_sequence_updates(engine):
    """Set database sequence objects to match the source db

       Relevant only when generated from SQLAlchemy connection.
       Needed to avoid subsequent unique key violations after DB build."""
    if engine and engine.name == 'postgresql':
        conn = engine.connect()
        qry = """SELECT 'SELECT last_value FROM ' || n.nspname ||
                         '.' || c.relname || ';' AS qry,
                        n.nspname || '.' || c.relname AS qual_name
                 FROM   pg_namespace n
                 JOIN   pg_class c ON (n.oid = c.relnamespace)
                 WHERE  c.relkind = 'S'"""
        for qry, qual_name in list(conn.execute(qry)):
            lastval, = conn.execute(qry).first()
            nextval = int(lastval) + 1
            yield 'ALTER SEQUENCE %s RESTART WITH %s;' % (qual_name, nextval)
