diff --git a/migrations/versions/rev_20261202_10_e5b4b207f490_store_the_directions_of_paths_as_json_.py b/migrations/versions/rev_20261202_10_e5b4b207f490_store_the_directions_of_paths_as_json_.py new file mode 100644 index 0000000..6962ba7 --- /dev/null +++ b/migrations/versions/rev_20261202_10_e5b4b207f490_store_the_directions_of_paths_as_json_.py @@ -0,0 +1,53 @@ +"""Store the directions of paths as JSON arrays. + +The "directions" column in "addresses_addresses" is of type `JSON`, +but `Path.sync_with_google_maps()` stored a JSON-encoded string in it. +So, the data was encoded twice: PostgreSQL saw one JSON string +instead of an array of latitude-longitude pairs. + +The `WHERE` clauses make both directions safe to run more than once. +""" + +import os + +from alembic import op + +from velofy import configuration + + +revision = "e5b4b207f490" +down_revision = "09c70662dda4" +branch_labels = None +depends_on = None + + +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") + + +def upgrade(): + """Upgrade to the next revision.""" + op.execute( + f""" + UPDATE + {config.CLEAN_SCHEMA}.addresses_addresses + SET + -- `#>> '{{}}'` extracts the text of a JSON string; `::json` parses it + directions = (directions #>> '{{}}')::json + WHERE + json_typeof(directions) = 'string'; + """, + ) + + +def downgrade(): + """Downgrade to the previous revision.""" + op.execute( + f""" + UPDATE + {config.CLEAN_SCHEMA}.addresses_addresses + SET + directions = to_json(directions::text) + WHERE + json_typeof(directions) = 'array'; + """, + )