Debian Codegraph @

jupyter_cache/cache/db.py

raw
1 from contextlib import contextmanager
2 from datetime import datetime
3 import os
4 from pathlib import Path
5 from typing import Any, Dict, List, Optional, Union
6
7 from sqlalchemy import JSON, Column, DateTime, Integer, String, Text
8 from sqlalchemy.engine import Engine, create_engine
9 from sqlalchemy.exc import IntegrityError, OperationalError
10
11 try:
12 from sqlalchemy.orm import declarative_base # sqlalchemy >= 1.4.0
13 except ImportError:
14 from sqlalchemy.ext.declarative import declarative_base # sqlalchemy < 1.4.0
15
16 from sqlalchemy.orm import sessionmaker, validates
17 from sqlalchemy.sql.expression import desc
18
19 from jupyter_cache import __version__
20 from jupyter_cache.utils import shorten_path
21
22 OrmBase = declarative_base()
23 DB_NAME = "global.db"
24
25 # version changes:
26 # 0.5.0:
27 # - __version__.txt file written to cache on creation
28 # - table: nbstage -> nbproject
29 # - added read_data and exec_data fields to nbproject
30
31
32 def create_db(path: Union[str, Path]) -> Engine:
33 """Get or create a database at the given path.
34
35 :param path: The path to the cache folder.
36 """
37 exists = (Path(path) / DB_NAME).exists()
38 engine = create_engine(f"sqlite:///{os.path.join(path, DB_NAME)}")
39 if not exists:
40 # add all the tables, and a version identifier
41 OrmBase.metadata.create_all(engine)
42 Path(path).joinpath("__version__.txt").write_text(__version__)
43
44 return engine
45
46
47 def get_version(path: Union[str, Path]) -> Optional[str]:
48 """Attempt to get the version of the cache."""
49 version_file = Path(path).joinpath("__version__.txt")
50 if version_file.exists():
51 return version_file.read_text().strip()
52
53
54 @contextmanager
55 def session_context(engine: Engine):
56 """Open a connection to the database."""
57 session = sessionmaker(bind=engine)()
58 try:
59 yield session
60 except OperationalError as exc:
61 session.rollback()
62 raise RuntimeError(
63 "Unexpected error accessing jupyter cache, it may need to be cleared."
64 ) from exc
65 except Exception:
66 session.rollback()
67 raise
68 finally:
69 session.close()
70
71
72 class Setting(OrmBase):
73 """A settings key/value pair representation."""
74
75 __tablename__ = "settings"
76
77 pk = Column(Integer(), primary_key=True)
78 key = Column(String(36), nullable=False, unique=True)
79 value = Column(JSON())
80
81 def __repr__(self):
82 return "{}(pk={},{}={})".format(
83 self.__class__.__name__, self.pk, self.key, self.value
84 )
85
86 @staticmethod
87 def set_value(key: str, value, db: Engine):
88 with session_context(db) as session: # type: Session
89 setting = session.query(Setting).filter_by(key=key).one_or_none()
90 if setting is None:
91 session.add(Setting(key=key, value=value))
92 else:
93 setting.value = value
94 try:
95 session.commit()
96 except IntegrityError:
97 raise TypeError(value)
98
99 @staticmethod
100 def get_value(key: str, db: Engine, default=None):
101 with session_context(db) as session: # type: Session
102 result = session.query(Setting.value).filter_by(key=key).one_or_none()
103 if result is None:
104 if default is not None:
105 result = [default]
106 else:
107 raise KeyError(f"Setting not found in DB: {key}")
108 value = result[0]
109 return value
110
111 @staticmethod
112 def get_dict(db: Engine) -> dict:
113 with session_context(db) as session: # type: Session
114 results = session.query(Setting.key, Setting.value).all()
115 return {k: v for k, v in results}
116
117
118 class NbProjectRecord(OrmBase):
119 """A record of a notebook within the project."""
120
121 __tablename__ = "nbproject"
122
123 pk = Column(Integer(), primary_key=True)
124 uri = Column(String(255), nullable=False, unique=True)
125 read_data = Column(JSON(), nullable=False)
126 """Data on how to read the uri to a notebook."""
127 assets = Column(JSON(), nullable=False, default=list)
128 """A list of file assets required for the notebook to run."""
129 exec_data = Column(JSON(), nullable=True)
130 """Data on how to execute the notebook."""
131 created = Column(DateTime, nullable=False, default=datetime.utcnow)
132 traceback = Column(Text(), nullable=True, default="")
133 """A traceback is added if a notebook fails to execute fully."""
134
135 def __repr__(self):
136 return f"{self.__class__.__name__}(pk={self.pk})"
137
138 def to_dict(self):
139 return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
140
141 def format_dict(
142 self,
143 cache_record: Optional["NbCacheRecord"] = None,
144 path_length: Optional[int] = None,
145 assets: bool = True,
146 read_error: Optional[str] = None,
147 read_name: bool = True,
148 ) -> dict:
149 """Return data for display."""
150 status = "-"
151 if cache_record:
152 status = f"✅ [{cache_record.pk}]"
153 elif self.traceback:
154 status = "❌"
155 elif read_error:
156 status = "❗️ (unreadable)"
157 data = {
158 "ID": self.pk,
159 "URI": str(shorten_path(self.uri, path_length)),
160 "Reader": self.read_data.get("name", "-") if read_name else self.read_data,
161 "Added": self.created.isoformat(" ", "minutes"),
162 "Status": status,
163 }
164 if assets:
165 data["Assets"] = len(self.assets)
166 return data
167
168 @validates("read_data")
169 def validate_read_data(self, key, value):
170 if not isinstance(value, dict):
171 raise ValueError("read_data must be a dict")
172 if "name" not in value:
173 raise ValueError("read_data must have a name")
174 return value
175
176 @validates("assets")
177 def validator_assets(self, key, value):
178 return self.validate_assets(value)
179
180 @staticmethod
181 def validate_assets(paths, uri=None):
182 """Validate asset paths are within same folder as the notebook URI"""
183 if not (
184 isinstance(paths, (list, tuple)) and all(isinstance(v, str) for v in paths)
185 ):
186 raise TypeError(f"assets must be interable of strings: {paths}")
187 if uri is None:
188 return list(paths)
189
190 uri_folder = Path(uri).parent
191 for path in paths:
192 try:
193 Path(path).relative_to(uri_folder)
194 except ValueError:
195 raise ValueError(f"Asset '{path}' is not in folder '{uri_folder}''")
196 return list(paths)
197
198 @staticmethod
199 def create_record(
200 uri: str,
201 db: Engine,
202 read_data: Dict[str, Any],
203 raise_on_exists=True,
204 *,
205 assets=(),
206 ) -> "NbProjectRecord":
207 assets = NbProjectRecord.validate_assets(assets, uri)
208 with session_context(db) as session: # type: Session
209 record = NbProjectRecord(uri=uri, read_data=read_data, assets=assets)
210 session.add(record)
211 try:
212 session.commit()
213 except IntegrityError:
214 if raise_on_exists:
215 raise ValueError(f"URI already in project: {uri}")
216 return NbProjectRecord.record_from_uri(uri, db)
217 session.refresh(record)
218 session.expunge(record)
219 return record
220
221 def remove_pks(pks: List[int], db: Engine):
222 with session_context(db) as session: # type: Session
223 session.query(NbProjectRecord).filter(NbProjectRecord.pk.in_(pks)).delete(
224 synchronize_session=False
225 )
226 session.commit()
227
228 def remove_uris(uris: List[str], db: Engine):
229 with session_context(db) as session: # type: Session
230 session.query(NbProjectRecord).filter(NbProjectRecord.uri.in_(uris)).delete(
231 synchronize_session=False
232 )
233 session.commit()
234
235 @staticmethod
236 def record_from_pk(pk: int, db: Engine) -> "NbProjectRecord":
237 with session_context(db) as session: # type: Session
238 result = session.query(NbProjectRecord).filter_by(pk=pk).one_or_none()
239 if result is None:
240 raise KeyError(f"Project record not found for NB with PK: {pk}")
241 session.expunge(result)
242 return result
243
244 @staticmethod
245 def record_from_uri(uri: str, db: Engine) -> "NbProjectRecord":
246 with session_context(db) as session: # type: Session
247 result = session.query(NbProjectRecord).filter_by(uri=uri).one_or_none()
248 if result is None:
249 raise KeyError(f"Project record not found for NB with URI: {uri}")
250 session.expunge(result)
251 return result
252
253 @staticmethod
254 def records_all(db: Engine) -> "NbProjectRecord":
255 with session_context(db) as session: # type: Session
256 results = session.query(NbProjectRecord).order_by(NbProjectRecord.pk).all()
257 session.expunge_all()
258 return results
259
260 def remove_tracebacks(pks, db: Engine):
261 """Remove all tracebacks."""
262 with session_context(db) as session: # type: Session
263 session.query(NbProjectRecord).filter(NbProjectRecord.pk.in_(pks)).update(
264 {NbProjectRecord.traceback: None}, synchronize_session=False
265 )
266 session.commit()
267
268 def set_traceback(uri: str, traceback: Optional[str], db: Engine):
269 with session_context(db) as session: # type: Session
270 result = session.query(NbProjectRecord).filter_by(uri=uri).one_or_none()
271 if result is None:
272 raise KeyError(f"Project record not found for NB with URI: {uri}")
273 result.traceback = traceback
274 try:
275 session.commit()
276 except IntegrityError:
277 raise TypeError(traceback)
278
279
280 class NbCacheRecord(OrmBase):
281 """A record of an executed notebook cache."""
282
283 __tablename__ = "nbcache"
284
285 pk = Column(Integer(), primary_key=True)
286 hashkey = Column(String(255), nullable=False, unique=True)
287 uri = Column(String(255), nullable=False, unique=False)
288 description = Column(String(255), nullable=False, default="")
289 data = Column(JSON())
290 """Extra data, such as the execution time."""
291 created = Column(DateTime, nullable=False, default=datetime.utcnow)
292 accessed = Column(
293 DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow
294 )
295
296 def __repr__(self):
297 return f"{self.__class__.__name__}(pk={self.pk})"
298
299 def to_dict(self):
300 return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
301
302 def format_dict(
303 self, hashkey=False, path_length=None, show_descript=False, show_data=True
304 ):
305 data = {
306 "ID": self.pk,
307 "Origin URI": str(shorten_path(self.uri, path_length)),
308 "Created": self.created.isoformat(" ", "minutes"),
309 "Accessed": self.accessed.isoformat(" ", "minutes"),
310 }
311 if show_descript:
312 data["Description"] = self.description
313 if hashkey:
314 data["Hashkey"] = self.hashkey
315 if show_data and self.data:
316 data["Data"] = self.data
317 return data
318
319 @staticmethod
320 def create_record(uri: str, hashkey: str, db: Engine, **kwargs) -> "NbCacheRecord":
321 with session_context(db) as session: # type: Session
322 record = NbCacheRecord(hashkey=hashkey, uri=uri, **kwargs)
323 session.add(record)
324 try:
325 session.commit()
326 except IntegrityError:
327 raise ValueError(f"hashkey already exists:{hashkey}")
328 session.refresh(record)
329 session.expunge(record)
330 return record
331
332 def remove_record(pk: int, db: Engine):
333 with session_context(db) as session: # type: Session
334 record = session.get(NbCacheRecord, pk)
335 session.delete(record)
336 session.commit()
337
338 def remove_records(pks: List[int], db: Engine):
339 with session_context(db) as session: # type: Session
340 session.query(NbCacheRecord).filter(NbCacheRecord.pk.in_(pks)).delete(
341 synchronize_session=False
342 )
343 session.commit()
344
345 @staticmethod
346 def record_from_hashkey(hashkey: str, db: Engine) -> "NbCacheRecord":
347 with session_context(db) as session: # type: Session
348 result = (
349 session.query(NbCacheRecord).filter_by(hashkey=hashkey).one_or_none()
350 )
351 if result is None:
352 raise KeyError(f"Cache record not found for NB with hashkey: {hashkey}")
353 session.expunge(result)
354 return result
355
356 @staticmethod
357 def record_from_pk(pk: int, db: Engine) -> "NbCacheRecord":
358 with session_context(db) as session: # type: Session
359 result = session.query(NbCacheRecord).filter_by(pk=pk).one_or_none()
360 if result is None:
361 raise KeyError(f"Cache record not found for NB with PK: {pk}")
362 session.expunge(result)
363 return result
364
365 def touch(pk, db: Engine):
366 """Touch a record, to change its last accessed time."""
367 with session_context(db) as session: # type: Session
368 record = session.query(NbCacheRecord).filter_by(pk=pk).one_or_none()
369 if record is None:
370 raise KeyError(f"Cache record not found for NB with PK: {pk}")
371 record.accessed = datetime.utcnow()
372 session.commit()
373
374 def touch_hashkey(hashkey, db: Engine):
375 """Touch a record, to change its last accessed time."""
376 with session_context(db) as session: # type: Session
377 record = (
378 session.query(NbCacheRecord).filter_by(hashkey=hashkey).one_or_none()
379 )
380 if record is None:
381 raise KeyError(f"Cache record not found for NB with hashkey: {hashkey}")
382 record.accessed = datetime.utcnow()
383 session.commit()
384
385 @staticmethod
386 def records_from_uri(uri: str, db: Engine) -> "NbCacheRecord":
387 with session_context(db) as session: # type: Session
388 results = session.query(NbCacheRecord).filter_by(uri=uri).all()
389 session.expunge_all()
390 return results
391
392 @staticmethod
393 def records_all(db: Engine) -> "NbCacheRecord":
394 with session_context(db) as session: # type: Session
395 results = session.query(NbCacheRecord).all()
396 session.expunge_all()
397 return results
398
399 def records_to_delete(keep: int, db: Engine) -> List[int]:
400 """Return pks of the oldest records, where keep is number to keep."""
401 with session_context(db) as session: # type: Session
402 pks_to_keep = [
403 pk
404 for pk, in session.query(NbCacheRecord.pk)
405 .order_by(desc("accessed"))
406 .limit(keep)
407 .all()
408 ]
409 pks_to_delete = [
410 pk
411 for pk, in session.query(NbCacheRecord.pk)
412 .filter(NbCacheRecord.pk.notin_(pks_to_keep))
413 .all()
414 ]
415 return pks_to_delete