spark-sql-migrations 0.0.1__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.
@@ -0,0 +1,8 @@
1
+ import logging
2
+
3
+ # A library must not configure logging when it is imported. A NullHandler on the
4
+ # package root keeps our records off logging.lastResort while leaving every
5
+ # decision about handlers, levels and formats to the host application. An
6
+ # application that wants our opinionated setup calls
7
+ # spark_sql_migrations.custom_logging.setup_logging() from its own entry point.
8
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -0,0 +1,78 @@
1
+ """Opinionated logging configuration, for *applications* to opt into.
2
+
3
+ Importing spark_sql_migrations never configures logging: library modules take a plain
4
+ ``logging.getLogger(__name__)`` and inherit whatever the host application set
5
+ up. An application that wants this format calls :func:`setup_logging` from its
6
+ own entry point -- never at import time, and never from library code, because
7
+ configuring the root logger is the application's decision to make.
8
+ """
9
+
10
+ import logging.config
11
+ import os
12
+
13
+ LOG_FILE_ENV_VAR = "SPARK_SQL_MIGRATIONS_LOG_FILE"
14
+ DEFAULT_LOG_FILENAME = "local_log.log"
15
+
16
+ FORMAT = "%(levelname)s %(asctime)s %(filename)s->%(funcName)s->%(lineno)d : %(message)s"
17
+
18
+
19
+ def get_log_file_path():
20
+ """where the file handler writes.
21
+
22
+ resolved against the caller's cwd for the same reason as the spark warehouse
23
+ dir: a __file__-relative default would land inside site-packages once this
24
+ is installed from a wheel.
25
+ """
26
+ return os.environ.get(LOG_FILE_ENV_VAR, os.path.join(os.getcwd(), DEFAULT_LOG_FILENAME))
27
+
28
+
29
+ def build_config():
30
+ """built per call, not a module constant: get_log_file_path() reads the
31
+ environment, and at module-import time the consumer hasn't set it yet."""
32
+ return {
33
+ "version": 1,
34
+ "disable_existing_loggers": False,
35
+ "formatters": {
36
+ "simple": {
37
+ "format": FORMAT,
38
+ "datefmt": "%y/%m/%d %H:%M:%S",
39
+ }
40
+ },
41
+ "handlers": {
42
+ "stdout": {
43
+ "class": "logging.StreamHandler",
44
+ "level": "INFO",
45
+ "formatter": "simple",
46
+ "stream": "ext://sys.stdout",
47
+ },
48
+ "stderr": {
49
+ "class": "logging.StreamHandler",
50
+ "level": "ERROR",
51
+ "formatter": "simple",
52
+ "stream": "ext://sys.stderr",
53
+ },
54
+ "file": {
55
+ "class": "logging.FileHandler",
56
+ "formatter": "simple",
57
+ "filename": get_log_file_path(),
58
+ "mode": "a",
59
+ },
60
+ },
61
+ "root": {"level": "DEBUG", "handlers": ["stderr", "stdout", "file"]},
62
+ }
63
+
64
+
65
+ def is_logging_configured():
66
+ # Check if the root logger has any handlers explicitly assigned
67
+ return len(logging.getLogger().handlers) >= 3
68
+
69
+
70
+ def setup_logging():
71
+ """configure the root logger with our handlers; safe to call more than once.
72
+
73
+ for application entry points only -- see the module docstring.
74
+ """
75
+ if not is_logging_configured():
76
+ logging.config.dictConfig(build_config())
77
+ logging.getLogger("py4j").setLevel(logging.ERROR)
78
+ return logging
@@ -0,0 +1,12 @@
1
+ -- revision_id:{{revision_id}};
2
+ -- prev_revision_id:{{prev_revision_id}};
3
+ begin
4
+ -- replace the statements below with the idempotent statements you
5
+ -- would like to have applied to databricks db or local spark(for testing)
6
+ -- crutch scaffolding will use jinja to fill in the cat and schema that are sent to it
7
+ -- this is also taken care of in the gh build.
8
+
9
+ -- e.g:
10
+ -- create schema if not exists {{cat}}.{{schema}};
11
+ -- create table if not exists {{cat}}.{{schema}}.test_table(int_id bigint, stuff string);
12
+ end;
@@ -0,0 +1,4 @@
1
+ -- revision_id:;
2
+ begin
3
+ create catalog if not exists {{cat}};
4
+ end;
@@ -0,0 +1,4 @@
1
+ -- revision_id:;
2
+ begin
3
+ create schema if not exists {{cat}}.{{schema}};
4
+ end;
@@ -0,0 +1,7 @@
1
+ -- revision_id:;
2
+ begin
3
+ create table if not exists {{cat}}.{{schema}}._spark_migrations_version (
4
+ migration_type string not null,
5
+ version_num string not null
6
+ );
7
+ end;
File without changes
File without changes
@@ -0,0 +1,333 @@
1
+ """Chained, idempotent SQL migrations for Spark and Databricks.
2
+
3
+ Two kinds of migration exist, and they are owned by different parties:
4
+
5
+ * the *initial* chain and the new-migration template ship inside this package.
6
+ They bootstrap the catalog, the schema and the version table, are selected by
7
+ filename suffix (``_all.sql`` / ``_dbr_only.sql``) rather than by revision,
8
+ and are re-applied on every run -- so they must be idempotent.
9
+ * the ``all_spark_migrations/`` and ``dbr_only_migrations/`` chains belong to
10
+ the consuming project. The caller passes their parent directory as
11
+ ``migrations_root``; each chain is walked from its root via
12
+ ``prev_revision_id`` and only the tail not yet recorded in the version table
13
+ is applied.
14
+ """
15
+
16
+ import argparse
17
+ import datetime
18
+ import logging
19
+ import os
20
+ import re
21
+ import uuid
22
+ from dataclasses import dataclass
23
+
24
+ from jinja2 import Environment, FileSystemLoader, PackageLoader, select_autoescape
25
+ from pyspark.sql.functions import col
26
+
27
+ from spark_sql_migrations.spark_utils import get_spark, is_dbr
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ ALL_SPARK = "all_spark"
33
+ DBR_ONLY = "dbr_only"
34
+
35
+ VERSION_TABLE = "_spark_migrations_version"
36
+
37
+ PACKAGE_NAME = "spark_sql_migrations"
38
+ INITIAL_MIGRATIONS_PACKAGE_PATH = "migrations_initial"
39
+ TEMPLATES_PACKAGE_PATH = "migration_templates"
40
+ DEFAULT_TEMPLATE_NAME = "default_migration_template.sql"
41
+
42
+ _HEADER_RE = re.compile(r"^--\s*(revision_id|prev_revision_id)\s*:\s*(\w*)\s*;$")
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Migration:
47
+ revision_id: str
48
+ prev_revision_id: str | None
49
+ template_name: str
50
+
51
+
52
+ def get_migrations_dir(migrations_root, migration_type):
53
+ """the client-owned directory holding one chain."""
54
+ return os.path.join(migrations_root, f"{migration_type}_migrations")
55
+
56
+
57
+ def get_default_template_path():
58
+ """the template this package ships; callers may pass their own instead."""
59
+ return os.path.join(os.path.dirname(__file__), "..", TEMPLATES_PACKAGE_PATH, DEFAULT_TEMPLATE_NAME)
60
+
61
+
62
+ def _parse_migration(migrations_dir, template_name):
63
+ headers = {}
64
+ migration_file_path = os.path.join(migrations_dir, template_name)
65
+ if os.path.getsize(migration_file_path) == 0:
66
+ raise ValueError(f"{template_name} is empty;")
67
+ with open(migration_file_path) as migration_file:
68
+ for line in migration_file:
69
+ line = line.strip()
70
+ match = _HEADER_RE.match(line)
71
+ if match:
72
+ headers[match.group(1)] = match.group(2) or None
73
+ elif line and not line.startswith("--"):
74
+ break
75
+
76
+ if not headers.get("revision_id"):
77
+ raise ValueError(f"{template_name} has no revision_id header;")
78
+
79
+ return Migration(
80
+ revision_id=headers["revision_id"],
81
+ prev_revision_id=headers.get("prev_revision_id"),
82
+ template_name=template_name,
83
+ )
84
+
85
+
86
+ def get_ordered_migration_objs(migration_objs):
87
+ by_revision = {}
88
+ for migration in migration_objs:
89
+ clash = by_revision.get(migration.revision_id)
90
+ if clash:
91
+ raise ValueError(
92
+ f"revision_id {migration.revision_id} is claimed by both "
93
+ f"{clash.template_name} and {migration.template_name};"
94
+ )
95
+ by_revision[migration.revision_id] = migration
96
+
97
+ roots = [migration for migration in migration_objs if not migration.prev_revision_id]
98
+ if len(roots) != 1:
99
+ raise ValueError(
100
+ f"expected exactly one migration with an empty prev_revision_id, "
101
+ f"found {[m.template_name for m in roots]};"
102
+ )
103
+
104
+ next_by_revision = {}
105
+ for migration in migration_objs:
106
+ if not migration.prev_revision_id:
107
+ continue
108
+ if migration.prev_revision_id not in by_revision:
109
+ raise ValueError(
110
+ f"{migration.template_name} points at unknown prev_revision_id {migration.prev_revision_id};"
111
+ )
112
+ sibling = next_by_revision.get(migration.prev_revision_id)
113
+ if sibling:
114
+ raise ValueError(
115
+ f"revision_id {migration.prev_revision_id} is the parent of both "
116
+ f"{sibling.template_name} and {migration.template_name};"
117
+ )
118
+ next_by_revision[migration.prev_revision_id] = migration
119
+
120
+ ordered = []
121
+ current = roots[0]
122
+ while current:
123
+ ordered.append(current)
124
+ current = next_by_revision.get(current.revision_id)
125
+
126
+ if len(ordered) != len(migration_objs):
127
+ walked = {migration.template_name for migration in ordered}
128
+ raise ValueError(
129
+ f"Migrations are not reachable from the root: "
130
+ f"{sorted(m.template_name for m in migration_objs if m.template_name not in walked)};"
131
+ )
132
+
133
+ return ordered
134
+
135
+
136
+ def get_migrations_list(migrations_dir):
137
+ """every migration in one directory, walked from its root to its head."""
138
+ if not os.path.isdir(migrations_dir):
139
+ raise ValueError(f"no migrations dir at {migrations_dir};")
140
+
141
+ migrations = [
142
+ _parse_migration(migrations_dir, template_name)
143
+ for template_name in sorted(os.listdir(migrations_dir))
144
+ if template_name.endswith(".sql")
145
+ ]
146
+ if not migrations:
147
+ return []
148
+
149
+ return get_ordered_migration_objs(migrations)
150
+
151
+
152
+ def get_unapplied_migrations_list(spark, migrations_dir, migration_type, cat: str, schema: str):
153
+ """the tail of one chain after the revision VERSION_TABLE records for it.
154
+
155
+ the whole chain when the table is missing or holds no row for this type.
156
+ """
157
+ ordered = get_migrations_list(migrations_dir)
158
+
159
+ version_table = f"{cat}.{schema}.{VERSION_TABLE}"
160
+ if not spark.catalog.tableExists(version_table):
161
+ return ordered
162
+
163
+ current = (
164
+ spark.read.table(version_table).where(col("migration_type") == migration_type).select("version_num").head()
165
+ )
166
+ if not current:
167
+ return ordered
168
+
169
+ current_revision_id = current["version_num"]
170
+
171
+ for index, migration in enumerate(ordered):
172
+ if migration.revision_id == current_revision_id:
173
+ return ordered[index + 1 :]
174
+
175
+ raise ValueError(
176
+ f"{VERSION_TABLE} has {migration_type} at {current_revision_id}, "
177
+ f"which matches no migration in {migrations_dir};"
178
+ )
179
+
180
+
181
+ def create_new_migration(message: str, template_path: str, output_path: str, truncate_slug_length: int = 40):
182
+ """
183
+ TODO XXX start looking up prev revision id from db or files and including it
184
+ """
185
+ rev_id = uuid.uuid4().hex[-12:]
186
+
187
+ date_prefix = datetime.datetime.today().strftime("%y%m%d")
188
+
189
+ slug = "_".join(re.split(r"\W+", message.lower())).strip("_")
190
+ if len(slug) > truncate_slug_length:
191
+ slug = slug[:truncate_slug_length].rsplit("_", 1)[0]
192
+
193
+ migration_filename = f"{date_prefix}_{slug}_{rev_id}.sql"
194
+
195
+ migration_path = os.path.join(output_path, migration_filename)
196
+
197
+ default_migration_content = open(template_path).read()
198
+ default_migration_content = default_migration_content.replace("{{revision_id}}", rev_id)
199
+
200
+ with open(migration_path, "w") as migration_file:
201
+ migration_file.write(default_migration_content)
202
+
203
+
204
+ def apply_template(output_dir, template, cat: str, schema: str):
205
+ result_sql = template.render(cat=cat, schema=schema)
206
+ with open(os.path.join(output_dir, template.name.replace(".sql", "_primed.sql")), "w") as file_handle:
207
+ file_handle.write(result_sql)
208
+ return result_sql
209
+
210
+
211
+ def get_ascending_letters_within_minute():
212
+ micros_since_minute = datetime.datetime.now() - datetime.datetime.now().replace(second=0, microsecond=0)
213
+ result = str(micros_since_minute.microseconds).translate(str.maketrans("0123456789", "ABCDEFGHIJ"))
214
+ return result
215
+
216
+
217
+ def get_output_folder(output_parent_path):
218
+ folder_name = f"{datetime.datetime.today().strftime('%Y%m%d_%H%M')}_{get_ascending_letters_within_minute()}"
219
+ return os.path.join(output_parent_path, folder_name)
220
+
221
+
222
+ def use_migration_file(fname):
223
+ if fname.endswith("all.sql"):
224
+ return True
225
+ elif is_dbr() and fname.endswith("dbr_only.sql"):
226
+ return True
227
+ return False
228
+
229
+
230
+ def migrate_initial(spark, output_folder, cat: str, schema: str):
231
+ """apply the package's own bootstrap chain; selected by suffix, not revision."""
232
+ env = Environment(
233
+ loader=PackageLoader(package_name=PACKAGE_NAME, package_path=INITIAL_MIGRATIONS_PACKAGE_PATH),
234
+ autoescape=select_autoescape(),
235
+ )
236
+ all_templates = env.list_templates(filter_func=use_migration_file)
237
+
238
+ logger.info(f"found {len(all_templates)} migrations; first five are {all_templates[:5]};")
239
+ for template_name in all_templates:
240
+ result_sql = apply_template(output_folder, env.get_template(template_name), cat=cat, schema=schema)
241
+ spark.sql(result_sql)
242
+ logger.info(f"invoked spark on {len(all_templates)} migrations;")
243
+
244
+
245
+ def record_revision(spark, cat: str, schema: str, migration_type: str, revision_id: str):
246
+ """point VERSION_TABLE's row for one migration type at revision_id.
247
+
248
+ delete + insert rather than merge: there is one row per type, and a replay
249
+ after a crash between the two statements is harmless because migrations are
250
+ idempotent. the values are inlined rather than passed as `args` because
251
+ delta's DELETE does not bind named parameters.
252
+ """
253
+ version_table = f"{cat}.{schema}.{VERSION_TABLE}"
254
+ type_literal = migration_type.replace("'", "''")
255
+ revision_literal = revision_id.replace("'", "''")
256
+ spark.sql(f"delete from {version_table} where migration_type = '{type_literal}'")
257
+ spark.sql(
258
+ f"insert into {version_table} (migration_type, version_num) " f"values ('{type_literal}', '{revision_literal}')"
259
+ )
260
+
261
+
262
+ def migrate_w_rev(spark, output_folder, migrations_root, cat: str, schema: str, migration_type: str):
263
+ """apply the migrations of one client chain that VERSION_TABLE hasn't recorded yet."""
264
+ migrations_dir = get_migrations_dir(migrations_root, migration_type)
265
+ unapplied = get_unapplied_migrations_list(spark, migrations_dir, migration_type, cat=cat, schema=schema)
266
+
267
+ logger.info(
268
+ f"{migration_type} has {len(unapplied)} unapplied migrations; "
269
+ f"first five are {[migration.template_name for migration in unapplied[:5]]};"
270
+ )
271
+
272
+ env = Environment(loader=FileSystemLoader(migrations_dir), autoescape=select_autoescape())
273
+ for migration in unapplied:
274
+ result_sql = apply_template(output_folder, env.get_template(migration.template_name), cat=cat, schema=schema)
275
+ spark.sql(result_sql)
276
+ record_revision(spark, cat, schema, migration_type, migration.revision_id)
277
+ logger.info(f"applied {migration.template_name}; {migration_type} is now at {migration.revision_id};")
278
+
279
+
280
+ def run_migrations(spark, cat, schema, output_folder, migrations_root):
281
+ initial_output_folder = os.path.join(output_folder, INITIAL_MIGRATIONS_PACKAGE_PATH)
282
+ dbr_ouput_folder = os.path.join(output_folder, f"{DBR_ONLY}_migrations")
283
+ all_spark_ouput_folder = os.path.join(output_folder, f"{ALL_SPARK}_migrations")
284
+ os.makedirs(initial_output_folder, exist_ok=True)
285
+ os.makedirs(dbr_ouput_folder, exist_ok=True)
286
+ os.makedirs(all_spark_ouput_folder, exist_ok=True)
287
+ migrate_initial(spark, initial_output_folder, cat, schema)
288
+ if is_dbr():
289
+ migrate_w_rev(spark, dbr_ouput_folder, migrations_root, cat, schema, DBR_ONLY)
290
+ migrate_w_rev(spark, all_spark_ouput_folder, migrations_root, cat, schema, ALL_SPARK)
291
+
292
+
293
+ def main(cat, schema, migrations_dir, output_parent_path=None):
294
+ output_folder = get_output_folder(output_parent_path or os.path.join(os.getcwd(), "migrations_out"))
295
+ os.makedirs(output_folder)
296
+ run_migrations(get_spark(), cat, schema, output_folder, migrations_dir)
297
+
298
+
299
+ def _cli_main(cat, schema, migrations_dir): # pragma: no cover
300
+ main(cat, schema, migrations_dir)
301
+
302
+
303
+ def _cli_create_new_migration(message, output_path, template_path): # pragma: no cover
304
+ create_new_migration(message, template_path or get_default_template_path(), output_path)
305
+
306
+
307
+ def build_parser(): # pragma: no cover
308
+ parser = argparse.ArgumentParser(description="spark_sql_migrations migration utilities")
309
+ subparsers = parser.add_subparsers(dest="command", required=True)
310
+
311
+ p_run = subparsers.add_parser("run", help="apply all pending migrations")
312
+ p_run.add_argument("--cat", default="spark_catalog")
313
+ p_run.add_argument("--schema", default="default")
314
+ p_run.add_argument(
315
+ "--migrations-dir", required=True, help="parent of all_spark_migrations/ and dbr_only_migrations/"
316
+ )
317
+ p_run.set_defaults(func=_cli_main)
318
+
319
+ p_create = subparsers.add_parser("create_new_migration", help="create a new migration from the template")
320
+ p_create.add_argument("--message", required=True)
321
+ p_create.add_argument("--output-path", required=True, help="the chain directory to write the new migration into")
322
+ p_create.add_argument("--template-path", default=None, help="defaults to the template shipped in this package")
323
+ p_create.set_defaults(func=_cli_create_new_migration)
324
+
325
+ return parser
326
+
327
+
328
+ if __name__ == "__main__": # pragma: no cover
329
+ args = build_parser().parse_args()
330
+ kwargs = vars(args)
331
+ func = kwargs.pop("func")
332
+ kwargs.pop("command")
333
+ func(**kwargs)
@@ -0,0 +1,72 @@
1
+ import os
2
+ import sys
3
+
4
+ from delta import configure_spark_with_delta_pip # type: ignore
5
+ from pyspark.sql.session import SparkSession
6
+
7
+ APP_NAME = "spark_sql_migrations"
8
+
9
+ WAREHOUSE_DIR_ENV_VAR = "SPARK_WAREHOUSE_DIR"
10
+ METASTORE_DIR_ENV_VAR = "SPARK_METASTORE_DIR"
11
+ DEFAULT_WAREHOUSE_DIRNAME = "spark-warehouse"
12
+
13
+
14
+ def is_dbr():
15
+ try:
16
+ from pyspark.dbutils import DBUtils # type: ignore # noqa: F401
17
+
18
+ # This will only succeed if the Databricks environment is available
19
+ return True # pragma: no cover
20
+ except Exception:
21
+ return False
22
+
23
+
24
+ def get_warehouse_dir():
25
+ """where local (non-DBR) spark keeps its warehouse.
26
+
27
+ resolved against the caller's cwd, never against __file__: installed from a
28
+ wheel this module lives in site-packages, so a __file__-relative default
29
+ would write the consumer's tables inside their virtualenv.
30
+ """
31
+ return os.environ.get(
32
+ WAREHOUSE_DIR_ENV_VAR,
33
+ os.path.join(os.getcwd(), DEFAULT_WAREHOUSE_DIRNAME),
34
+ )
35
+
36
+
37
+ def get_spark(use_dbc=False):
38
+ if use_dbc or is_dbr():
39
+ from databricks.connect.session import DatabricksSession # type: ignore # pants: no-infer-dep
40
+
41
+ os.environ["DATABRICKS_SERVERLESS_COMPUTE_ID"] = "auto"
42
+ return DatabricksSession.builder.getOrCreate()
43
+
44
+ spark_remote = os.environ.get("SPARK_REMOTE")
45
+ if spark_remote:
46
+ return SparkSession.builder.remote(spark_remote).getOrCreate()
47
+
48
+ # Pin the worker interpreter to the one actually running this process. Left
49
+ # unset, Spark resolves "python3" independently for the worker daemon, which
50
+ # can land on a different Python build than the driver's when launched from
51
+ # an IDE (mismatched sys.executable vs. PATH resolution) -- causing worker
52
+ # crashes like "SRE module mismatch" that don't reproduce from the CLI.
53
+ os.environ.setdefault("PYSPARK_PYTHON", sys.executable)
54
+ os.environ.setdefault("PYSPARK_DRIVER_PYTHON", sys.executable)
55
+
56
+ builder = (
57
+ SparkSession.builder.appName(APP_NAME)
58
+ .config("spark.sql.warehouse.dir", get_warehouse_dir())
59
+ .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
60
+ .config(
61
+ "spark.sql.catalog.spark_catalog",
62
+ "org.apache.spark.sql.delta.catalog.DeltaCatalog",
63
+ )
64
+ .config("spark.sql.sources.default", "delta")
65
+ )
66
+ metastore_dir = os.environ.get(METASTORE_DIR_ENV_VAR)
67
+ if metastore_dir:
68
+ builder = builder.config(
69
+ "javax.jdo.option.ConnectionURL",
70
+ f"jdbc:derby:;databaseName={metastore_dir};create=true",
71
+ )
72
+ return configure_spark_with_delta_pip(builder).getOrCreate()
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: spark_sql_migrations
3
+ Version: 0.0.1
4
+ Summary: Chained, idempotent SQL migrations for Spark and Databricks.
5
+ Home-page: https://github.com/mcjug2015/spark_sql_migrations
6
+ Author: Victor Semenov
7
+ License: Apache-2.0
8
+ Project-URL: Source, https://github.com/mcjug2015/spark_sql_migrations
9
+ Project-URL: Issues, https://github.com/mcjug2015/spark_sql_migrations/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: SQL
14
+ Classifier: Topic :: Database
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: Jinja2<4,>=3.1
20
+ Provides-Extra: local
21
+ Requires-Dist: pyspark[connect]<5,>=4.0; extra == "local"
22
+ Requires-Dist: delta-spark<5,>=4.0; extra == "local"
23
+ Provides-Extra: databricks
24
+ Requires-Dist: databricks-connect<19,>=18; extra == "databricks"
25
+ Dynamic: author
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: project-url
33
+ Dynamic: provides-extra
34
+ Dynamic: requires-dist
35
+ Dynamic: requires-python
36
+ Dynamic: summary
37
+
38
+ # spark_sql_migrations
39
+
40
+ [![CI](https://github.com/mcjug2015/spark_sql_migrations/actions/workflows/ci.yml/badge.svg)](https://github.com/mcjug2015/spark_sql_migrations/actions/workflows/ci.yml)
41
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
42
+
43
+ Chained, idempotent SQL migrations for Spark and Databricks.
44
+
45
+ Alembic-shaped schema migrations for a Spark/Delta catalog: your migrations are plain
46
+ `.sql` files linked into a chain by revision headers, the applied revision is recorded in
47
+ a version table inside your own schema, and each run applies only the tail that has not
48
+ been applied yet.
49
+
50
+ ## Why
51
+
52
+ Spark and Databricks have no migration story of their own. Delta gives you `CREATE TABLE
53
+ IF NOT EXISTS`, but nothing that tracks which DDL a given catalog has seen, and nothing
54
+ that lets you write a change once and have it apply on a laptop and on Databricks alike.
55
+ spark_sql_migrations is the small amount of machinery that closes that gap, and nothing
56
+ more: no ORM, no autogeneration, no Python migration scripts. You write SQL.
57
+
58
+ ## Installing
59
+
60
+ `spark_sql_migrations` declares **no Spark of its own** — the extras decide which one you get:
61
+
62
+ ```bash
63
+ pip install "spark_sql_migrations[local]" # pyspark + delta-spark, for laptops and CI
64
+ pip install "spark_sql_migrations[databricks]" # databricks-connect
65
+ pip install spark_sql_migrations # no Spark at all
66
+ ```
67
+
68
+ Pick exactly one flavour. `databricks-connect` ships its own top-level `pyspark/` and
69
+ `delta/` packages, so installing it alongside `pyspark`/`delta-spark` silently clobbers
70
+ both.
71
+
72
+ Unreleased changes can be consumed as the wheel built by CI (the `dist` artifact on any
73
+ green run) or built locally with `pants package //:dist`.
74
+
75
+ ## The two kinds of migration
76
+
77
+ Migrations come from two different owners, and they behave differently:
78
+
79
+ | | ships in the wheel | owned by you |
80
+ |---|---|---|
81
+ | **what** | catalog, schema, `_spark_migrations_version` table | your tables and columns |
82
+ | **where** | `spark_sql_migrations/migrations_initial/` | `all_spark_migrations/`, `dbr_only_migrations/` |
83
+ | **selected by** | filename suffix — `_all.sql` everywhere, `_dbr_only.sql` on Databricks | the `prev_revision_id` chain |
84
+ | **when applied** | every run | once, then recorded |
85
+
86
+ The bootstrap chain is re-applied on **every** run, so it must be idempotent. Your own
87
+ chains are applied once each and their head revision is written to the version table.
88
+
89
+ ## Laying out your chains
90
+
91
+ Point spark_sql_migrations at a directory holding one or both chains:
92
+
93
+ ```
94
+ your_project/
95
+ └── migrations/ <- this is --migrations-dir
96
+ ├── all_spark_migrations/ <- runs everywhere
97
+ └── dbr_only_migrations/ <- runs only when is_dbr()
98
+ ```
99
+
100
+ Choose deliberately. SQL that only Databricks understands must not live in
101
+ `all_spark_migrations/`, or your local runs will break.
102
+
103
+ ## Running migrations
104
+
105
+ ```bash
106
+ python -m spark_sql_migrations.spark_sql.spark_sql run --cat spark_catalog --schema default --migrations-dir path/to/migrations
107
+ ```
108
+
109
+ Or from Python, which is what a consuming project usually wraps:
110
+
111
+ ```python
112
+ import os
113
+
114
+ from spark_sql_migrations.spark_sql.spark_sql import main
115
+
116
+
117
+ def get_migrations_dir():
118
+ """the parent of this project's own migration chains."""
119
+ return os.path.dirname(__file__)
120
+
121
+
122
+ main(cat="spark_catalog", schema="default", migrations_dir=get_migrations_dir())
123
+ ```
124
+
125
+ `main` builds its own session via `get_spark()`. To supply your own — a session already
126
+ configured by your job, say — call `run_migrations(spark, cat, schema, output_folder,
127
+ migrations_root)` directly.
128
+
129
+ Every rendered statement is written to a timestamped folder under `migrations_out/`
130
+ before it is executed, so you can always read the exact SQL a run applied.
131
+
132
+ ## Writing a migration
133
+
134
+ Generate one rather than hand-rolling the header:
135
+
136
+ ```bash
137
+ python -m spark_sql_migrations.spark_sql.spark_sql create_new_migration --message "add batch id to metrics" --output-path path/to/migrations/all_spark_migrations
138
+ ```
139
+
140
+ That writes `<yymmdd>_<slug>_<revision_id>.sql` from the template shipped in the package
141
+ (override with `--template-path`), with `revision_id` filled in:
142
+
143
+ ```sql
144
+ -- revision_id:e5ce0039b32b;
145
+ -- prev_revision_id:;
146
+ begin
147
+ create table if not exists {{cat}}.{{schema}}.test_table(int_id bigint, stuff string);
148
+ end;
149
+ ```
150
+
151
+ Then set `prev_revision_id` to the revision this one follows. Ordering comes from that
152
+ chain, **not** from the filename — the date prefix is for humans. A chain must have
153
+ exactly one root (empty `prev_revision_id`) and no forks.
154
+
155
+ `{{cat}}` and `{{schema}}` are Jinja placeholders rendered at apply time; never hardcode a
156
+ catalog or schema.
157
+
158
+ ### Idempotency
159
+
160
+ Prefer `IF NOT EXISTS`. Where Databricks doesn't offer it — notably
161
+ `ALTER TABLE ... ADD COLUMN` — guard with a SQLSTATE exit handler:
162
+
163
+ ```sql
164
+ -- revision_id:57037b6c19b4;
165
+ -- prev_revision_id:07990e2a101e;
166
+ begin
167
+ -- idempotent add: swallow FIELD_ALREADY_EXISTS (SQLSTATE 42710) if the column
168
+ -- is already present. Databricks has no ADD COLUMN IF NOT EXISTS, so use a
169
+ -- SQL-scripting EXIT handler (CONTINUE handlers are unsupported).
170
+ declare exit handler for sqlstate '42710'
171
+ begin end;
172
+ alter table {{cat}}.{{schema}}.metrics add column metric_batch_id string;
173
+ end;
174
+ ```
175
+
176
+ ## Local vs Databricks
177
+
178
+ `get_spark()` returns a `DatabricksSession` when `is_dbr()` is true and a Delta-configured
179
+ local `SparkSession` otherwise, so the same code runs in both places. Local behaviour is
180
+ tuned by environment variables:
181
+
182
+ | Variable | Effect |
183
+ |---|---|
184
+ | `SPARK_WAREHOUSE_DIR` | warehouse location (default: `./spark-warehouse`) |
185
+ | `SPARK_METASTORE_DIR` | Derby metastore location; unset means Spark's default |
186
+ | `SPARK_REMOTE` | connect to an existing Spark Connect server instead of starting one |
187
+
188
+ ## Development
189
+
190
+ Built with [Pants](https://www.pantsbuild.org/). Two resolves: `python-default` for the
191
+ library, `py-reqs-dev` for tests.
192
+
193
+ ```bash
194
+ # black, isort, flake8, mypy. `::` and not `/`, or the subtrees go unchecked.
195
+ pants fmt lint check spark_sql_migrations:: spark_sql_migrations_test:: scripts::
196
+
197
+ # unit, then integration as its own invocation
198
+ pants test --use-coverage spark_sql_migrations_test/:: -spark_sql_migrations_test/integration::
199
+ pants test spark_sql_migrations_test/integration::
200
+
201
+ # wheel + sdist
202
+ pants package //:dist
203
+ ```
204
+
205
+ `scripts/run_local.sh` runs everything CI runs, including building the distribution and
206
+ verifying all three install flavours. Branch coverage over `spark_sql_migrations/` is
207
+ gated at 94%.
208
+
209
+ Dependencies are locked. Edit `spark_sql_migrations/requirements.txt` or
210
+ `spark_sql_migrations_test/requirements-dev.txt`, then `pants generate-lockfiles` — never
211
+ hand-edit a
212
+ lockfile.
213
+
214
+ ## License
215
+
216
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,16 @@
1
+ spark_sql_migrations/__init__.py,sha256=y-dGVkeeYXwDinWN23rRRbwScEhHUwFBicF7YSWMlzM,442
2
+ spark_sql_migrations/custom_logging.py,sha256=Dj0BlnU4L39ylKSEzdz_SaEGgj8nm7izioBOoJDo5YQ,2671
3
+ spark_sql_migrations/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ spark_sql_migrations/spark_utils.py,sha256=ImNrHsXwcxREk6YNxR7aXry1nrTjKuBC6EkzNcX9Fx8,2664
5
+ spark_sql_migrations/migration_templates/default_migration_template.sql,sha256=fjk9ykmwtF3t9Rl_0EuzoyW8-kBGTY3PtSHBJRZYuQU,510
6
+ spark_sql_migrations/migrations_initial/first_01_intial_create_cat_dbr_only.sql,sha256=sGAYGHC0o26E3XsGavO9BKeYYcDr8NKKHyQZP3nce-8,65
7
+ spark_sql_migrations/migrations_initial/first_02_intial_create_schema_all.sql,sha256=qM0sUDgOTyZR-7VmEwyJil5kaygi7fAy7lmGlyXo_Og,75
8
+ spark_sql_migrations/migrations_initial/first_03_intial_create_state_table_all.sql,sha256=JFochIA3chVvCARtjcgU2WOeGvdtmeocpI2CDA0eIQU,172
9
+ spark_sql_migrations/spark_sql/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ spark_sql_migrations/spark_sql/spark_sql.py,sha256=Ici1ssXcAj7UsaQSWRpgc-1eJ4q-aXh6O_AZRYZrueQ,13208
11
+ spark_sql_migrations-0.0.1.dist-info/licenses/LICENSE,sha256=TJdL-klfWUy-m2zkW6TSKRkJv3eLTTYWgUfM1wSzm8M,11345
12
+ spark_sql_migrations-0.0.1.dist-info/METADATA,sha256=UEVZpKkSfZuCVvZXCK8BLhq2tpIZc3lL96CF7aUzEYc,8050
13
+ spark_sql_migrations-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
+ spark_sql_migrations-0.0.1.dist-info/namespace_packages.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
15
+ spark_sql_migrations-0.0.1.dist-info/top_level.txt,sha256=eC1HgBkv7dOjkovdGlvNGpx4KyC_OHkDkJg3RuTJhT4,21
16
+ spark_sql_migrations-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Victor Semenov
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ spark_sql_migrations