Skip to content

Commit 54895eb

Browse files
committed
add post build hook to swap out psycopg2-binary for psycopg2 based on DBT_PSYCOPG2_NAME
1 parent 97f7ef7 commit 54895eb

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

hatch_hooks.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import os
2+
import subprocess
3+
import sys
4+
5+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
6+
from hatchling.plugin import hookimpl
7+
8+
9+
class Psycopg2NoBinary(BuildHookInterface):
10+
"""
11+
Custom build hook to install psycopg2 instead of psycopg2-binary based on the presence of `DBT_PSYCOPG2_NAME`.
12+
This is necessary as psycopg2-binary is better for local development, but psycopg2 is better for production.
13+
"""
14+
15+
PLUGIN_NAME = "psycopg2"
16+
17+
def finalize(self, version, build_data, artifact_path) -> None:
18+
if os.getenv("DBT_PSYCOPG2_NAME", "") == "psycopg2":
19+
psycopg2_binary_pinned = [
20+
package
21+
for package in build_data["dependencies"]
22+
if package.startswith("psycopg2-binary")
23+
].pop()
24+
psycopg2_pinned = psycopg2_binary_pinned.replace("-binary", "")
25+
subprocess.check_call(
26+
[sys.executable, "-m", "pip", "-y", "uninstall", "psycopg2-binary"]
27+
)
28+
subprocess.check_call(
29+
[sys.executable, "-m", "pip", "-y", "install", f'"{psycopg2_pinned}"']
30+
)
31+
32+
33+
@hookimpl
34+
def hatch_register_build_hook():
35+
return Psycopg2NoBinary

0 commit comments

Comments
 (0)