Esempio n. 1
0
def migrate(config=None, migration_directory="db"):
    '''
    Perform migrations.

    Parameters
    ==========
    config
        Dictionary with psycopg2 "connect" method arguments.
        If None then read INI file
    migration_directory: str
        Directory with .psql files. Files must to keep naming convention:
            svarog-XX.psql
        where XX is number of database revision.

    Returns
    =======
    Function print migration status on console. Changes are save in database.

    Notes
    =====
    If any migration fail then all changes are revert.
    '''
    repository = Repository(config)

    db_version = repository.get_database_version()

    migrations = list_migrations(migration_directory)

    with repository.transaction() as transaction:
        for migration_version, migration_path in migrations:
            if migration_version <= db_version:
                print("Skip migration to %d version" % (migration_version, ))
                continue

            print("Process migration to %d version..." % (migration_version, ),
                  end="")
            with open(migration_path) as migration_file:
                content = migration_file.read()

            repository.execute_raw_query(content)
            print("OK")

        transaction.commit()

    new_db_version = repository.get_database_version()
    print("Migration complete from %d to %d!" % (db_version, new_db_version))
Esempio n. 2
0
    def test_db_version(self, mock_connect):
        repostory = Repository({})
        mock_cursor = mock_connect.return_value.cursor.return_value
        mock_cursor.fetchone.side_effect = [{
            "count": 1
        }, (3, ), {
            "version": 15
        }]

        version = repostory.get_database_version()
        self.assertEqual(version, 15)