Skip to content

Commit

Permalink
Cache plugin modules (#9031)
Browse files Browse the repository at this point in the history
* Cache plugin modules

* Add changelog entry

* Use lru_cache to keep Python 3.8 happy.
  • Loading branch information
peterallenwebb authored Nov 20, 2023
1 parent 1c9cec1 commit 9bb970e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
6 changes: 6 additions & 0 deletions .changes/unreleased/Under the Hood-20231107-191546.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: Under the Hood
body: Cache dbt plugin modules to improve integration test performance
time: 2023-11-07T19:15:46.170151-05:00
custom:
Author: peterallenwebb
Issue: "9029"
21 changes: 15 additions & 6 deletions core/dbt/plugins/manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import functools
import importlib
import pkgutil
from typing import Dict, List, Callable
from types import ModuleType
from typing import Dict, List, Callable, Mapping

from dbt.contracts.graph.manifest import Manifest
from dbt.exceptions import DbtRuntimeError
Expand Down Expand Up @@ -63,6 +65,17 @@ def get_manifest_artifacts(self, manifest: Manifest) -> PluginArtifacts:
raise NotImplementedError(f"get_manifest_artifacts hook not implemented for {self.name}")


@functools.lru_cache(maxsize=None)
def _get_dbt_modules() -> Mapping[str, ModuleType]:
# This is an expensive function, especially in the context of testing, when
# it is called repeatedly, so we break it out and cache the result globally.
return {
name: importlib.import_module(name)
for _, name, _ in pkgutil.iter_modules()
if name.startswith(PluginManager.PLUGIN_MODULE_PREFIX)
}


class PluginManager:
PLUGIN_MODULE_PREFIX = "dbt_"
PLUGIN_ATTR_NAME = "plugins"
Expand Down Expand Up @@ -91,11 +104,7 @@ def __init__(self, plugins: List[dbtPlugin]) -> None:

@classmethod
def from_modules(cls, project_name: str) -> "PluginManager":
discovered_dbt_modules = {
name: importlib.import_module(name)
for _, name, _ in pkgutil.iter_modules()
if name.startswith(cls.PLUGIN_MODULE_PREFIX)
}
discovered_dbt_modules = _get_dbt_modules()

plugins = []
for name, module in discovered_dbt_modules.items():
Expand Down

0 comments on commit 9bb970e

Please sign in to comment.