|
| 1 | +# I have archived this file here even though it is not in alembic format beacuse |
| 2 | +# this is one of the early database migrations we did when we changed banzai to track |
| 3 | +# instruments and cameras rather than just telescopes. Future migrations of this type |
| 4 | +# will use alembic. |
| 5 | + |
| 6 | +import argparse |
| 7 | + |
| 8 | +from sqlalchemy import create_engine |
| 9 | +from sqlalchemy import Column, Integer, String, Date, ForeignKey, Boolean, CHAR |
| 10 | +from sqlalchemy.ext.declarative import declarative_base |
| 11 | + |
| 12 | +from banzai import dbs, logs |
| 13 | + |
| 14 | +logger = logs.get_logger() |
| 15 | + |
| 16 | +Base = declarative_base() |
| 17 | + |
| 18 | + |
| 19 | +# The five base classes below are taken from Banzai version < 0.16.0 |
| 20 | +class CalibrationImage(Base): |
| 21 | + __tablename__ = 'calimages' |
| 22 | + id = Column(Integer, primary_key=True, autoincrement=True) |
| 23 | + type = Column(String(30), index=True) |
| 24 | + filename = Column(String(50), unique=True) |
| 25 | + filepath = Column(String(100)) |
| 26 | + dayobs = Column(Date, index=True) |
| 27 | + ccdsum = Column(String(20)) |
| 28 | + filter_name = Column(String(32)) |
| 29 | + telescope_id = Column(Integer, ForeignKey("telescopes.id"), index=True) |
| 30 | + |
| 31 | + |
| 32 | +class Telescope(Base): |
| 33 | + __tablename__ = 'telescopes' |
| 34 | + id = Column(Integer, primary_key=True, autoincrement=True) |
| 35 | + site = Column(String(10), ForeignKey('sites.id'), index=True) |
| 36 | + instrument = Column(String(20), index=True) |
| 37 | + camera_type = Column(String(20)) |
| 38 | + schedulable = Column(Boolean, default=False) |
| 39 | + |
| 40 | + |
| 41 | +class Site(Base): |
| 42 | + __tablename__ = 'sites' |
| 43 | + id = Column(String(3), primary_key=True) |
| 44 | + timezone = Column(Integer) |
| 45 | + |
| 46 | + |
| 47 | +class BadPixelMask(Base): |
| 48 | + __tablename__ = 'bpms' |
| 49 | + id = Column(Integer, primary_key=True, autoincrement=True) |
| 50 | + telescope_id = Column(Integer, ForeignKey("telescopes.id"), index=True) |
| 51 | + filename = Column(String(50)) |
| 52 | + filepath = Column(String(100)) |
| 53 | + ccdsum = Column(String(20)) |
| 54 | + creation_date = Column(Date) |
| 55 | + |
| 56 | + |
| 57 | +class PreviewImage(Base): |
| 58 | + __tablename__ = 'previewimages' |
| 59 | + id = Column(Integer, primary_key=True, autoincrement=True) |
| 60 | + filename = Column(String(50), index=True) |
| 61 | + checksum = Column(CHAR(32), index=True, default='0'*32) |
| 62 | + success = Column(Boolean, default=False) |
| 63 | + tries = Column(Integer, default=0) |
| 64 | + |
| 65 | + |
| 66 | +def create_new_db(db_address): |
| 67 | + engine = create_engine(db_address) |
| 68 | + dbs.Base.metadata.create_all(engine) |
| 69 | + |
| 70 | + |
| 71 | +def base_to_dict(base): |
| 72 | + return [{key: value for key, value in row.__dict__.items() if not key.startswith('_')} for row in base] |
| 73 | + |
| 74 | + |
| 75 | +def change_key_name(row_list, old_key, new_key): |
| 76 | + for row in row_list: |
| 77 | + row[new_key] = row.pop(old_key) |
| 78 | + |
| 79 | + |
| 80 | +def add_rows(db_session, base, row_list, max_chunk_size=100000): |
| 81 | + for i in range(0, len(row_list), max_chunk_size): |
| 82 | + logger.debug("Inserting rows {a} to {b}".format(a=i+1, b=min(i+max_chunk_size, len(row_list)))) |
| 83 | + db_session.bulk_insert_mappings(base, row_list[i:i + max_chunk_size]) |
| 84 | + db_session.commit() |
| 85 | + |
| 86 | + |
| 87 | +def migrate_db(): |
| 88 | + |
| 89 | + parser = argparse.ArgumentParser() |
| 90 | + parser.add_argument('old_db_address', |
| 91 | + help='Old database address to be migrated: Should be in SQLAlchemy form') |
| 92 | + parser.add_argument('new_db_address', |
| 93 | + help='New database address: Should be in SQLAlchemy form') |
| 94 | + parser.add_argument("--log-level", default='debug', choices=['debug', 'info', 'warning', |
| 95 | + 'critical', 'fatal', 'error']) |
| 96 | + args = parser.parse_args() |
| 97 | + |
| 98 | + logs.set_log_level(args.log_level) |
| 99 | + logger.info("Creating new DB {new_db_address} from old DB {old_db_address}".format( |
| 100 | + new_db_address=args.new_db_address, old_db_address=args.old_db_address)) |
| 101 | + create_new_db(args.new_db_address) |
| 102 | + |
| 103 | + with dbs.get_session(db_address=args.old_db_address) as old_db_session, dbs.get_session(db_address=args.new_db_address) as new_db_session: |
| 104 | + |
| 105 | + # First copy sites table |
| 106 | + logger.info("Querying and organizing the old Site table") |
| 107 | + sites = base_to_dict(old_db_session.query(Site).all()) |
| 108 | + logger.info("Adding {n} rows from the old Site table to the new Site table".format(n=len(sites))) |
| 109 | + add_rows(new_db_session, dbs.Site, sites) |
| 110 | + |
| 111 | + # Move Telescope to Instrument with a couple of variable renames |
| 112 | + logger.info("Querying and organizing the old Telescope table") |
| 113 | + telescopes = base_to_dict(old_db_session.query(Telescope).all()) |
| 114 | + change_key_name(telescopes, 'instrument', 'camera') |
| 115 | + change_key_name(telescopes, 'camera_type', 'type') |
| 116 | + logger.info("Adding {n} rows from the old Telescope table to the new Instrument table".format( |
| 117 | + n=len(telescopes))) |
| 118 | + add_rows(new_db_session, dbs.Instrument, telescopes) |
| 119 | + |
| 120 | + # Move old BPMs to CalibrationImage |
| 121 | + logger.info("Querying and organizing the old BadPixelMask table") |
| 122 | + bpms = base_to_dict(old_db_session.query(BadPixelMask).all()) |
| 123 | + for row in bpms: |
| 124 | + row['type'] = 'BPM' |
| 125 | + row['is_master'] = True |
| 126 | + row['attributes'] = {'ccdsum': row.pop('ccdsum')} |
| 127 | + del row['id'] |
| 128 | + change_key_name(bpms, 'creation_date', 'dateobs') |
| 129 | + change_key_name(bpms, 'telescope_id', 'instrument_id') |
| 130 | + # BPMs have some duplicates, remove them |
| 131 | + already_seen = [] |
| 132 | + bpms_pruned = [] |
| 133 | + for row in bpms: |
| 134 | + if row['filename'] not in already_seen: |
| 135 | + bpms_pruned.append(row) |
| 136 | + already_seen.append(row['filename']) |
| 137 | + logger.info("Adding {n} rows from the old BadPixelMask table to the new CalibrationImage table".format( |
| 138 | + n=len(bpms_pruned))) |
| 139 | + add_rows(new_db_session, dbs.CalibrationImage, bpms_pruned) |
| 140 | + |
| 141 | + # Convert old CalibrationImage to new type |
| 142 | + logger.info("Querying and organizing the old CalibrationsImage table") |
| 143 | + calibrations = base_to_dict(old_db_session.query(CalibrationImage).all()) |
| 144 | + for row in calibrations: |
| 145 | + row['is_master'] = True |
| 146 | + row['attributes'] = {'filter': row.pop('filter_name'), 'ccdsum': row.pop('ccdsum')} |
| 147 | + del row['id'] |
| 148 | + change_key_name(calibrations, 'dayobs', 'dateobs') |
| 149 | + change_key_name(calibrations, 'telescope_id', 'instrument_id') |
| 150 | + logger.info("Adding {n} rows from the old CalibrationImage table to the new CalibrationImage table".format( |
| 151 | + n=len(calibrations))) |
| 152 | + add_rows(new_db_session, dbs.CalibrationImage, calibrations) |
| 153 | + |
| 154 | + # Copy the PreviewImage table to ProcssedImage (attributes are all the same) |
| 155 | + logger.info("Querying and organizing the old PreviewImage table") |
| 156 | + preview_images = base_to_dict(old_db_session.query(PreviewImage).all()) |
| 157 | + logger.info("Adding {n} rows from the old PreviewImage table to the new ProcessedImage table".format( |
| 158 | + n=len(preview_images))) |
| 159 | + add_rows(new_db_session, dbs.ProcessedImage, preview_images) |
| 160 | + |
| 161 | + logger.info("Finished") |
0 commit comments