pyBiocFileCache 0.5.1__py3-none-any.whl → 0.5.2.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.5.1
3
+ Version: 0.5.2.dev1
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -0,0 +1,15 @@
1
+ pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
+ pybiocfilecache/cache.py,sha256=Ij8-3-_4sTWLlSmXRqyIZXIZpNqKL2_j1u14EVS261w,22135
3
+ pybiocfilecache/config.py,sha256=hfknpMCzNk6wt84lTvbfH3Z0g66u_-2Fer3AftgDJBA,1040
4
+ pybiocfilecache/exceptions.py,sha256=8jrnctFYF7Rc1xsITtLUwKKvx8GMoKbarucyc-4f2zI,706
5
+ pybiocfilecache/models.py,sha256=A6BIrT78qqURxJoDvBjkDRBFV5cLdi3WKxreSCPB9tw,2125
6
+ pybiocfilecache/utils.py,sha256=lBK4BmzT6Z7XCn4j8kmhz9BPQpWT-RYfWvWC7YNtIGM,2291
7
+ pybiocfilecache/migrations/__init__.py,sha256=hGgAPQfmQKqZgGtEaB0FaHqDL3weTAPDTjewpUpZuEE,32
8
+ pybiocfilecache/migrations/migration.py,sha256=v9YEcOH9-x-6FLM_P1yXg-0506zZ98TdCCPuu4QPulE,4693
9
+ pybiocfilecache/migrations/migrationV0_5_0.py,sha256=yRoGmCmGQxAo7eZ3SLd64kCwovXWgU77NkxBMhzKVVA,3044
10
+ pyBiocFileCache-0.5.2.dev1.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
11
+ pyBiocFileCache-0.5.2.dev1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
12
+ pyBiocFileCache-0.5.2.dev1.dist-info/METADATA,sha256=kKv4GJRDnkS8sD7Floh5r1OrpBySIUtjQoj3GvoeC8Y,2996
13
+ pyBiocFileCache-0.5.2.dev1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
14
+ pyBiocFileCache-0.5.2.dev1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
15
+ pyBiocFileCache-0.5.2.dev1.dist-info/RECORD,,
pybiocfilecache/cache.py CHANGED
@@ -19,6 +19,7 @@ from .exceptions import (
19
19
  RnameExistsError,
20
20
  RpathTimeoutError,
21
21
  )
22
+ from .migrations import Migrator
22
23
  from .models import Base, Resource
