postjevsql.git / third-party / pg_major.bzl
1# The reindeer macros, with pgrx's PostgreSQL major made a configuration.
2#
3# reindeer writes pgrx and pgrx-pg-sys with the one `pgNN` feature that
4# third-party/Cargo.toml selects. These wrappers replace any `pgNN` in
5# PG_MAJORS with a select over the `pg_major` constraint
6# (build/defs.bzl's `pg_major_select`), and give pgrx-pg-sys's bindgen
7# run that major's pg_config, so //platforms:pgNN builds pgrx for NN.
8# reindeer.toml's `buckfile_imports` loads this file in place of the
9# prelude's, so a `reindeer buckify` keeps it.
10
11load("@prelude//rust:cargo_buildscript.bzl", _buildscript_run = "buildscript_run")
12load("@prelude//rust:cargo_package.bzl", _cargo = "cargo")
13load("//build:defs.bzl", "PG_MAJORS", "pg_major_select")
14
15_PG_FEATURES = ["pg" + m for m in PG_MAJORS]
16
17def _features(features):
18    rest = [f for f in features if f not in _PG_FEATURES]
19    if len(rest) == len(features):
20        return features
21    return rest + pg_major_select(lambda m: ["pg" + m])
22
23def _rust_library(name, features = [], **kwargs):
24    _cargo.rust_library(name = name, features = _features(features), **kwargs)
25
26def _rust_binary(name, features = [], **kwargs):
27    _cargo.rust_binary(name = name, features = _features(features), **kwargs)
28
29def _pg_config_env(env, m):
30    # pgrx-bindgen reads the server headers through PGRX_PG_CONFIG_PATH.
31    # The devshell writes `pg_config_NN` for every major; without one, the
32    # environment's (the newest) is used, and bindgen refuses the
33    # mismatch with the `pgNN` feature.
34    pg_config = read_config("postjevsql", "pg_config_" + m)
35    if pg_config == None:
36        return env
37    return env | {"PGRX_PG_CONFIG_PATH": pg_config}
38
39def buildscript_run(name, package_name, features = [], env = {}, **kwargs):
40    if package_name == "pgrx-pg-sys":
41        env = pg_major_select(lambda m: _pg_config_env(env, m))
42    _buildscript_run(
43        name = name,
44        package_name = package_name,
45        features = _features(features),
46        env = env,
47        **kwargs
48    )
49
50cargo = struct(
51    rust_library = _rust_library,
52    rust_binary = _rust_binary,
53)