Karan6124 commited on
Commit
753ba4e
·
1 Parent(s): 1826316

chore: configure alembic dynamically from dotenv and generate initial migration

Browse files
alembic.ini ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # path to migration scripts.
5
+ # this is typically a path given in POSIX (e.g. forward slashes)
6
+ # format, relative to the token %(here)s which refers to the location of this
7
+ # ini file
8
+ script_location = %(here)s/alembic
9
+
10
+ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11
+ # Uncomment the line below if you want the files to be prepended with date and time
12
+ # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13
+ # for all available tokens
14
+ # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15
+ # Or organize into date-based subdirectories (requires recursive_version_locations = true)
16
+ # file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
17
+
18
+ # sys.path path, will be prepended to sys.path if present.
19
+ # defaults to the current working directory. for multiple paths, the path separator
20
+ # is defined by "path_separator" below.
21
+ prepend_sys_path = .
22
+
23
+
24
+ # timezone to use when rendering the date within the migration file
25
+ # as well as the filename.
26
+ # If specified, requires the tzdata library which can be installed by adding
27
+ # `alembic[tz]` to the pip requirements.
28
+ # string value is passed to ZoneInfo()
29
+ # leave blank for localtime
30
+ # timezone =
31
+
32
+ # max length of characters to apply to the "slug" field
33
+ # truncate_slug_length = 40
34
+
35
+ # set to 'true' to run the environment during
36
+ # the 'revision' command, regardless of autogenerate
37
+ # revision_environment = false
38
+
39
+ # set to 'true' to allow .pyc and .pyo files without
40
+ # a source .py file to be detected as revisions in the
41
+ # versions/ directory
42
+ # sourceless = false
43
+
44
+ # version location specification; This defaults
45
+ # to <script_location>/versions. When using multiple version
46
+ # directories, initial revisions must be specified with --version-path.
47
+ # The path separator used here should be the separator specified by "path_separator"
48
+ # below.
49
+ # version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
50
+
51
+ # path_separator; This indicates what character is used to split lists of file
52
+ # paths, including version_locations and prepend_sys_path within configparser
53
+ # files such as alembic.ini.
54
+ # The default rendered in new alembic.ini files is "os", which uses os.pathsep
55
+ # to provide os-dependent path splitting.
56
+ #
57
+ # Note that in order to support legacy alembic.ini files, this default does NOT
58
+ # take place if path_separator is not present in alembic.ini. If this
59
+ # option is omitted entirely, fallback logic is as follows:
60
+ #
61
+ # 1. Parsing of the version_locations option falls back to using the legacy
62
+ # "version_path_separator" key, which if absent then falls back to the legacy
63
+ # behavior of splitting on spaces and/or commas.
64
+ # 2. Parsing of the prepend_sys_path option falls back to the legacy
65
+ # behavior of splitting on spaces, commas, or colons.
66
+ #
67
+ # Valid values for path_separator are:
68
+ #
69
+ # path_separator = :
70
+ # path_separator = ;
71
+ # path_separator = space
72
+ # path_separator = newline
73
+ #
74
+ # Use os.pathsep. Default configuration used for new projects.
75
+ path_separator = os
76
+
77
+ # set to 'true' to search source files recursively
78
+ # in each "version_locations" directory
79
+ # new in Alembic version 1.10
80
+ # recursive_version_locations = false
81
+
82
+ # the output encoding used when revision files
83
+ # are written from script.py.mako
84
+ # output_encoding = utf-8
85
+
86
+ # database URL. This is consumed by the user-maintained env.py script only.
87
+ # other means of configuring database URLs may be customized within the env.py
88
+ # file.
89
+ sqlalchemy.url = driver://user:pass@localhost/dbname
90
+
91
+
92
+ [post_write_hooks]
93
+ # post_write_hooks defines scripts or Python functions that are run
94
+ # on newly generated revision scripts. See the documentation for further
95
+ # detail and examples
96
+
97
+ # format using "black" - use the console_scripts runner, against the "black" entrypoint
98
+ # hooks = black
99
+ # black.type = console_scripts
100
+ # black.entrypoint = black
101
+ # black.options = -l 79 REVISION_SCRIPT_FILENAME
102
+
103
+ # lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
104
+ # hooks = ruff
105
+ # ruff.type = module
106
+ # ruff.module = ruff
107
+ # ruff.options = check --fix REVISION_SCRIPT_FILENAME
108
+
109
+ # Alternatively, use the exec runner to execute a binary found on your PATH
110
+ # hooks = ruff
111
+ # ruff.type = exec
112
+ # ruff.executable = ruff
113
+ # ruff.options = check --fix REVISION_SCRIPT_FILENAME
114
+
115
+ # Logging configuration. This is also consumed by the user-maintained
116
+ # env.py script only.
117
+ [loggers]
118
+ keys = root,sqlalchemy,alembic
119
+
120
+ [handlers]
121
+ keys = console
122
+
123
+ [formatters]
124
+ keys = generic
125
+
126
+ [logger_root]
127
+ level = WARNING
128
+ handlers = console
129
+ qualname =
130
+
131
+ [logger_sqlalchemy]
132
+ level = WARNING
133
+ handlers =
134
+ qualname = sqlalchemy.engine
135
+
136
+ [logger_alembic]
137
+ level = INFO
138
+ handlers =
139
+ qualname = alembic
140
+
141
+ [handler_console]
142
+ class = StreamHandler
143
+ args = (sys.stderr,)
144
+ level = NOTSET
145
+ formatter = generic
146
+
147
+ [formatter_generic]
148
+ format = %(levelname)-5.5s [%(name)s] %(message)s
149
+ datefmt = %H:%M:%S
alembic/README ADDED
@@ -0,0 +1 @@
 
 
1
+ Generic single-database configuration.
alembic/env.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from logging.config import fileConfig
3
+ from sqlalchemy import engine_from_config, pool
4
+ from alembic import context
5
+ from dotenv import load_dotenv
6
+
7
+ # Load environment variables from .env
8
+ load_dotenv()
9
+
10
+ # This is the Alembic Config object
11
+ config = context.config
12
+
13
+ # Dynamically set the sqlalchemy.url from our .env file
14
+ db_url = os.getenv("DATABASE_URL")
15
+ if db_url:
16
+ # Ensure serverless NeonDB SSL settings are matched
17
+ if "localhost" not in db_url and "sslmode" not in db_url:
18
+ if "?" in db_url:
19
+ db_url += "&sslmode=require"
20
+ else:
21
+ db_url += "?sslmode=require"
22
+ config.set_main_option("sqlalchemy.url", db_url)
23
+
24
+ # Interpret the config file for Python logging
25
+ if config.config_file_name is not None:
26
+ fileConfig(config.config_file_name)
27
+
28
+ # Import models so Alembic target_metadata knows they exist
29
+ from app.services.database import Base
30
+ from app.models.database_models import (
31
+ CaseContextModel,
32
+ FactModel,
33
+ HypothesisModel,
34
+ EvidenceModel,
35
+ VerificationModel
36
+ )
37
+
38
+ # Set the metadata object for 'autogenerate' support
39
+ target_metadata = Base.metadata
40
+
41
+ def run_migrations_offline() -> None:
42
+ """Run migrations in 'offline' mode."""
43
+ url = config.get_main_option("sqlalchemy.url")
44
+ context.configure(
45
+ url=url,
46
+ target_metadata=target_metadata,
47
+ literal_binds=True,
48
+ dialect_opts={"paramstyle": "named"},
49
+ )
50
+
51
+ with context.begin_transaction():
52
+ context.run_migrations()
53
+
54
+ def run_migrations_online() -> None:
55
+ """Run migrations in 'online' mode."""
56
+ connectable = engine_from_config(
57
+ config.get_section(config.config_ini_section, {}),
58
+ prefix="sqlalchemy.",
59
+ poolclass=pool.NullPool,
60
+ )
61
+
62
+ with connectable.connect() as connection:
63
+ context.configure(
64
+ connection=connection,
65
+ target_metadata=target_metadata
66
+ )
67
+
68
+ with context.begin_transaction():
69
+ context.run_migrations()
70
+
71
+ if context.is_offline_mode():
72
+ run_migrations_offline()
73
+ else:
74
+ run_migrations_online()
alembic/script.py.mako ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ ${imports if imports else ""}
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = ${repr(up_revision)}
16
+ down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
17
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19
+
20
+
21
+ def upgrade() -> None:
22
+ """Upgrade schema."""
23
+ ${upgrades if upgrades else "pass"}
24
+
25
+
26
+ def downgrade() -> None:
27
+ """Downgrade schema."""
28
+ ${downgrades if downgrades else "pass"}
alembic/versions/b78e4e81098b_initial_schema.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """initial_schema
2
+
3
+ Revision ID: b78e4e81098b
4
+ Revises:
5
+ Create Date: 2026-05-30 20:24:46.544176
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = 'b78e4e81098b'
16
+ down_revision: Union[str, Sequence[str], None] = None
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ """Upgrade schema."""
23
+ # ### commands auto generated by Alembic - please adjust! ###
24
+ op.create_table('cases',
25
+ sa.Column('case_id', sa.String(), nullable=False),
26
+ sa.Column('problem_statement', sa.String(), nullable=False),
27
+ sa.Column('status', sa.String(), nullable=False),
28
+ sa.Column('metadata_json', sa.JSON(), nullable=True),
29
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
30
+ sa.PrimaryKeyConstraint('case_id')
31
+ )
32
+ op.create_index(op.f('ix_cases_case_id'), 'cases', ['case_id'], unique=False)
33
+ op.create_table('facts',
34
+ sa.Column('id', sa.String(), nullable=False),
35
+ sa.Column('case_id', sa.String(), nullable=False),
36
+ sa.Column('source', sa.String(), nullable=False),
37
+ sa.Column('content', sa.String(), nullable=False),
38
+ sa.Column('created_at', sa.DateTime(), nullable=True),
39
+ sa.ForeignKeyConstraint(['case_id'], ['cases.case_id'], ondelete='CASCADE'),
40
+ sa.PrimaryKeyConstraint('id')
41
+ )
42
+ op.create_index(op.f('ix_facts_id'), 'facts', ['id'], unique=False)
43
+ op.create_table('hypotheses',
44
+ sa.Column('id', sa.String(), nullable=False),
45
+ sa.Column('case_id', sa.String(), nullable=False),
46
+ sa.Column('statement', sa.String(), nullable=False),
47
+ sa.Column('status', sa.String(), nullable=False),
48
+ sa.Column('assigned_investigator', sa.String(), nullable=True),
49
+ sa.Column('created_at', sa.DateTime(), nullable=True),
50
+ sa.ForeignKeyConstraint(['case_id'], ['cases.case_id'], ondelete='CASCADE'),
51
+ sa.PrimaryKeyConstraint('id')
52
+ )
53
+ op.create_index(op.f('ix_hypotheses_id'), 'hypotheses', ['id'], unique=False)
54
+ op.create_table('evidence',
55
+ sa.Column('id', sa.String(), nullable=False),
56
+ sa.Column('case_id', sa.String(), nullable=False),
57
+ sa.Column('hypothesis_id', sa.String(), nullable=False),
58
+ sa.Column('source', sa.String(), nullable=False),
59
+ sa.Column('content', sa.String(), nullable=False),
60
+ sa.Column('confidence', sa.Float(), nullable=False),
61
+ sa.Column('created_at', sa.DateTime(), nullable=True),
62
+ sa.ForeignKeyConstraint(['case_id'], ['cases.case_id'], ondelete='CASCADE'),
63
+ sa.ForeignKeyConstraint(['hypothesis_id'], ['hypotheses.id'], ondelete='CASCADE'),
64
+ sa.PrimaryKeyConstraint('id')
65
+ )
66
+ op.create_index(op.f('ix_evidence_id'), 'evidence', ['id'], unique=False)
67
+ op.create_table('verifications',
68
+ sa.Column('id', sa.String(), nullable=False),
69
+ sa.Column('case_id', sa.String(), nullable=False),
70
+ sa.Column('evidence_id', sa.String(), nullable=False),
71
+ sa.Column('valid', sa.Boolean(), nullable=False),
72
+ sa.Column('confidence_score', sa.Float(), nullable=False),
73
+ sa.Column('context_alignment_score', sa.Float(), nullable=False),
74
+ sa.Column('reason', sa.String(), nullable=False),
75
+ sa.Column('created_at', sa.DateTime(), nullable=True),
76
+ sa.ForeignKeyConstraint(['case_id'], ['cases.case_id'], ondelete='CASCADE'),
77
+ sa.ForeignKeyConstraint(['evidence_id'], ['evidence.id'], ondelete='CASCADE'),
78
+ sa.PrimaryKeyConstraint('id')
79
+ )
80
+ op.create_index(op.f('ix_verifications_id'), 'verifications', ['id'], unique=False)
81
+ # ### end Alembic commands ###
82
+
83
+
84
+ def downgrade() -> None:
85
+ """Downgrade schema."""
86
+ # ### commands auto generated by Alembic - please adjust! ###
87
+ op.drop_index(op.f('ix_verifications_id'), table_name='verifications')
88
+ op.drop_table('verifications')
89
+ op.drop_index(op.f('ix_evidence_id'), table_name='evidence')
90
+ op.drop_table('evidence')
91
+ op.drop_index(op.f('ix_hypotheses_id'), table_name='hypotheses')
92
+ op.drop_table('hypotheses')
93
+ op.drop_index(op.f('ix_facts_id'), table_name='facts')
94
+ op.drop_table('facts')
95
+ op.drop_index(op.f('ix_cases_case_id'), table_name='cases')
96
+ op.drop_table('cases')
97
+ # ### end Alembic commands ###