from xplordb.migration import v1
from packaging.version import Version

# key : current version to be upgraded
MIGRATIONS = {"0.13.8" : v1.migrate}

def migrate_database(conn, target_version: str):
    """
    Migrate iteratively.  
    User must be connected as administrator or database owner.
    Each migration is destructive, with the following steps:  
    - export raw data as csv
    - remove old schema
    - install new schema
    - import data
    """
    cur = conn.cursor()

    # get current version
    cur.execute("SELECT version FROM ref.xplordb")
    version_str = cur.fetchone()[0]
    version = Version(version_str)
    if version < Version("0.13.8"):
        print("Xplordb schema is too old. Aborting")
        return
    target_version = Version(target_version)

    while version < target_version:
        migrate = MIGRATIONS[version_str]
        migrate(conn)
        conn.commit()
        # get new version
        cur.execute("SELECT version FROM ref.xplordb")
        version_str = cur.fetchone()[0]
        version = Version(version_str)