bqmigrate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bqmigrate/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """BigQuery schema migrations: tables declared in Python, applied as Alembic revisions."""
bqmigrate/cli.py ADDED
@@ -0,0 +1,148 @@
1
+ """The `bqmigrate` command: upgrade, pending, drift and plan, each against one environment of `bqmigrate.toml`.
2
+
3
+ bqmigrate upgrade staging --release v1.4.0
4
+ bqmigrate pending production
5
+ bqmigrate drift staging
6
+ bqmigrate plan staging
7
+
8
+ It exits 0 when the command did what it says, 1 when it refused or found unknown drift, and 2 for a
9
+ command line it cannot read.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import logging
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import TYPE_CHECKING, TextIO
19
+
20
+ from google.cloud import bigquery
21
+
22
+ from bqmigrate.config import ProjectConfig
23
+ from bqmigrate.drift import DriftCheck
24
+ from bqmigrate.errors import MigrationError
25
+ from bqmigrate.plan import Planner
26
+ from bqmigrate.revisions import RevisionMarker
27
+ from bqmigrate.run import MigrationRun
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Callable, Sequence
31
+ from contextlib import AbstractContextManager
32
+
33
+ from bqmigrate.environment import Environment
34
+
35
+ type ClientFactory = Callable[[Environment], bigquery.Client]
36
+
37
+
38
+ def _client(environment: Environment) -> bigquery.Client:
39
+ return bigquery.Client(project=environment.project, location=environment.location)
40
+
41
+
42
+ def _parser() -> argparse.ArgumentParser:
43
+ parser = argparse.ArgumentParser(prog="bqmigrate", description="BigQuery schema migrations.")
44
+ parser.add_argument("--config", type=Path, default=Path(ProjectConfig.FILE_NAME), help="the project's config file")
45
+ commands = parser.add_subparsers(dest="command", required=True)
46
+
47
+ upgrade = commands.add_parser("upgrade", help="apply the revisions the environment has not had")
48
+ upgrade.add_argument("environment")
49
+ upgrade.add_argument("--target", default=RevisionMarker.HEAD.value, help="the last revision to apply")
50
+ upgrade.add_argument("--release", help="what is being deployed, recorded in the ledger")
51
+
52
+ pending = commands.add_parser("pending", help="list the revisions the environment has not had")
53
+ pending.add_argument("environment")
54
+
55
+ drift = commands.add_parser("drift", help="compare the specs with the environment's tables")
56
+ drift.add_argument("environment")
57
+ drift.add_argument("--accept", action="store_true", help="record every drift found as accepted")
58
+
59
+ plan = commands.add_parser("plan", help="say how each drift would be made good")
60
+ plan.add_argument("environment")
61
+ return parser
62
+
63
+
64
+ class Cli:
65
+ """One invocation, writing its results to `out`."""
66
+
67
+ def __init__(self, config: ProjectConfig, *, client_factory: ClientFactory, out: TextIO) -> None:
68
+ self._config = config
69
+ self._client_factory = client_factory
70
+ self._out = out
71
+
72
+ def upgrade(self, name: str, *, target: str, release: str | None) -> None:
73
+ """Apply the pending revisions up to `target`."""
74
+ with self._open_run(name, release=release) as run:
75
+ run.upgrade(self._config.revision_directory, target=target)
76
+ self._write(f"applied {len(run.applied_revisions)}: {', '.join(run.applied_revisions) or 'none'}")
77
+
78
+ def pending(self, name: str) -> None:
79
+ """List the revisions not applied yet, in apply order."""
80
+ with self._open_run(name, release=None) as run:
81
+ revisions = run.pending(self._config.revision_directory)
82
+ self._write("\n".join(revisions) if len(revisions) > 0 else "nothing pending")
83
+
84
+ def drift(self, name: str, *, accept: bool) -> None:
85
+ """Fail on drift the environment has not accepted, or record all of it as accepted.
86
+
87
+ :raises DriftError: unknown drift, or accepted drift that is gone
88
+ """
89
+ check = self._drift_check(name)
90
+ if accept:
91
+ drifts = check.run()
92
+ path = self._config.write_known_drift(name, drifts)
93
+ self._write(f"{len(drifts)} drift accepted in {path}")
94
+ return
95
+ known = self._config.known_drift(name)
96
+ check.raise_on_unknown(known)
97
+ self._write(f"no unknown drift; {len(known)} accepted")
98
+
99
+ def plan(self, name: str) -> None:
100
+ """Every drift with how it would be made good, then the tables that need a rebuild."""
101
+ environment = self._config.environment(name)
102
+ datasets = self._config.load_datasets()
103
+ drifts = DriftCheck(self._client_factory(environment), environment, datasets).run()
104
+ changes = Planner(environment, datasets).plan(drifts)
105
+ for change in changes:
106
+ self._write(str(change))
107
+ rebuilds = Planner.tables_to_rebuild(changes)
108
+ self._write(f"{len(changes)} changes; rebuild: {', '.join(rebuilds) or 'none'}")
109
+
110
+ def _drift_check(self, name: str) -> DriftCheck:
111
+ environment = self._config.environment(name)
112
+ return DriftCheck(self._client_factory(environment), environment, self._config.load_datasets())
113
+
114
+ def _open_run(self, name: str, *, release: str | None) -> AbstractContextManager[MigrationRun]:
115
+ settings = self._config.settings(name)
116
+ return MigrationRun.open(
117
+ self._config.environment(name), ledger_dataset=settings.ledger_dataset, release=release
118
+ )
119
+
120
+ def _write(self, line: str) -> None:
121
+ self._out.write(f"{line}\n")
122
+
123
+
124
+ def main(
125
+ argv: Sequence[str] | None = None,
126
+ *,
127
+ client_factory: ClientFactory = _client,
128
+ out: TextIO = sys.stdout,
129
+ err: TextIO = sys.stderr,
130
+ ) -> int:
131
+ """Run the command `argv` spells; the exit status is the return value."""
132
+ arguments = _parser().parse_args(argv)
133
+ logging.basicConfig(level=logging.INFO, stream=err, format="%(message)s")
134
+ try:
135
+ cli = Cli(ProjectConfig.load(arguments.config), client_factory=client_factory, out=out)
136
+ match arguments.command:
137
+ case "upgrade":
138
+ cli.upgrade(arguments.environment, target=arguments.target, release=arguments.release)
139
+ case "pending":
140
+ cli.pending(arguments.environment)
141
+ case "drift":
142
+ cli.drift(arguments.environment, accept=arguments.accept)
143
+ case _:
144
+ cli.plan(arguments.environment)
145
+ except (MigrationError, FileNotFoundError) as error:
146
+ err.write(f"bqmigrate: {error}\n")
147
+ return 1
148
+ return 0
bqmigrate/config.py ADDED
@@ -0,0 +1,137 @@
1
+ """A project's `bqmigrate.toml`: where its revisions and specs are, and its environments.
2
+
3
+ revisions = "migrations"
4
+ datasets = "myapp.schemas:DATASETS"
5
+
6
+ [environments.staging]
7
+ project = "acme-staging"
8
+ dataset_prefix = "staging_"
9
+ location = "EU"
10
+ known_drift = "drift/staging.json"
11
+
12
+ Paths are relative to the file. `datasets` names a sequence of `Dataset` specs as `module:attribute`,
13
+ imported with the file's directory on the import path.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import importlib
19
+ import json
20
+ import sys
21
+ import tomllib
22
+ from collections.abc import Sequence
23
+ from pathlib import Path
24
+ from typing import ClassVar, Self
25
+
26
+ from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError
27
+
28
+ from bqmigrate.drift import Drift
29
+ from bqmigrate.environment import Environment
30
+ from bqmigrate.errors import MigrationError
31
+ from bqmigrate.spec import Dataset
32
+
33
+ _KNOWN_DRIFT = TypeAdapter(list[Drift])
34
+ _DATASETS = TypeAdapter(Sequence[Dataset])
35
+
36
+
37
+ class ConfigError(MigrationError):
38
+ """A `bqmigrate.toml` that names something that is not there."""
39
+
40
+
41
+ class EnvironmentSettings(BaseModel):
42
+ """One environment's entry: what `Environment` takes, the ledger's dataset and its known drift file."""
43
+
44
+ model_config = ConfigDict(frozen=True, extra="forbid")
45
+
46
+ project: str = Field(min_length=1)
47
+ dataset_prefix: str = ""
48
+ location: str = "US"
49
+ ledger_dataset: str = Field(default="migrations", min_length=1)
50
+ known_drift: Path | None = None
51
+
52
+
53
+ class ProjectConfig(BaseModel):
54
+ """The whole file, with `root` the directory it was read from."""
55
+
56
+ model_config = ConfigDict(frozen=True, extra="forbid")
57
+
58
+ FILE_NAME: ClassVar[str] = "bqmigrate.toml"
59
+
60
+ root: Path
61
+ revisions: Path
62
+ datasets: str = Field(pattern=r"^[\w.]+:\w+$")
63
+ environments: dict[str, EnvironmentSettings] = Field(min_length=1)
64
+
65
+ @classmethod
66
+ def load(cls, path: Path) -> Self:
67
+ """The config in `path`.
68
+
69
+ :raises FileNotFoundError: there is no such file
70
+ :raises ValidationError: the file does not hold a config
71
+ """
72
+ with path.open("rb") as file:
73
+ values = tomllib.load(file)
74
+ return cls.model_validate({**values, "root": path.parent.resolve()})
75
+
76
+ @property
77
+ def revision_directory(self) -> Path:
78
+ """The Alembic script directory, holding `env.py` and `versions/`."""
79
+ return self.root / self.revisions
80
+
81
+ def settings(self, name: str) -> EnvironmentSettings:
82
+ """The settings of the environment named `name`.
83
+
84
+ :raises ConfigError: no environment has that name
85
+ """
86
+ settings = self.environments.get(name)
87
+ if settings is None:
88
+ raise ConfigError(f"no environment {name!r}; the config has {', '.join(sorted(self.environments))}")
89
+ return settings
90
+
91
+ def environment(self, name: str) -> Environment:
92
+ """The environment named `name`.
93
+
94
+ :raises ConfigError: no environment has that name
95
+ """
96
+ settings = self.settings(name)
97
+ return Environment(
98
+ name=name, project=settings.project, dataset_prefix=settings.dataset_prefix, location=settings.location
99
+ )
100
+
101
+ def load_datasets(self) -> list[Dataset]:
102
+ """The dataset specs `datasets` names, imported with `root` on the import path.
103
+
104
+ :raises ConfigError: the attribute is missing or does not hold dataset specs
105
+ """
106
+ module_name, attribute = self.datasets.split(":")
107
+ root = str(self.root)
108
+ if root not in sys.path:
109
+ sys.path.insert(0, root)
110
+ module = importlib.import_module(module_name)
111
+ datasets: object = getattr(module, attribute, None)
112
+ try:
113
+ # Strict: the specs are taken as declared, never rebuilt from other shapes.
114
+ return list(_DATASETS.validate_python(datasets, strict=True))
115
+ except ValidationError as error:
116
+ raise ConfigError(f"{self.datasets} is not a sequence of Dataset specs") from error
117
+
118
+ def known_drift(self, name: str) -> list[Drift]:
119
+ """The drift environment `name` has accepted, empty when it lists none or its file does not exist yet."""
120
+ path = self.settings(name).known_drift
121
+ if path is None or not (self.root / path).exists():
122
+ return []
123
+ return _KNOWN_DRIFT.validate_json((self.root / path).read_bytes())
124
+
125
+ def write_known_drift(self, name: str, drifts: Sequence[Drift]) -> Path:
126
+ """Record `drifts` as environment `name`'s accepted drift.
127
+
128
+ :raises ConfigError: the environment names no known drift file
129
+ """
130
+ path = self.settings(name).known_drift
131
+ if path is None:
132
+ raise ConfigError(f"environment {name!r} has no known_drift file to write")
133
+ target = self.root / path
134
+ target.parent.mkdir(parents=True, exist_ok=True)
135
+ entries = [drift.model_dump(mode="json") for drift in drifts]
136
+ target.write_text(json.dumps(entries, indent=2) + "\n")
137
+ return target
bqmigrate/ddl.py ADDED
@@ -0,0 +1,111 @@
1
+ """GoogleSQL DDL rendered from specs, so a revision states a change once, in the spec's terms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from bqmigrate.spec import Granularity
8
+ from bqmigrate.types import ColumnType, Mode
9
+
10
+ if TYPE_CHECKING:
11
+ from bqmigrate.environment import TableAddress
12
+ from bqmigrate.spec import Column, Table
13
+
14
+
15
+ def sql_string(value: str) -> str:
16
+ """`value` as a GoogleSQL string literal: backslashes, double quotes and line breaks escaped, since a
17
+ quoted literal cannot span lines.
18
+ """
19
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\r", "\\r")
20
+ return f'"{escaped}"'
21
+
22
+
23
+ def identifier(name: str) -> str:
24
+ """`name` backtick-quoted, so a reserved word or a dash needs no special case."""
25
+ return f"`{name}`"
26
+
27
+
28
+ def column_type(column: Column) -> str:
29
+ """The column's type as DDL writes it: a STRUCT spells its fields, a REPEATED column is an ARRAY."""
30
+ if column.type.is_struct:
31
+ fields = ", ".join(column_definition(field) for field in column.fields)
32
+ element = f"STRUCT<{fields}>"
33
+ else:
34
+ element = column.type.value
35
+ if column.mode is Mode.REPEATED:
36
+ return f"ARRAY<{element}>"
37
+ return element
38
+
39
+
40
+ def column_definition(column: Column) -> str:
41
+ """The column as a `CREATE TABLE` or `ADD COLUMN` declares it: name, type, NOT NULL, default, options."""
42
+ parts = [identifier(column.name), column_type(column)]
43
+ if column.mode is Mode.REQUIRED:
44
+ parts.append("NOT NULL")
45
+ if column.default is not None:
46
+ parts.append(f"DEFAULT {column.default}")
47
+ if column.description is not None:
48
+ parts.append(f"OPTIONS(description={sql_string(column.description)})")
49
+ return " ".join(parts)
50
+
51
+
52
+ def partition_by(table: Table) -> str | None:
53
+ """The `PARTITION BY` expression for the table's partitioning, None when it is not partitioned.
54
+
55
+ A daily DATE partition is the column itself; every other granularity truncates the column to it, with
56
+ the function for the column's type.
57
+ """
58
+ partitioning = table.partitioning
59
+ if partitioning is None:
60
+ return None
61
+ granularity = partitioning.granularity.value
62
+ if partitioning.column is None:
63
+ return f"TIMESTAMP_TRUNC(_PARTITIONTIME, {granularity})"
64
+ column = table.column(partitioning.column)
65
+ if column is None:
66
+ raise ValueError(f"table {table.name} partitions on a column it does not declare")
67
+ name = identifier(column.name)
68
+ match column.type:
69
+ case ColumnType.DATE if partitioning.granularity is Granularity.DAY:
70
+ return name
71
+ case ColumnType.DATE:
72
+ return f"DATE_TRUNC({name}, {granularity})"
73
+ case ColumnType.DATETIME:
74
+ return f"DATETIME_TRUNC({name}, {granularity})"
75
+ case ColumnType.TIMESTAMP:
76
+ return f"TIMESTAMP_TRUNC({name}, {granularity})"
77
+ case _:
78
+ raise ValueError(f"table {table.name} partitions on the {column.type} column {column.name}")
79
+
80
+
81
+ def _table_options(table: Table) -> list[str]:
82
+ """The clauses after a table's column list: its partitioning, clustering and description."""
83
+ clauses: list[str] = []
84
+ partition_expression = partition_by(table)
85
+ if partition_expression is not None:
86
+ clauses.append(f"PARTITION BY {partition_expression}")
87
+ if len(table.clustering) > 0:
88
+ clauses.append(f"CLUSTER BY {', '.join(identifier(name) for name in table.clustering)}")
89
+ if table.description is not None:
90
+ clauses.append(f"OPTIONS(description={sql_string(table.description)})")
91
+ return clauses
92
+
93
+
94
+ def _column_list(table: Table) -> str:
95
+ columns = ",\n ".join(column_definition(column) for column in table.columns)
96
+ return f"(\n {columns}\n)"
97
+
98
+
99
+ def create_table(address: TableAddress, table: Table) -> str:
100
+ """`CREATE TABLE IF NOT EXISTS` for `table` at `address`, with its partitioning, clustering and description."""
101
+ return "\n".join([f"CREATE TABLE IF NOT EXISTS {address.sql} {_column_list(table)}", *_table_options(table)])
102
+
103
+
104
+ def create_table_as(address: TableAddress, table: Table, select: str) -> str:
105
+ """`CREATE OR REPLACE TABLE ... AS` for `table` at `address`, holding the rows `select` reads.
106
+
107
+ The rows match the columns by position, so `select` reads them in the spec's order. A NULL in a
108
+ NOT NULL column fails the whole statement, which writes nothing.
109
+ """
110
+ statement = [f"CREATE OR REPLACE TABLE {address.sql} {_column_list(table)}", *_table_options(table), "AS", select]
111
+ return "\n".join(statement)
bqmigrate/drift.py ADDED
@@ -0,0 +1,188 @@
1
+ """Drift: a live table that differs from the spec declaring it, or a spec whose table is missing.
2
+
3
+ Each spec is compared with its table in one environment, in what a spec declares: columns at every
4
+ depth with their type, mode, default and description, the table's description, partitioning and
5
+ clustering. Column order is not compared, since `ADD COLUMN` can only append.
6
+
7
+ An environment may carry drift it has accepted, such as a column a hotfix added by hand; `DriftCheck`
8
+ fails only on drift that list does not hold, and on listed drift that is gone, so the list stays true.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ from enum import StrEnum
15
+ from typing import TYPE_CHECKING, cast, override
16
+
17
+ from google.api_core.exceptions import NotFound
18
+ from pydantic import BaseModel, ConfigDict
19
+
20
+ from bqmigrate.errors import DriftError
21
+ from bqmigrate.spec import Column, TimePartitioning
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Collection, Sequence
25
+
26
+ from google.cloud import bigquery
27
+
28
+ from bqmigrate.environment import Environment
29
+ from bqmigrate.spec import Dataset, Table
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class DriftKind(StrEnum):
35
+ """What a live table holds otherwise than its spec."""
36
+
37
+ TABLE_MISSING = "table_missing"
38
+ COLUMN_MISSING = "column_missing"
39
+ COLUMN_NOT_DECLARED = "column_not_declared"
40
+ COLUMN_TYPE = "column_type"
41
+ COLUMN_MODE = "column_mode"
42
+ COLUMN_DEFAULT = "column_default"
43
+ COLUMN_DESCRIPTION = "column_description"
44
+ TABLE_DESCRIPTION = "table_description"
45
+ PARTITIONING = "partitioning"
46
+ CLUSTERING = "clustering"
47
+
48
+
49
+ class Drift(BaseModel):
50
+ """One difference between a live table and its spec.
51
+
52
+ `column` is the column's dotted path for a column's drift and None for the table's. `declared` and
53
+ `found` are the spec's value and the table's, None where one side has none.
54
+ """
55
+
56
+ model_config = ConfigDict(frozen=True, extra="forbid")
57
+
58
+ table: str
59
+ kind: DriftKind
60
+ column: str | None = None
61
+ declared: str | None = None
62
+ found: str | None = None
63
+
64
+ @override
65
+ def __str__(self) -> str:
66
+ subject = self.table if self.column is None else f"{self.table}.{self.column}"
67
+ return f"{subject}: {self.kind}, declared {self.declared}, found {self.found}"
68
+
69
+
70
+ def _schema(table: bigquery.Table) -> list[bigquery.SchemaField]:
71
+ # The client types a table's schema loosely; each entry is a SchemaField.
72
+ return cast("list[bigquery.SchemaField]", table.schema)
73
+
74
+
75
+ def _text(value: object) -> str | None:
76
+ return None if value is None else str(value)
77
+
78
+
79
+ class DriftCheck:
80
+ """Compares each table spec of `datasets` with its live table in `environment`."""
81
+
82
+ def __init__(self, client: bigquery.Client, environment: Environment, datasets: Sequence[Dataset]) -> None:
83
+ self._client = client
84
+ self._environment = environment
85
+ self._datasets = datasets
86
+
87
+ def run(self) -> list[Drift]:
88
+ """Every difference found, table by table in spec order."""
89
+ drifts: list[Drift] = []
90
+ for dataset in self._datasets:
91
+ for table in dataset.tables:
92
+ address = self._environment.dataset(dataset).table(table)
93
+ try:
94
+ live = self._client.get_table(address.qualified)
95
+ except NotFound:
96
+ drifts.append(Drift(table=address.qualified, kind=DriftKind.TABLE_MISSING))
97
+ continue
98
+ drifts.extend(self._table_drift(address.qualified, table, live))
99
+ logger.info("%d specs compared with %s, %d differences", self._table_count, self._environment.name, len(drifts))
100
+ return drifts
101
+
102
+ def raise_on_unknown(self, known: Collection[Drift]) -> None:
103
+ """Run the check and fail on drift `known` does not list, or on listed drift no longer found.
104
+
105
+ :raises DriftError: naming both lists
106
+ """
107
+ found = self.run()
108
+ unknown = [drift for drift in found if drift not in known]
109
+ gone = [drift for drift in known if drift not in found]
110
+ if len(unknown) > 0 or len(gone) > 0:
111
+ raise DriftError(unknown, gone)
112
+
113
+ @property
114
+ def _table_count(self) -> int:
115
+ return sum(len(dataset.tables) for dataset in self._datasets)
116
+
117
+ def _table_drift(self, qualified: str, table: Table, live: bigquery.Table) -> list[Drift]:
118
+ found_columns = tuple(Column.from_schema_field(field) for field in _schema(live))
119
+ drifts = [
120
+ Drift(table=qualified, kind=kind, column=column, declared=declared, found=found)
121
+ for kind, column, declared, found in _column_drift(table.columns, found_columns, prefix="")
122
+ ]
123
+ if table.description != live.description:
124
+ drifts.append(
125
+ Drift(
126
+ table=qualified,
127
+ kind=DriftKind.TABLE_DESCRIPTION,
128
+ declared=table.description,
129
+ found=_text(live.description),
130
+ )
131
+ )
132
+ partitioning = TimePartitioning.from_table(live)
133
+ if live.range_partitioning is not None or partitioning != table.partitioning:
134
+ found_partitioning = "range" if live.range_partitioning is not None else _text(partitioning)
135
+ drifts.append(
136
+ Drift(
137
+ table=qualified,
138
+ kind=DriftKind.PARTITIONING,
139
+ declared=_text(table.partitioning),
140
+ found=found_partitioning,
141
+ )
142
+ )
143
+ clustering = tuple(cast("list[str] | None", live.clustering_fields) or ())
144
+ if clustering != table.clustering:
145
+ drifts.append(
146
+ Drift(
147
+ table=qualified,
148
+ kind=DriftKind.CLUSTERING,
149
+ declared=", ".join(table.clustering) or None,
150
+ found=", ".join(clustering) or None,
151
+ )
152
+ )
153
+ return drifts
154
+
155
+
156
+ type _ColumnDrift = tuple[DriftKind, str, str | None, str | None]
157
+
158
+
159
+ def _column_drift(declared: Sequence[Column], found: Sequence[Column], *, prefix: str) -> list[_ColumnDrift]:
160
+ """The differences between two lists of columns, matched by name without case, at every depth."""
161
+ found_by_name = {column.name.casefold(): column for column in found}
162
+ declared_names = {column.name.casefold() for column in declared}
163
+ drifts: list[_ColumnDrift] = []
164
+ for column in declared:
165
+ path = f"{prefix}{column.name}"
166
+ live = found_by_name.get(column.name.casefold())
167
+ if live is None:
168
+ drifts.append((DriftKind.COLUMN_MISSING, path, column.type.value, None))
169
+ continue
170
+ drifts.extend(_attribute_drift(column, live, path))
171
+ if column.type.is_struct and live.type.is_struct:
172
+ drifts.extend(_column_drift(column.fields, live.fields, prefix=f"{path}."))
173
+ drifts.extend(
174
+ (DriftKind.COLUMN_NOT_DECLARED, f"{prefix}{column.name}", None, column.type.value)
175
+ for column in found
176
+ if column.name.casefold() not in declared_names
177
+ )
178
+ return drifts
179
+
180
+
181
+ def _attribute_drift(declared: Column, found: Column, path: str) -> list[_ColumnDrift]:
182
+ attributes = [
183
+ (DriftKind.COLUMN_TYPE, declared.type.value, found.type.value),
184
+ (DriftKind.COLUMN_MODE, declared.mode.value, found.mode.value),
185
+ (DriftKind.COLUMN_DEFAULT, declared.default, found.default),
186
+ (DriftKind.COLUMN_DESCRIPTION, declared.description, found.description),
187
+ ]
188
+ return [(kind, path, spec, live) for kind, spec, live in attributes if spec != live]
@@ -0,0 +1,73 @@
1
+ """Where a migration runs: one environment's copy of the declared datasets, in one project.
2
+
3
+ Environments share one set of specs and revisions, and tell their datasets apart by a prefix on
4
+ the dataset name: `staging_analytics` and `analytics` are two environments' copies of the dataset
5
+ `analytics`. Every table a revision touches is addressed through the environment, so a revision
6
+ written once runs against each copy.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import TYPE_CHECKING
13
+
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
16
+ if TYPE_CHECKING:
17
+ from bqmigrate.spec import Dataset, Table
18
+
19
+
20
+ class TableAddress(BaseModel):
21
+ """One table's address. It may name a table no spec declares, such as a dropped one or a snapshot."""
22
+
23
+ model_config = ConfigDict(frozen=True, extra="forbid")
24
+
25
+ project: str = Field(min_length=1)
26
+ dataset: str = Field(min_length=1)
27
+ name: str = Field(min_length=1)
28
+
29
+ @property
30
+ def qualified(self) -> str:
31
+ """`project.dataset.table`, as the BigQuery client takes a table id."""
32
+ return f"{self.project}.{self.dataset}.{self.name}"
33
+
34
+ @property
35
+ def sql(self) -> str:
36
+ """The table id backtick-quoted for a statement."""
37
+ return f"`{self.qualified}`"
38
+
39
+
40
+ class DatasetAddress(BaseModel):
41
+ """One environment's copy of a dataset."""
42
+
43
+ model_config = ConfigDict(frozen=True, extra="forbid")
44
+
45
+ project: str = Field(min_length=1)
46
+ name: str = Field(min_length=1)
47
+
48
+ @property
49
+ def qualified(self) -> str:
50
+ """`project.dataset`, as the BigQuery client takes a dataset id."""
51
+ return f"{self.project}.{self.name}"
52
+
53
+ def table(self, table: Table | str) -> TableAddress:
54
+ """The address of `table` in this dataset, by its spec or by name."""
55
+ name = table if isinstance(table, str) else table.name
56
+ return TableAddress(project=self.project, dataset=self.name, name=name)
57
+
58
+
59
+ class Environment(BaseModel):
60
+ """One environment: the project its datasets live in, the prefix they carry, and where jobs run."""
61
+
62
+ model_config = ConfigDict(frozen=True, extra="forbid")
63
+
64
+ name: str = Field(min_length=1)
65
+ project: str = Field(min_length=1)
66
+ # Prepended to every dataset name; empty for an environment whose datasets carry none.
67
+ dataset_prefix: str = Field(default="", pattern=re.compile(r"^[A-Za-z0-9_]*$"))
68
+ location: str = Field(default="US", min_length=1)
69
+
70
+ def dataset(self, dataset: Dataset | str) -> DatasetAddress:
71
+ """The environment's copy of `dataset`, by its spec or by its unprefixed name."""
72
+ name = dataset if isinstance(dataset, str) else dataset.name
73
+ return DatasetAddress(project=self.project, name=f"{self.dataset_prefix}{name}")