Coverage for datakiln/metadata/migrations/__init__.py: 44%

18 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-16 23:23 +0000

1""" 

2Migrations of the metadata tables. 

3""" 

4from pathlib import Path 

5 

6from alembic import command 

7from alembic.config import Config 

8from sqlalchemy import inspect 

9 

10from datakiln.metadata.table import Base 

11 

12 

13# The version of databases built before there were migrations 

14BASELINE = "0001" 

15 

16 

17def get_config(conn): 

18 """Configuration of the migrations, which run on a connection. 

19 

20 :param conn: SQLAlchemy connection, whose transaction is the one of the 

21 migrations. 

22 :type conn: sqlalchemy.Connection 

23 

24 :return: Alembic configuration. 

25 :rtype: alembic.config.Config 

26 """ 

27 config = Config() 

28 config.set_main_option("script_location", str(Path(__file__).parent)) 

29 config.attributes["connection"] = conn 

30 return config 

31 

32 

33def upgrade(conn): 

34 """Bring the metadata tables to the current version. 

35 

36 :param conn: SQLAlchemy connection, whose transaction is the one of the 

37 migrations. 

38 :type conn: sqlalchemy.Connection 

39 """ 

40 config = get_config(conn) 

41 

42 # A database built before the migrations has the tables of the first 

43 # version, but no record of it 

44 schema = Base.metadata.schema 

45 inspector = inspect(conn) 

46 if ( 

47 inspector.has_table("table_", schema) 

48 and not inspector.has_table("alembic_version", schema) 

49 ): 

50 command.stamp(config, BASELINE) 

51 

52 command.upgrade(config, "head")