23
24
  from .utils import (
24
25
  calculate_file_hash,
@@ -69,6 +70,29 @@ class BiocFileCache:
69
70
  self._setup_database()
70
71
  self._last_cleanup = datetime.now()
71
72
 
73
+ # Initialize migrator
74
+ self.migrator = Migrator(self.engine)
75
+
76
+ # Run migrations
77
+ try:
78
+ self.migrator.migrate()
79
+ except Exception as e:
80
+ logger.error(f"Failed to run migrations: {e}")
81
+ raise
82
+
83
+ def get_schema_version(self) -> str:
84
+ """Get current schema version."""
85
+ return self.migrator.get_current_version()
86
+
87
+ def migrate_schema(self, target_version: Optional[str] = None) -> None:
88
+ """Migrate schema to specified version.
89
+
90
+ Args:
91
+ target_version: Version to migrate to.
92
+ If None, migrates to latest version.
93
+ """
94
+ self.migrator.migrate(target_version)
95
+
72
96
  def _setup_cache_dir(self) -> None:
73
97
  if not self.config.cache_dir.exists():
74
98
  self.config.cache_dir.mkdir(parents=True, exist_ok=True)
@@ -0,0 +1 @@
1
+ from .migration import Migrator
@@ -0,0 +1,139 @@
1
+ import logging
2
+ from typing import Optional
3
+
4
+ from sqlalchemy import text
5
+ from sqlalchemy.engine import Engine
6
+
7
+ __author__ = "Jayaram Kancherla"
8
+ __copyright__ = "Jayaram Kancherla"
9
+ __license__ = "MIT"
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class Migration:
16
+ """Base class for migrations."""
17
+
18
+ version: str
19
+ description: str
20
+
21
+ @staticmethod
22
+ def up(engine: Engine) -> None:
23
+ """Upgrade to this version."""
24
+ raise NotImplementedError
25
+
26
+ @staticmethod
27
+ def down(engine: Engine) -> None:
28
+ """Downgrade from this version."""
29
+ raise NotImplementedError
30
+
31
+
32
+ class Migrator:
33
+ """Handles database schema migrations."""
34
+
35
+ def __init__(self, engine: Engine):
36
+ from .migrationV0_5_0 import MigrationV0_5_0
37
+
38
+ self.engine = engine
39
+ self.migrations = [MigrationV0_5_0]
40
+
41
+ def _detect_version_from_structure(self) -> str:
42
+ """Detect schema version by examining table structure."""
43
+ with self.engine.connect() as conn:
44
+ # Check table structure
45
+ columns = conn.execute(
46
+ text("""
47
+ PRAGMA table_info(resource);
48
+ """)
49
+ ).fetchall()
50
+ column_names = {col[1] for col in columns}
51
+
52
+ # Check for columns that indicate version
53
+ # if "is_compressed" in column_names:
54
+ # return "0.5.0"
55
+ if "tags" in column_names and "size_bytes" in column_names:
56
+ return "0.5.0"
57
+ else:
58
+ return "0.4.1"
59
+
60
+ def get_current_version(self) -> Optional[str]:
61
+ """Get current schema version from database.
62
+
63
+ Will attempt to detect version if `schema_version` is not in metadata.
64
+ """
65
+ with self.engine.connect() as conn:
66
+ result = conn.execute(
67
+ text("""
68
+ SELECT value FROM metadata
69
+ WHERE key = 'schema_version'
70
+ """)
71
+ )
72
+ row = result.fetchone()
73
+
74
+ if row is not None:
75
+ return row[0]
76
+
77
+ detected_version = self._detect_version_from_structure()
78
+ conn.execute(
79
+ text("""
80
+ INSERT INTO metadata (key, value)
81
+ VALUES ('schema_version', :version);
82
+ """),
83
+ {"version": detected_version},
84
+ )
85
+
86
+ return detected_version
87
+
88
+ def migrate(self, target_version: Optional[str] = None) -> None:
89
+ """Migrate schema to target version.
90
+
91
+ Args:
92
+ target_version:
93
+ Version to migrate to.
94
+ If None, migrates to latest version.
95
+ """
96
+ try:
97
+ current = self.get_current_version()
98
+ latest_version = self.migrations[-1].version
99
+ target_version = target_version or latest_version
100
+
101
+ if current == target_version:
102
+ logger.info("Already at target version")
103
+ return
104
+
105
+ if current == "0.4.1" and target_version == "0.5.0":
106
+ logger.info("Upgrading from 0.4.1 to 0.5.0")
107
+ self.migrations[0].up(self.engine)
108
+ elif current == "0.5.0" and target_version == "0.4.1":
109
+ logger.info("Downgrading from 0.5.0 to 0.4.1")
110
+ self.migrations[0].down(self.engine)
111
+ else:
112
+ raise ValueError(f"Unsupported migration path: {current} -> {target_version}")
113
+
114
+ except Exception as e:
115
+ logger.error(f"Migration failed: {e}")
116
+ raise
117
+
118
+ # When we have multiple migrations
119
+ # current_idx = next((i for i, m in enumerate(self.migrations) if m.version == current), None)
120
+ # target_idx = next((i for i, m in enumerate(self.migrations) if m.version == target_version), None)
121
+
122
+ # if current_idx is None:
123
+ # raise ValueError(f"Unknown current version: {current}")
124
+ # if target_idx is None:
125
+ # raise ValueError(f"Unknown target version: {target_version}")
126
+
127
+ # if current_idx < target_idx:
128
+ # # Upgrade
129
+ # for migration in self.migrations[current_idx : target_idx + 1]:
130
+ # logger.info(f"Upgrading to {migration.version}")
131
+ # migration.up(self.engine)
132
+ # elif current_idx > target_idx:
133
+ # # Downgrade
134
+ # for migration in reversed(self.migrations[target_idx + 1 : current_idx + 1]):
135
+ # logger.info(f"Downgrading from {migration.version}")
136
+ # migration.down(self.engine)
137
+
138
+ def __repr__(self) -> str:
139
+ return f"Migrator(current_version={self.get_current_version()})"
@@ -0,0 +1,102 @@
1
+ from sqlalchemy import text
2
+ from sqlalchemy.engine import Engine
3
+
4
+ from .migration import Migration
5
+
6
+ __author__ = "Jayaram Kancherla"
7
+ __copyright__ = "Jayaram Kancherla"
8
+ __license__ = "MIT"
9
+
10
+
11
+ class MigrationV0_5_0(Migration):
12
+ """Migration from v0.4.1 to 0.5.0."""
13
+
14
+ version = "0.5.0"
15
+ description = "Add tags, size_bytes, compression flag, and update indexes"
16
+
17
+ @staticmethod
18
+ def up(engine: Engine) -> None:
19
+ """Upgrade from v0.4.1 to v0.5.0."""
20
+ with engine.begin() as conn:
21
+ # Add new columns
22
+ conn.execute(
23
+ text("""
24
+ ALTER TABLE resource
25
+ ADD COLUMN tags TEXT;
26
+ """)
27
+ )
28
+ conn.execute(
29
+ text("""
30
+ ALTER TABLE resource
31
+ ADD COLUMN size_bytes INTEGER;
32
+ """)
33
+ )
34
+ # conn.execute(
35
+ # text("""
36
+ # ALTER TABLE resource
37
+ # ADD COLUMN is_compressed BOOLEAN DEFAULT FALSE;
38
+ # """)
39
+ # )
40
+
41
+ # Calculate size_bytes for existing resources
42
+ conn.execute(
43
+ text("""
44
+ UPDATE resource
45
+ SET size_bytes = (
46
+ SELECT length(readfile(rpath))
47
+ FROM resource r2
48
+ WHERE r2.id = resource.id
49
+ )
50
+ WHERE EXISTS (
51
+ SELECT 1
52
+ FROM resource r3
53
+ WHERE r3.id = resource.id
54
+ AND r3.rpath IS NOT NULL
55
+ );
56
+ """)
57
+ )
58
+
59
+ # Add indexes
60
+ conn.execute(
61
+ text("""
62
+ CREATE UNIQUE INDEX IF NOT EXISTS ix_resource_rname
63
+ ON resource(rname);
64
+ """)
65
+ )
66
+ conn.execute(
67
+ text("""
68
+ CREATE INDEX IF NOT EXISTS ix_resource_rid
69
+ ON resource(rid);
70
+ """)
71
+ )
72
+
73
+ # Update metadata
74
+ conn.execute(
75
+ text("""
76
+ UPDATE metadata
77
+ SET value = '0.5.0'
78
+ WHERE key = 'schema_version';
79
+ """)
80
+ )
81
+
82
+ @staticmethod
83
+ def down(engine: Engine) -> None:
84
+ """Downgrade from v0.5.0 to 0.4.1."""
85
+ with engine.begin() as conn:
86
+ # Remove indexes
87
+ conn.execute(text("DROP INDEX IF EXISTS ix_resource_rname;"))
88
+ conn.execute(text("DROP INDEX IF EXISTS ix_resource_rid;"))
89
+
90
+ # Remove columns
91
+ # conn.execute(text("ALTER TABLE resource DROP COLUMN is_compressed;"))
92
+ conn.execute(text("ALTER TABLE resource DROP COLUMN size_bytes;"))
93
+ conn.execute(text("ALTER TABLE resource DROP COLUMN tags;"))
94
+
95
+ # Update metadata
96
+ conn.execute(
97
+ text("""
98
+ UPDATE metadata
99
+ SET value = '0.4.1'
100
+ WHERE key = 'schema_version';
101
+ """)
102
+ )
@@ -1,13 +0,0 @@
1
- pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
- pybiocfilecache/cache.py,sha256=YOCur7R7209WBI6JEW3Q9VzD7ymu7Wj2DDLGEMFCeDo,21395
3
- pybiocfilecache/config.py,sha256=hfknpMCzNk6wt84lTvbfH3Z0g66u_-2Fer3AftgDJBA,1040
4
- pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
- pybiocfilecache/exceptions.py,sha256=8jrnctFYF7Rc1xsITtLUwKKvx8GMoKbarucyc-4f2zI,706
6
- pybiocfilecache/models.py,sha256=A6BIrT78qqURxJoDvBjkDRBFV5cLdi3WKxreSCPB9tw,2125
7
- pybiocfilecache/utils.py,sha256=lBK4BmzT6Z7XCn4j8kmhz9BPQpWT-RYfWvWC7YNtIGM,2291
8
- pyBiocFileCache-0.5.1.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
9
- pyBiocFileCache-0.5.1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
- pyBiocFileCache-0.5.1.dist-info/METADATA,sha256=N1hNP2VEuDt-u2maLQW9b5qmS7llNtkKgGUusWNpolU,2991
11
- pyBiocFileCache-0.5.1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
12
- pyBiocFileCache-0.5.1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
- pyBiocFileCache-0.5.1.dist-info/RECORD,,
pybiocfilecache/const.py DELETED
@@ -1 +0,0 @@
1
- SCHEMA_VERSION = "0.99.4"