Skip to content

Commit 43db517

Browse files
revert to use get_or_load_models for nonsqlmodels and dbt
1 parent 85ed2e0 commit 43db517

3 files changed

Lines changed: 83 additions & 30 deletions

File tree

sqlmesh/core/loader.py

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ class LoadedProject:
6868

6969

7070
class CacheBase(abc.ABC):
71+
@abc.abstractmethod
72+
def get_or_load_models(
73+
self, target_path: Path, loader: t.Callable[[], t.List[Model]]
74+
) -> t.List[Model]:
75+
"""Get or load all models from cache."""
76+
pass
77+
7178
@abc.abstractmethod
7279
def put(self, models: t.List[Model], path: Path) -> bool:
7380
pass
@@ -291,31 +298,30 @@ def _load_external_models(
291298
if external_models_path.exists() and external_models_path.is_dir():
292299
paths_to_load.extend(self._glob_paths(external_models_path, extension=".yaml"))
293300

301+
def _load(path: Path) -> t.List[Model]:
302+
try:
303+
with open(path, "r", encoding="utf-8") as file:
304+
return [
305+
create_external_model(
306+
defaults=self.config.model_defaults.dict(),
307+
path=path,
308+
project=self.config.project,
309+
audit_definitions=audits,
310+
**{
311+
"dialect": self.config.model_defaults.dialect,
312+
"default_catalog": self.context.default_catalog,
313+
**row,
314+
},
315+
)
316+
for row in YAML().load(file.read())
317+
]
318+
except Exception as ex:
319+
raise ConfigError(self._failed_to_load_model_error(path, ex))
320+
294321
for path in paths_to_load:
295322
self._track_file(path)
296-
external_models = cache.get(path)
297323

298-
if not external_models:
299-
try:
300-
with open(path, "r", encoding="utf-8") as file:
301-
external_models = [
302-
create_external_model(
303-
defaults=self.config.model_defaults.dict(),
304-
path=path,
305-
project=self.config.project,
306-
audit_definitions=audits,
307-
**{
308-
"dialect": self.config.model_defaults.dialect,
309-
"default_catalog": self.context.default_catalog,
310-
**row,
311-
},
312-
)
313-
for row in YAML().load(file.read())
314-
]
315-
316-
cache.put(external_models, path)
317-
except Exception as ex:
318-
raise ConfigError(f"Failed to load model definition at '{path}'.\n{ex}")
324+
external_models = cache.get_or_load_models(path, lambda: _load(path))
319325

320326
# external models with no explicit gateway defined form the base set
321327
for model in external_models:
@@ -843,6 +849,20 @@ def __init__(self, loader: SqlMeshLoader, config_path: Path):
843849
self.config_path = config_path
844850
self._model_cache = ModelCache(self.config_path / c.CACHE)
845851

852+
def get_or_load_models(
853+
self, target_path: Path, loader: t.Callable[[], t.List[Model]]
854+
) -> t.List[Model]:
855+
models = self._model_cache.get_or_load(
856+
self._cache_entry_name(target_path),
857+
self._model_cache_entry_id(target_path),
858+
loader=loader,
859+
)
860+
861+
for model in models:
862+
model._path = target_path
863+
864+
return models
865+
846866
def put(self, models: t.List[Model], path: Path) -> bool:
847867
return self._model_cache.put(
848868
models,

sqlmesh/core/model/cache.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from sqlglot.schema import MappingSchema
1111

1212
from sqlmesh.core import constants as c
13-
from sqlmesh.core.model.definition import ExternalModel, Model, SqlModel
13+
from sqlmesh.core.model.definition import ExternalModel, Model, SqlModel, _Model
1414
from sqlmesh.utils.cache import FileCache
1515
from sqlmesh.utils.hashing import crc32
1616
from sqlmesh.utils.process import PoolExecutor, create_process_pool_executor
@@ -40,6 +40,30 @@ def __init__(self, path: Path):
4040
prefix="model_definition",
4141
)
4242

43+
def get_or_load(
44+
self, name: str, entry_id: str = "", *, loader: t.Callable[[], t.List[Model]]
45+
) -> t.List[Model]:
46+
"""Returns an existing cached model definition or loads and caches a new one.
47+
Args:
48+
name: The name of the entry.
49+
entry_id: The unique entry identifier. Used for cache invalidation.
50+
loader: Used to load a new model definition when no cached instance was found.
51+
Returns:
52+
The model definition.
53+
"""
54+
cache_entry = self._file_cache.get(name, entry_id)
55+
if isinstance(cache_entry, list) and isinstance(seq_get(cache_entry, 0), _Model):
56+
return cache_entry
57+
58+
models = loader()
59+
if isinstance(models, list) and isinstance(seq_get(models, 0), (SqlModel, ExternalModel)):
60+
# make sure we preload full_depends_on
61+
for model in models:
62+
model.full_depends_on
63+
64+
self._file_cache.put(name, entry_id, value=models)
65+
return models
66+
4367
def put(self, models: t.List[Model], name: str, entry_id: str = "") -> bool:
4468
if isinstance(models, list) and isinstance(seq_get(models, 0), (SqlModel, ExternalModel)):
4569
# make sure we preload full_depends_on

sqlmesh/dbt/loader.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,9 @@ def _to_sqlmesh(config: BMC, context: DbtContext) -> Model:
147147
)
148148
continue
149149

150-
cached_models = cache.get(model.path)
151-
152-
if cached_models:
153-
sqlmesh_model = cached_models[0]
154-
else:
155-
sqlmesh_model = _to_sqlmesh(model, context)
156-
cache.put([sqlmesh_model], model.path)
150+
sqlmesh_model = cache.get_or_load_models(
151+
model.path, loader=lambda: [_to_sqlmesh(model, context)]
152+
)[0]
157153

158154
models[sqlmesh_model.fqn] = sqlmesh_model
159155

@@ -346,6 +342,19 @@ def __init__(
346342
cache_path = loader.config_path / c.CACHE / target.name
347343
self._model_cache = ModelCache(cache_path)
348344

345+
def get_or_load_models(
346+
self, target_path: Path, loader: t.Callable[[], t.List[Model]]
347+
) -> t.List[Model]:
348+
models = self._model_cache.get_or_load(
349+
self._cache_entry_name(target_path),
350+
self._cache_entry_id(target_path),
351+
loader=loader,
352+
)
353+
for model in models:
354+
model._path = target_path
355+
356+
return models
357+
349358
def put(self, models: t.List[Model], path: Path) -> bool:
350359
return self._model_cache.put(
351360
models,

0 commit comments

Comments
 (0)