Coverage for python/lsst/daf/butler/core/storedFileInfo.py: 47%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = ("StoredFileInfo", "StoredDatastoreItemInfo")
26import inspect
27from dataclasses import dataclass
28from typing import TYPE_CHECKING, Any, Dict, Optional, Type
30from lsst.resources import ResourcePath
32from .formatter import Formatter, FormatterParameter
33from .location import Location, LocationFactory
34from .storageClass import StorageClass, StorageClassFactory
36if TYPE_CHECKING: 36 ↛ 37line 36 didn't jump to line 37, because the condition on line 36 was never true
37 from .datasets import DatasetRef
39# String to use when a Python None is encountered
40NULLSTR = "__NULL_STRING__"
43class StoredDatastoreItemInfo:
44 """Internal information associated with a stored dataset in a `Datastore`.
46 This is an empty base class. Datastore implementations are expected to
47 write their own subclasses.
48 """
50 __slots__ = ()
52 def file_location(self, factory: LocationFactory) -> Location:
53 """Return the location of artifact.
55 Parameters
56 ----------
57 factory : `LocationFactory`
58 Factory relevant to the datastore represented by this item.
60 Returns
61 -------
62 location : `Location`
63 The location of the item within this datastore.
64 """
65 raise NotImplementedError("The base class does not know how to locate an item in a datastore.")
67 @classmethod
68 def from_record(cls: Type[StoredDatastoreItemInfo], record: Dict[str, Any]) -> StoredDatastoreItemInfo:
69 """Create instance from database record.
71 Parameters
72 ----------
73 record : `dict`
74 The record associated with this item.
76 Returns
77 -------
78 info : instance of the relevant type.
79 The newly-constructed item corresponding to the record.
80 """
81 raise NotImplementedError()
84@dataclass(frozen=True)
85class StoredFileInfo(StoredDatastoreItemInfo):
86 """Datastore-private metadata associated with a Datastore file."""
88 __slots__ = {"formatter", "path", "storageClass", "component", "checksum", "file_size"}
90 storageClassFactory = StorageClassFactory()
92 def __init__(
93 self,
94 formatter: FormatterParameter,
95 path: str,
96 storageClass: StorageClass,
97 component: Optional[str],
98 checksum: Optional[str],
99 file_size: int,
100 ):
102 # Use these shenanigans to allow us to use a frozen dataclass
103 object.__setattr__(self, "path", path)
104 object.__setattr__(self, "storageClass", storageClass)
105 object.__setattr__(self, "component", component)
106 object.__setattr__(self, "checksum", checksum)
107 object.__setattr__(self, "file_size", file_size)
109 if isinstance(formatter, str):
110 # We trust that this string refers to a Formatter
111 formatterStr = formatter
112 elif isinstance(formatter, Formatter) or (
113 inspect.isclass(formatter) and issubclass(formatter, Formatter)
114 ):
115 formatterStr = formatter.name()
116 else:
117 raise TypeError(f"Supplied formatter '{formatter}' is not a Formatter")
118 object.__setattr__(self, "formatter", formatterStr)
120 formatter: str
121 """Fully-qualified name of Formatter. If a Formatter class or instance
122 is given the name will be extracted."""
124 path: str
125 """Path to dataset within Datastore."""
127 storageClass: StorageClass
128 """StorageClass associated with Dataset."""
130 component: Optional[str]
131 """Component associated with this file. Can be None if the file does
132 not refer to a component of a composite."""
134 checksum: Optional[str]
135 """Checksum of the serialized dataset."""
137 file_size: int
138 """Size of the serialized dataset in bytes."""
140 def to_record(self, ref: DatasetRef) -> Dict[str, Any]:
141 """Convert the supplied ref to a database record."""
142 component = ref.datasetType.component()
143 if component is None and self.component is not None:
144 component = self.component
145 if component is None:
146 # Use empty string since we want this to be part of the
147 # primary key.
148 component = NULLSTR
150 return dict(
151 dataset_id=ref.id,
152 formatter=self.formatter,
153 path=self.path,
154 storage_class=self.storageClass.name,
155 component=component,
156 checksum=self.checksum,
157 file_size=self.file_size,
158 )
160 def file_location(self, factory: LocationFactory) -> Location:
161 """Return the location of artifact.
163 Parameters
164 ----------
165 factory : `LocationFactory`
166 Factory relevant to the datastore represented by this item.
168 Returns
169 -------
170 location : `Location`
171 The location of the item within this datastore.
172 """
173 uriInStore = ResourcePath(self.path, forceAbsolute=False)
174 if uriInStore.isabs():
175 location = Location(None, uriInStore)
176 else:
177 location = factory.fromPath(uriInStore)
178 return location
180 @classmethod
181 def from_record(cls: Type[StoredFileInfo], record: Dict[str, Any]) -> StoredFileInfo:
182 """Create instance from database record.
184 Parameters
185 ----------
186 record : `dict`
187 The record associated with this item.
189 Returns
190 -------
191 info : `StoredFileInfo`
192 The newly-constructed item corresponding to the record.
193 """
194 # Convert name of StorageClass to instance
195 storageClass = cls.storageClassFactory.getStorageClass(record["storage_class"])
196 component = record["component"] if (record["component"] and record["component"] != NULLSTR) else None
198 info = StoredFileInfo(
199 formatter=record["formatter"],
200 path=record["path"],
201 storageClass=storageClass,
202 component=component,
203 checksum=record["checksum"],
204 file_size=record["file_size"],
205 )
206 return info