|
| 1 | +import datajoint as dj |
| 2 | +from pathlib import Path |
| 3 | +import re |
| 4 | +from .utils import user_choice |
| 5 | + |
| 6 | + |
| 7 | +def migrate_dj011_external_blob_storage_to_dj012(migration_schema, store): |
| 8 | + """ |
| 9 | + Utility function to migrate external blob data from 0.11 to 0.12. |
| 10 | + :param migration_schema: string of target schema to be migrated |
| 11 | + :param store: string of target dj.config['store'] to be migrated |
| 12 | + """ |
| 13 | + if not isinstance(migration_schema, str): |
| 14 | + raise ValueError( |
| 15 | + 'Expected type {} for migration_schema, not {}.'.format( |
| 16 | + str, type(migration_schema))) |
| 17 | + |
| 18 | + do_migration = False |
| 19 | + do_migration = user_choice( |
| 20 | + """ |
| 21 | +Warning: Ensure the following are completed before proceeding. |
| 22 | +- Appropriate backups have been taken, |
| 23 | +- Any existing DJ 0.11.X connections are suspended, and |
| 24 | +- External config has been updated to new dj.config['stores'] structure. |
| 25 | +Proceed? |
| 26 | + """, default='no') == 'yes' |
| 27 | + if do_migration: |
| 28 | + _migrate_dj011_blob(dj.schema(migration_schema), store) |
| 29 | + print('Migration completed for schema: {}, store: {}.'.format( |
| 30 | + migration_schema, store)) |
| 31 | + return |
| 32 | + print('No migration performed.') |
| 33 | + |
| 34 | + |
| 35 | +def _migrate_dj011_blob(schema, default_store): |
| 36 | + query = schema.connection.query |
| 37 | + |
| 38 | + LEGACY_HASH_SIZE = 43 |
| 39 | + |
| 40 | + legacy_external = dj.FreeTable( |
| 41 | + schema.connection, |
| 42 | + '`{db}`.`~external`'.format(db=schema.database)) |
| 43 | + |
| 44 | + # get referencing tables |
| 45 | + refs = query(""" |
| 46 | + SELECT concat('`', table_schema, '`.`', table_name, '`') |
| 47 | + as referencing_table, column_name, constraint_name |
| 48 | + FROM information_schema.key_column_usage |
| 49 | + WHERE referenced_table_name="{tab}" and referenced_table_schema="{db}" |
| 50 | + """.format( |
| 51 | + tab=legacy_external.table_name, |
| 52 | + db=legacy_external.database), as_dict=True).fetchall() |
| 53 | + |
| 54 | + for ref in refs: |
| 55 | + # get comment |
| 56 | + column = query( |
| 57 | + 'SHOW FULL COLUMNS FROM {referencing_table}' |
| 58 | + 'WHERE Field="{column_name}"'.format( |
| 59 | + **ref), as_dict=True).fetchone() |
| 60 | + |
| 61 | + store, comment = re.match( |
| 62 | + r':external(-(?P<store>.+))?:(?P<comment>.*)', |
| 63 | + column['Comment']).group('store', 'comment') |
| 64 | + |
| 65 | + # get all the hashes from the reference |
| 66 | + hashes = {x[0] for x in query( |
| 67 | + 'SELECT `{column_name}` FROM {referencing_table}'.format( |
| 68 | + **ref))} |
| 69 | + |
| 70 | + # sanity check make sure that store suffixes match |
| 71 | + if store is None: |
| 72 | + assert all(len(_) == LEGACY_HASH_SIZE for _ in hashes) |
| 73 | + else: |
| 74 | + assert all(_[LEGACY_HASH_SIZE:] == store for _ in hashes) |
| 75 | + |
| 76 | + # create new-style external table |
| 77 | + ext = schema.external[store or default_store] |
| 78 | + |
| 79 | + # add the new-style reference field |
| 80 | + temp_suffix = 'tempsub' |
| 81 | + |
| 82 | + try: |
| 83 | + query("""ALTER TABLE {referencing_table} |
| 84 | + ADD COLUMN `{column_name}_{temp_suffix}` {type} DEFAULT NULL |
| 85 | + COMMENT ":blob@{store}:{comment}" |
| 86 | + """.format( |
| 87 | + type=dj.declare.UUID_DATA_TYPE, |
| 88 | + temp_suffix=temp_suffix, |
| 89 | + store=(store or default_store), comment=comment, **ref)) |
| 90 | + except: |
| 91 | + print('Column already added') |
| 92 | + pass |
| 93 | + |
| 94 | + # Copy references into the new external table |
| 95 | + # No Windows! Backslashes will cause problems |
| 96 | + |
| 97 | + contents_hash_function = { |
| 98 | + 'file': lambda ext, relative_path: dj.hash.uuid_from_file( |
| 99 | + str(Path(ext.spec['location'], relative_path))), |
| 100 | + 's3': lambda ext, relative_path: dj.hash.uuid_from_buffer( |
| 101 | + ext.s3.get(relative_path)) |
| 102 | + } |
| 103 | + |
| 104 | + for _hash, size in zip(*legacy_external.fetch('hash', 'size')): |
| 105 | + if _hash in hashes: |
| 106 | + relative_path = str(Path(schema.database, _hash).as_posix()) |
| 107 | + uuid = dj.hash.uuid_from_buffer(init_string=relative_path) |
| 108 | + external_path = ext._make_external_filepath(relative_path) |
| 109 | + if ext.spec['protocol'] == 's3': |
| 110 | + contents_hash = dj.hash.uuid_from_buffer(ext._download_buffer(external_path)) |
| 111 | + else: |
| 112 | + contents_hash = dj.hash.uuid_from_file(external_path) |
| 113 | + ext.insert1(dict( |
| 114 | + filepath=relative_path, |
| 115 | + size=size, |
| 116 | + contents_hash=contents_hash, |
| 117 | + hash=uuid |
| 118 | + ), skip_duplicates=True) |
| 119 | + |
| 120 | + query( |
| 121 | + 'UPDATE {referencing_table} ' |
| 122 | + 'SET `{column_name}_{temp_suffix}`=%s ' |
| 123 | + 'WHERE `{column_name}` = "{_hash}"' |
| 124 | + .format( |
| 125 | + _hash=_hash, |
| 126 | + temp_suffix=temp_suffix, **ref), uuid.bytes) |
| 127 | + |
| 128 | + # check that all have been copied |
| 129 | + check = query( |
| 130 | + 'SELECT * FROM {referencing_table} ' |
| 131 | + 'WHERE `{column_name}` IS NOT NULL' |
| 132 | + ' AND `{column_name}_{temp_suffix}` IS NULL' |
| 133 | + .format(temp_suffix=temp_suffix, **ref)).fetchall() |
| 134 | + |
| 135 | + assert len(check) == 0, 'Some hashes havent been migrated' |
| 136 | + |
| 137 | + # drop old foreign key, rename, and create new foreign key |
| 138 | + query(""" |
| 139 | + ALTER TABLE {referencing_table} |
| 140 | + DROP FOREIGN KEY `{constraint_name}`, |
| 141 | + DROP COLUMN `{column_name}`, |
| 142 | + CHANGE COLUMN `{column_name}_{temp_suffix}` `{column_name}` |
| 143 | + {type} DEFAULT NULL |
| 144 | + COMMENT ":blob@{store}:{comment}", |
| 145 | + ADD FOREIGN KEY (`{column_name}`) REFERENCES {ext_table_name} |
| 146 | + (`hash`) |
| 147 | + """.format( |
| 148 | + temp_suffix=temp_suffix, |
| 149 | + ext_table_name=ext.full_table_name, |
| 150 | + type=dj.declare.UUID_DATA_TYPE, |
| 151 | + store=(store or default_store), comment=comment, **ref)) |
| 152 | + |
| 153 | + # Drop the old external table but make sure it's no longer referenced |
| 154 | + # get referencing tables |
| 155 | + refs = query(""" |
| 156 | + SELECT concat('`', table_schema, '`.`', table_name, '`') as |
| 157 | + referencing_table, column_name, constraint_name |
| 158 | + FROM information_schema.key_column_usage |
| 159 | + WHERE referenced_table_name="{tab}" and referenced_table_schema="{db}" |
| 160 | + """.format( |
| 161 | + tab=legacy_external.table_name, |
| 162 | + db=legacy_external.database), as_dict=True).fetchall() |
| 163 | + |
| 164 | + assert not refs, 'Some references still exist' |
| 165 | + |
| 166 | + # drop old external table |
| 167 | + legacy_external.drop_quick() |
0 commit comments