Skip to content

Commit

Permalink
add column if not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
NaturezzZ committed Nov 21, 2024
1 parent a3d0314 commit 4b5bbdd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
1 change: 1 addition & 0 deletions run_page/generator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def sync_from_app(self, app_tracks):
self.session.commit()

def load(self):
# if sub_type is not in the db, just add an empty string to it
activities = (
self.session.query(Activity)
.filter(Activity.distance > 0.1)
Expand Down
29 changes: 26 additions & 3 deletions run_page/generator/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import geopy
from geopy.geocoders import Nominatim
from sqlalchemy import Column, Float, Integer, Interval, String, create_engine
from sqlalchemy import Column, Float, Integer, Interval, String, create_engine, inspect, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Expand Down Expand Up @@ -139,10 +139,33 @@ def update_or_create_activity(session, run_activity):
return created


def add_missing_columns(engine, model):
inspector = inspect(engine)
table_name = model.__tablename__
columns = {col['name'] for col in inspector.get_columns(table_name)}
missing_columns = []

for column in model.__table__.columns:
if column.name not in columns:
missing_columns.append(column)
if missing_columns:
with engine.connect() as conn:
for column in missing_columns:
column_type = str(column.type)
conn.execute(text(f'ALTER TABLE {table_name} ADD COLUMN {column.name} {column_type}'))


def init_db(db_path):
engine = create_engine(
f"sqlite:///{db_path}", connect_args={"check_same_thread": False}
)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)
return session()

# check missing columns
add_missing_columns(engine, Activity)

sm = sessionmaker(bind=engine)
session = sm()
# apply the changes
session.commit()
return session

0 comments on commit 4b5bbdd

Please sign in to comment.