-
Notifications
You must be signed in to change notification settings - Fork 9
Use JSON column for metadata and switch from array to ranges #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ioan-alexandra
wants to merge
47
commits into
iterorganization:develop
Choose a base branch
from
ioan-alexandra:develop
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 14 commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
a1ab4f2
add alembic migration
ioan-alexandra 51708f7
add alembic to pyproject, delete db and adjust migration
ioan-alexandra bb7523e
Merge branch 'iterorganization:develop' into develop
ioan-alexandra 7f65c43
format
ioan-alexandra 5bad088
lint
ioan-alexandra 7846265
redo autogenerate alembic to add files
ioan-alexandra 3712954
lint
ioan-alexandra dbc96bc
let Base.metadata handle all models
ioan-alexandra 0d6008d
Merge branch 'develop' of github.com:ioan-alexandra/SimDB into develop
ioan-alexandra 1d5b15b
switch from metadata field to json column
ioan-alexandra 40f93a3
take out limit Header since its fixed in another pr
ioan-alexandra 6b3f56c
format
ioan-alexandra 35a4cf7
lint
ioan-alexandra 886895c
use sql statements to only update specific field instead of whole json
ioan-alexandra 0f24002
use MutableDict
ioan-alexandra e28eb77
typing errors
ioan-alexandra 9ffc009
fix tests
ioan-alexandra 8e75576
Merge branch 'iterorganization:develop' into develop
ioan-alexandra a47eb5c
Merge branch 'iterorganization:develop' into develop
ioan-alexandra df068cf
check if metadata exists before creating
ioan-alexandra 4cf5461
remove custom serialization and use sqlalchemy
ioan-alexandra b5249db
formatting
ioan-alexandra 0b62d57
small fixes
ioan-alexandra 15858f1
yannick comments
ioan-alexandra 7850422
format
ioan-alexandra a83b1c0
linting
ioan-alexandra 3c1eacd
add json serializable
ioan-alexandra 9086488
ruff
ioan-alexandra 4d0ba65
Merge remote-tracking branch 'upstream/develop' into develop
ioan-alexandra 851ec1c
ruff
ioan-alexandra ee2c33d
typing
ioan-alexandra 803678a
fix ty errors
ioan-alexandra 79bb699
fix tests
ioan-alexandra fd7ea7f
move from arrays to ranges
ioan-alexandra 391742e
Query ranges using SQL directly
Yannicked 2e9c56c
Add tests for querying
Yannicked 96d254d
Cleanup filtering functions
Yannicked 16d778e
Revert removal of base64 encoded np array decoding
Yannicked 7319aa3
Fix numpy array ingestion
Yannicked a241d17
Reduce amount of queries
Yannicked 6ca91d8
Ruff
Yannicked 9f774f2
ty
Yannicked 8810ff0
some cleanup
ioan-alexandra 110830f
Use JSON queries for metadata endpoint
Yannicked 9184f7d
Merge branch 'develop' into ioan-alexandra/develop
Yannicked 6cc7139
Merge remote-tracking branch 'upstream/develop' into HEAD
ioan-alexandra 219fb93
lint
ioan-alexandra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
146 changes: 146 additions & 0 deletions
146
alembic/versions/28bee3aa2429_convert_metadata_to_json_column.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| """convert_metadata_to_json_column | ||
|
|
||
| Revision ID: 28bee3aa2429 | ||
| Revises: 9e9a4a7cd639 | ||
| Create Date: 2026-02-26 17:01:30.925750 | ||
|
|
||
| """ | ||
|
|
||
| import json | ||
| import pickle | ||
| from typing import Sequence, Union | ||
|
|
||
| import sqlalchemy as sa | ||
| from sqlalchemy import text | ||
| from sqlalchemy.dialects import postgresql | ||
|
|
||
| from alembic import op | ||
|
|
||
| revision: str = "28bee3aa2429" | ||
| down_revision: Union[str, Sequence[str], None] = "9e9a4a7cd639" | ||
| branch_labels: Union[str, Sequence[str], None] = None | ||
| depends_on: Union[str, Sequence[str], None] = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade schema.""" | ||
| conn = op.get_bind() | ||
|
|
||
| # Add metadata JSON column to simulations table | ||
| # Use JSON type for PostgreSQL, Text for SQLite (will store JSON as text) | ||
| if conn.dialect.name == "postgresql": | ||
| op.add_column( | ||
| "simulations", | ||
| sa.Column( | ||
| "metadata", postgresql.JSON(astext_type=sa.Text()), nullable=True | ||
| ), | ||
| ) | ||
| else: | ||
| op.add_column("simulations", sa.Column("metadata", sa.Text(), nullable=True)) | ||
|
|
||
| # Migrate existing metadata from metadata table to JSON column | ||
| # First, we need to aggregate metadata by simulation | ||
| if conn.dialect.name == "postgresql": | ||
| # PostgreSQL: Use json_object_agg | ||
| migration_query = text(""" | ||
| UPDATE simulations | ||
| SET metadata = subq.meta_json | ||
| FROM ( | ||
| SELECT sim_id, json_object_agg(element, value) as meta_json | ||
| FROM metadata | ||
| GROUP BY sim_id | ||
| ) AS subq | ||
| WHERE simulations.id = subq.sim_id | ||
| """) | ||
| conn.execute(migration_query) | ||
| else: | ||
| # SQLite: Build JSON manually using group_concat | ||
| # This is more complex, we'll handle it per simulation | ||
| result = conn.execute(text("SELECT DISTINCT sim_id FROM metadata")) | ||
| sim_ids = [row[0] for row in result] | ||
|
|
||
| for sim_id in sim_ids: | ||
| # Get all metadata for this simulation | ||
| meta_rows = conn.execute( | ||
| text("SELECT element, value FROM metadata WHERE sim_id = :sim_id"), | ||
| {"sim_id": sim_id}, | ||
| ) | ||
|
|
||
| meta_dict = {} | ||
| for element, value in meta_rows: | ||
| # Value is stored as pickle, need to deserialize | ||
| if value is not None: | ||
| try: | ||
| meta_dict[element] = ( | ||
| pickle.loads(value) if isinstance(value, bytes) else value | ||
| ) | ||
| except Exception: | ||
| meta_dict[element] = value | ||
| else: | ||
| meta_dict[element] = None | ||
|
|
||
| conn.execute( | ||
| text("UPDATE simulations SET metadata = :metadata WHERE id = :sim_id"), | ||
| {"metadata": json.dumps(meta_dict), "sim_id": sim_id}, | ||
| ) | ||
|
|
||
| op.drop_index("metadata_index", table_name="metadata") | ||
| op.drop_index(op.f("ix_metadata_sim_id"), table_name="metadata") | ||
| op.drop_table("metadata") | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade schema.""" | ||
| conn = op.get_bind() | ||
|
|
||
| # Recreate metadata table | ||
| op.create_table( | ||
| "metadata", | ||
| sa.Column("id", sa.Integer(), nullable=False), | ||
| sa.Column("sim_id", sa.Integer(), nullable=True), | ||
| sa.Column("element", sa.String(length=250), nullable=False), | ||
| sa.Column("value", sa.PickleType(), nullable=True), | ||
| sa.ForeignKeyConstraint( | ||
| ["sim_id"], | ||
| ["simulations.id"], | ||
| ), | ||
| sa.PrimaryKeyConstraint("id"), | ||
| ) | ||
| op.create_index(op.f("ix_metadata_sim_id"), "metadata", ["sim_id"], unique=False) | ||
| op.create_index("metadata_index", "metadata", ["sim_id", "element"], unique=True) | ||
|
|
||
| # Migrate data back from JSON column to metadata table | ||
| if conn.dialect.name == "postgresql": | ||
| migration_query = text(""" | ||
| INSERT INTO metadata (sim_id, element, value) | ||
| SELECT s.id, kv.key, kv.value::text | ||
| FROM simulations s, json_each_text(s.metadata::json) kv | ||
| WHERE s.metadata IS NOT NULL | ||
| """) | ||
| conn.execute(migration_query) | ||
| else: | ||
| result = conn.execute( | ||
| text("SELECT id, metadata FROM simulations WHERE metadata IS NOT NULL") | ||
| ) | ||
| for sim_id, metadata_json in result: | ||
| if metadata_json: | ||
| try: | ||
| meta_dict = json.loads(metadata_json) | ||
| for element, value in meta_dict.items(): | ||
| # Pickle the value for storage | ||
| pickled_value = pickle.dumps(value, 0) | ||
| conn.execute( | ||
| text( | ||
| "INSERT INTO metadata (sim_id, element, value) " | ||
| "VALUES (:sim_id, :element, :value)" | ||
| ), | ||
| { | ||
| "sim_id": sim_id, | ||
| "element": element, | ||
| "value": pickled_value, | ||
| }, | ||
| ) | ||
| except Exception: | ||
| pass | ||
|
|
||
| op.drop_column("simulations", "metadata") | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.