feat(db): create and migrate the schema on a Postgres database

With TREK_DB_URL set, TREK now boots on Postgres; without it nothing changes.

- The database engine contract gains open, close, reopen and the schema
  bootstrap; DatabaseLifecycle delegates to the engine resolveEngine() picks.
- An empty Postgres database gets server/assets/postgres/baseline.sql
  (generated from the entities by gen:pg-baseline, with the reference rows
  the migrations up to its cut insert: tour types, provider catalogues,
  addons, app settings) and every migration up to its cut recorded as
  executed, in one transaction. A database holding tables
  without TREK's history is refused before anything is written; a migrated one
  runs the newer-database refusal and its pending migrations, which refuse
  without a copy unless TREK_DB_PRE_MIGRATE_SNAPSHOT=false.
- INTEGER columns are bigint on Postgres (SQLite's INTEGER is 64-bit: an
  epoch-millisecond column overflowed int4), and the engine's driver reads
  bigint and numeric back as numbers, refusing values past 2^53.
- The two SQLite triggers are ported to PL/pgSQL; check:pg-baseline fails
  while a SQLite trigger has no port, and while the baseline drifts from the
  entities before a later migration freezes it.
- Backups and restores on Postgres refuse until they can dump and load one.
- Migration helpers read the catalog per engine (dialect/catalog.ts), and
  the email case index no longer needs group_concat.
- CI runs check:pg-baseline and boots the image on postgres:17 twice.
This commit is contained in:
Isaias Tavares
2026-11-02 14:25:34 -03:00
parent 25f5e34558
commit a77705984e
40 changed files with 2655 additions and 229 deletions
+70 -1
View File
@@ -44,7 +44,7 @@ permissions:
# Client: Bundle the production build, one chunk per map engine
# Client: End-to-End the app in Chromium and WebKit
# Plugin SDK: Types & Coverage
# Repo: Docker Image builds the image and boots it until ready
# Repo: Docker Image builds the image and boots it until ready, on SQLite and on Postgres
# Repo: Helm Chart & Compose
# Repo: Sonar Scan SonarCloud analysis, not required
# ci-ok the one required check (below)
@@ -282,6 +282,13 @@ jobs:
# migration that changes a column regenerates it in the same change.
run: cd server && npm run check:db-types
- name: Postgres baseline matches the entities
# server/assets/postgres/ is the schema a fresh Postgres database starts
# from, generated from the entities by gen:pg-baseline. Until a migration
# lands after its cut it must match them exactly; after, it is frozen
# and only its list of migrations is checked.
run: cd server && npm run check:pg-baseline
server-lint-checks:
name: 'Server: Lint & Checks'
needs: changes
@@ -1211,10 +1218,72 @@ jobs:
docker logs trek-ci 2>&1 | grep 'SIGTERM received' >/dev/null \
|| { echo "::error::the server never saw SIGTERM"; exit 1; }
# The same image on a Postgres database (TREK_DB_URL): an empty database
# gets the baseline schema, the admin is seeded, and the server answers
# ready. The database runs beside it on a private network, never exposed.
- name: Start the container on Postgres
run: |
set -euo pipefail
docker network create trek-ci-pg
docker run -d --name trek-ci-db --network trek-ci-pg \
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:17
for _ in $(seq 1 30); do
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
sleep 2
done
docker exec trek-ci-db pg_isready -U postgres -d trek \
|| { echo "::error::Postgres did not accept connections within 60 seconds."; exit 1; }
mkdir -p "$RUNNER_TEMP/trek-pg/data" "$RUNNER_TEMP/trek-pg/uploads"
docker run -d --name trek-ci-on-pg --network trek-ci-pg -p 127.0.0.1:3001:3000 \
--read-only --tmpfs /tmp:noexec,nosuid,size=128m \
--security-opt no-new-privileges:true \
--cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID --cap-add KILL \
-v "$RUNNER_TEMP/trek-pg/data:/app/data" \
-v "$RUNNER_TEMP/trek-pg/uploads:/app/uploads" \
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
-e TREK_DB_URL=postgres://postgres:ci@trek-ci-db:5432/trek \
trek:ci
# Twice: the first start creates the schema in the empty database, the
# restart finds it migrated and must start without touching it.
- name: Wait until the server on Postgres is ready, then again after a restart
run: |
wait_ready() {
for _ in $(seq 1 90); do
if [ "$(docker inspect -f '{{.State.Running}}' trek-ci-on-pg)" != "true" ]; then
echo "::error::The container on Postgres exited before it became ready."
exit 1
fi
if curl -sf http://127.0.0.1:3001/api/health/ready; then
echo
return 0
fi
sleep 2
done
echo "::error::/api/health/ready on Postgres did not answer within 180 seconds."
exit 1
}
wait_ready
docker restart -t 30 trek-ci-on-pg >/dev/null
wait_ready
- name: Stop the container on Postgres gracefully
run: |
set -euo pipefail
docker stop -t 30 trek-ci-on-pg >/dev/null
code="$(docker inspect -f '{{.State.ExitCode}}' trek-ci-on-pg)"
[ "$code" = "0" ] || { echo "::error::docker stop ended with exit code $code, not a graceful shutdown"; exit 1; }
- name: Container log
if: always()
run: docker logs trek-ci 2>&1 || true
- name: Container log on Postgres
if: always()
run: |
docker logs trek-ci-on-pg 2>&1 || true
docker logs trek-ci-db 2>&1 | tail -50 || true
# The Helm chart and the compose files are what self-hosters deploy from,
# and before this job only a release ever touched them. The chart is linted,
# rendered with the defaults and with each secret and persistence mode, and
+1
View File
@@ -53,6 +53,7 @@ cd server && npm run lint:boundaries # no new import cycles or cro
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
+3 -2
View File
@@ -91,8 +91,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
# Runtime data assets read from server/assets at runtime: airports.json (flight
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map). The build
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
# database starts from). The build
# only emits dist, so these must be copied explicitly or the features silently
# degrade to empty in the image.
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
+1 -1
View File
@@ -52,7 +52,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
# BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120)
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. Not supported yet: a boot with it set is refused. Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
# TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10)
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
+6 -3
View File
File diff suppressed because one or more lines are too long
+336
View File
@@ -0,0 +1,336 @@
{
"through": "Migration20200101046340_a_released_object_outlasts_every_undo_before_it_goes",
"migrations": [
"Migration20200101000000_baseline_schema",
"Migration20200101000100_users_add_unsplash_api_key",
"Migration20200101000200_users_add_openweather_api_key",
"Migration20200101000300_places_add_duration_minutes",
"Migration20200101000400_places_add_notes",
"Migration20200101000500_places_add_image_url",
"Migration20200101000600_places_add_transport_mode",
"Migration20200101000700_days_add_title",
"Migration20200101000800_reservations_add_status",
"Migration20200101000900_trip_files_add_reservation_id",
"Migration20200101001000_reservations_add_type",
"Migration20200101001100_trips_add_cover_image",
"Migration20200101001200_day_notes_add_icon",
"Migration20200101001300_trips_add_is_archived",
"Migration20200101001400_categories_add_user_id",
"Migration20200101001500_users_add_avatar",
"Migration20200101001600_users_add_oidc_sub",
"Migration20200101001700_users_add_oidc_issuer",
"Migration20200101001800_users_add_last_login",
"Migration20200101001900_create_budget_items_new",
"Migration20200101002000_day_accommodations_add_check_in",
"Migration20200101002100_places_add_end_time",
"Migration20200101002200_day_assignments_add_reservation_status",
"Migration20200101002300_reservations_add_assignment_id",
"Migration20200101002400_create_assignment_participants",
"Migration20200101002500_create_collab_notes",
"Migration20200101002600_day_assignments_add_assignment_time",
"Migration20200101002700_create_budget_item_members",
"Migration20200101002800_create_collab_message_reactions",
"Migration20200101002900_collab_messages_add_deleted",
"Migration20200101003000_trip_files_add_note_id",
"Migration20200101003100_reservations_add_reservation_end_time",
"Migration20200101003200_places_add_osm_id",
"Migration20200101003300_trip_files_add_uploaded_by",
"Migration20200101003400_reservations_add_accommodation_id",
"Migration20200101003500_create_invite_tokens",
"Migration20200101003600_users_add_mfa_enabled",
"Migration20200101003700_create_packing_category_assignees",
"Migration20200101003800_create_packing_templates",
"Migration20200101003900_create_packing_bags",
"Migration20200101004000_create_visited_countries",
"Migration20200101004100_create_bucket_list",
"Migration20200101004200_vacay_plans_add_weekend_days",
"Migration20200101004300_users_add_immich_url",
"Migration20200101004400_create_file_links",
"Migration20200101004500_reservations_add_day_plan_position",
"Migration20200101004600_budget_items_add_paid_by_user_id",
"Migration20200101004700_bucket_list_add_target_date",
"Migration20200101004800_create_notification_preferences",
"Migration20200101004900_notification_preferences_add_notify_vacay_invite",
"Migration20200101005000_create_share_tokens",
"Migration20200101005100_share_tokens_add_share_map",
"Migration20200101005200_create_audit_log",
"Migration20200101005300_users_add_mfa_backup_codes",
"Migration20200101005400_mcp_long_lived_api_tokens",
"Migration20200101005500_mcp_addon_entry",
"Migration20200101005600_index_on_mcp_tokens",
"Migration20200101005700_ensure_mcp_addon_type_is_integration",
"Migration20200101005800_places_add_route_geometry",
"Migration20200101005900_users_add_must_change_password",
"Migration20200101010000_trips_add_reminder_days",
"Migration20200101010100_encrypt_any_plaintext_oidc_client_secret_left",
"Migration20200101010200_encrypt_any_plaintext_smtp_pass_left_in",
"Migration20200101010300_encrypt_any_plaintext_immich_api_key_values",
"Migration20200101010400_budget_items_add_expense_date",
"Migration20200101010500_create_trip_album_links",
"Migration20200101010600_create_notifications",
"Migration20200101010700_create_trip_photos",
"Migration20200101010800_create_trip_album_links",
"Migration20200101010900_users_add_synology_url",
"Migration20200101011000_step_070",
"Migration20200101011100_step_071",
"Migration20200101011200_step_072",
"Migration20200101011300_trip_photos_add_album_link_id",
"Migration20200101011400_todo_items",
"Migration20200101011500_backfill_addons",
"Migration20200101011600_place_region_cache_for_sub_national_atlas",
"Migration20200101011700_create_visited_regions",
"Migration20200101011800_normalized_per_user_per_channel_notification_preferences",
"Migration20200101011900_drop_the_old_notification_preferences_table",
"Migration20200101012000_add_reservation_id_to_budget_items_for",
"Migration20200101012100_add_quantity_to_packing_items_user_id",
"Migration20200101012200_per_day_positions_for_multi_day_reservations",
"Migration20200101012300_budget_category_ordering",
"Migration20200101012400_naver_list_import_addon",
"Migration20200101012500_oauth_2",
"Migration20200101012600_refresh_token_rotation_chain_tracking_for_replay",
"Migration20200101012700_public_client_support_for_browser_initiated_dynamic",
"Migration20200101012800_make_oauth_clients",
"Migration20200101012900_add_otp_field_skip_ssl_column_device",
"Migration20200101013000_journey_addon",
"Migration20200101013100_journal",
"Migration20200101013200_journey_multi_trip_support_sharing_collaboration",
"Migration20200101013300_journey_rebuild",
"Migration20200101013400_journey_photos",
"Migration20200101013500_journey_cover_image",
"Migration20200101013600_pros_cons_for_journey_entries",
"Migration20200101013700_journey_share_tokens",
"Migration20200101013800_vacay_week_start_setting",
"Migration20200101013900_unified_photo_provider_abstraction_layer",
"Migration20200101014000_hide_skeletons_per_user_setting_on_journey",
"Migration20200101014100_idempotency_keys_for_offline_mutation_replay",
"Migration20200101014200_enable_naver_list_import_by_default",
"Migration20200101014300_add_check_in_end_column_for_check",
"Migration20200101014400_system_notices",
"Migration20200101014500_passphrase_support_for_synology_shared_album_links",
"Migration20200101014600_persistent_google_place_photo_disk_cache_registry",
"Migration20200101014700_persistent_place_details_row_cache",
"Migration20200101014800_backfill_expired_signed_google_photo_urls_to",
"Migration20200101014900_disk_cache_metadata_for_remote_provider_photo",
"Migration20200101015000_reservation_endpoints",
"Migration20200101015100_reservations_add_end_day_id",
"Migration20200101015200_opt_in_immich_auto_upload",
"Migration20200101015300_expose_immich_auto_upload_toggle_in_the",
"Migration20200101015400_rfc_8707_resource_indicators",
"Migration20200101015500_password_reset",
"Migration20200101015600_todo_due_date_reminders",
"Migration20200101015700_security_audit_batch_1",
"Migration20200101015800_widen_idempotency_keys_primary_key_to",
"Migration20200101015900_sec_h6_revoke_all_oauth_tokens_issued",
"Migration20200101020000_remove_not_null_constraint_on_day_accommodations",
"Migration20200101020100_null_out_proxy_image_url_entries_that",
"Migration20200101020200_clear_legacy_google_photo_urls_missed_by",
"Migration20200101020300_journey_gallery_refactor",
"Migration20200101020400_correct_stale_day_id_end_day_id",
"Migration20200101020500_846_make_sort_order_authoritative_within_a",
"Migration20200101020600_swap_inverted_start_day_id_end_day",
"Migration20200101020700_prepare_migration_to_nest_typeorm",
"Migration20200101020800_trim_leading_trailing_whitespace_from_stored_usernames",
"Migration20200101020900_create_schema_version_new",
"Migration20200101021000_oauth_2",
"Migration20200101021100_drop_stale_atlas_cache_rows_for_territories",
"Migration20200101021200_costs_rework",
"Migration20200101021300_rename_the_budget_planner_addon_to_costs",
"Migration20200101021400_webauthn_passkey_support_per_user_credentials_single",
"Migration20200101021500_atlas_dropped_natural_earth_for_geoboundaries",
"Migration20200101021600_step_136",
"Migration20200101021700_users_add_airtrail_url",
"Migration20200101021800_reservations_add_external_source",
"Migration20200101021900_users_add_airtrail_write_enabled",
"Migration20200101022000_store_google_maps_feature_ids_separately_from",
"Migration20200101022100_remember_the_app_version_a_notice_was",
"Migration20200101022200_budget_item_members_add_amount",
"Migration20200101022300_calendar_feed_tokens",
"Migration20200101022400_optimistic_concurrency_token_for_offline_conflict_detection",
"Migration20200101022500_video_support",
"Migration20200101022600_dedicated_booking_url",
"Migration20200101022700_private_packing_items",
"Migration20200101022800_guest_members",
"Migration20200101022900_three_tier_packing_sharing",
"Migration20200101023000_collections_addon",
"Migration20200101023100_user_added_links_on_collections_saved_places",
"Migration20200101023200_per_member_permission_role_on_a_shared",
"Migration20200101023300_per_trip_invite_links",
"Migration20200101023400_optional_trip_binding_on_an_admin_invite",
"Migration20200101023500_plugin_system_scaffold",
"Migration20200101023600_separate_the_admin_s_on_off_intent",
"Migration20200101023700_plugin_capabilities",
"Migration20200101023800_tofu_pin_for_a_plugin_s_author",
"Migration20200101023900_hash_chained_capability_audit_log",
"Migration20200101024000_per_collection_custom_labels",
"Migration20200101024100_plugin_owned_metadata_on_core_entities",
"Migration20200101024200_freeze_the_fx_rate_on_settle_up",
"Migration20200101024300_1446_guests_are_per_trip_people_but",
"Migration20200101024400_plugin_dependencies",
"Migration20200101024500_per_user_plugin_settings",
"Migration20200101024600_host_brokered_outbound_oauth",
"Migration20200101024700_persistent_plugin_scheduler",
"Migration20200101024800_durable_gdpr_erasure_queue",
"Migration20200101024900_tombstones_for_atlas_countries_the_user_has",
"Migration20200101025000_operator_supplied_egress_hosts_for_a_plugin",
"Migration20200101025100_settings_page_action_buttons_a_plugin_contributes",
"Migration20200101025200_why_a_plugin_s_update_was_refused",
"Migration20200101025300_the_semver_range_of_trek_versions_a",
"Migration20200101025400_place_regions_is_a_re_derivable_nominatim",
"Migration20200101025500_tombstones_for_atlas_regions_the_user_has",
"Migration20200101025600_half_vacation_days",
"Migration20200101025700_read_only_vacay_calendar_sharing",
"Migration20200101025800_collaborative_place_ratings",
"Migration20200101025900_per_segment_travel_mode",
"Migration20200101030000_school_holidays_are_a_visual_vacay_calendar",
"Migration20200101030100_1517",
"Migration20200101030200_comp_flex_days",
"Migration20200101030300_configurable_vacation_year",
"Migration20200101030400_manual_gpx_track_colour",
"Migration20200101030500_backfill_the_three_places_feature_toggles_before",
"Migration20200101030600_free_the_note_column_on_budget_items",
"Migration20200101030700_note_colours",
"Migration20200101030800_per_segment_travel_mode_for_boundary_legs",
"Migration20200101030900_1298",
"Migration20200101031000_a_reservation_day_positions_row_only_makes",
"Migration20200101031100_1939",
"Migration20200101031200_capture_metadata_on_the_photo_itself",
"Migration20200101031300_a_journey_shared_while_the_trip_is",
"Migration20200101031400_trek_studio_books",
"Migration20200101031500_great_britain_gained_its_counties_and_boroughs",
"Migration20200101031600_storage_slice_2",
"Migration20200101031700_give_back_the_notes_the_ticketjson_step",
"Migration20200101031800_a_deliberate_non_latest_plugin_install_sets",
"Migration20200101031900_reservations_an_automated_ingest_parked_for_review",
"Migration20200101032000_separate_an_integration_key_from_an_mcp",
"Migration20200101032100_naver_list_import_was_typed_trip_but",
"Migration20200101032200_whether_a_journey_s_map_draws_the",
"Migration20200101032300_settings_field_defaults",
"Migration20200101032400_settings_form_actions_gain_a_scope",
"Migration20200101032500_a_journal_entry_that_is_not_a",
"Migration20200101032600_place_shadow_log_which_search_result_a",
"Migration20200101032700_what_kind_of_stop_a_place_is",
"Migration20200101032800_points_a_day_s_drive_is_made",
"Migration20200101032900_which_imported_track_a_day_s_drive",
"Migration20200101033000_rename_the_misnamed_guangdong_province",
"Migration20200101033100_let_a_file_hang_off_an_expense",
"Migration20200101033200_which_chat_message_an_uploaded_image_belongs",
"Migration20200101033300_links_somebody_shared_with_the_trip",
"Migration20200101033400_route_usage_counters",
"Migration20200101033500_how_full_this_stop_fills_the_tank",
"Migration20200101033600_create_school_holiday_countries",
"Migration20200101033700_day_assignments_add_end_day",
"Migration20200101033800_create_roadtrip_day_boundaries",
"Migration20200101033900_create_roadtrip_preferences",
"Migration20200101034000_a_settle_up_payment_s_date_was",
"Migration20200101034100_amap",
"Migration20200101034200_dawarich_connection",
"Migration20200101034300_reviewed_visit_suggestions",
"Migration20200101034400_bucket_list_entries_can_now_be_ticked",
"Migration20200101034500_where_an_atlas_country_came_from",
"Migration20200101034600_per_key_read_scopes_for_api_v1",
"Migration20200101034700_where_a_place_came_from_when_it",
"Migration20200101034800_provenance_for_a_day_stop_that_a",
"Migration20200101034900_give_every_stay_booked_before_this_release",
"Migration20200101035000_the_same_sweep_once_more_for_the",
"Migration20200101035100_a_suggestion_the_traveller_has_waved_away",
"Migration20200101035200_the_country_an_entry_happened_in_resolved",
"Migration20200101035300_which_of_the_optional_entry_fields_a",
"Migration20200101035400_let_go_of_a_booking_the_day",
"Migration20200101035500_a_journal_skeleton_belongs_to_a_day",
"Migration20200101035600_document_providers_part_1_of_3_the",
"Migration20200101035700_document_providers_part_2_of_3_the",
"Migration20200101035800_document_providers_part_3_of_3_the",
"Migration20200101035900_document_providers_when_trek_itself_put_a",
"Migration20200101040000_trips_longer_than_a_year_lost_every",
"Migration20200101040100_the_road_trip_day_boundaries_carried_the",
"Migration20200101040200_trek_photo_cache_meta_cache_key_not_null",
"Migration20200101040300_a_booked_night_finally_took_the_seat_a_new",
"Migration20200101040400_immich_learns_the_switch_synology_airtrail_and",
"Migration20200101040500_a_place_that_moves_takes_its_atlas",
"Migration20200101040600_web_push_one_row_per_browser_a",
"Migration20200101040700_the_2527_trigger_once_more_for_an",
"Migration20200101040800_a_stop_kept_on_the_day_but",
"Migration20200101040900_how_many_of_an_item_are_packed",
"Migration20200101041000_a_bucket_list_wish_for_one_state",
"Migration20200101041100_half_company_holidays_0_5_covers_the",
"Migration20200101041200_a_journey_entry_still_being_written",
"Migration20200101041300_two_narrower_ways_to_share_a_trip",
"Migration20200101041400_a_note_on_a_settle_up_payment",
"Migration20200101041500_google_api_calls_per_utc_day",
"Migration20200101041600_packing_templates_remember_what_an_item_weighs",
"Migration20200101041700_a_journey_s_state_as_its_owner",
"Migration20200101041800_a_place_s_e_mail_and_its",
"Migration20200101041900_a_journey_that_puts_an_entry_on",
"Migration20200101042000_tours",
"Migration20200101042100_a_trip_reminder_remembers_it_was_sent",
"Migration20200101042200_an_index_on_every_foreign_key",
"Migration20200101042300_every_tour_type_the_contract_names",
"Migration20200101042400_one_account_per_email_whatever_its_case",
"Migration20200101042500_a_cron_tick_runs_in_one_process",
"Migration20200101042600_a_session_row_per_sign_in",
"Migration20200101042700_timestamps_stored_in_one_spelling",
"Migration20200101042800_an_email_the_account_typed_in_itself",
"Migration20200101042900_tour_planned_total_duration",
"Migration20200101043000_tour_break_additional_duration",
"Migration20200101043100_an_imported_tour_has_no_hiking_difficulty",
"Migration20200101043200_via_ferrata_tiles_outlive_a_restart",
"Migration20200101043300_a_tour_leg_can_follow_a_via_ferrata",
"Migration20200101043400_wanderer_connection_and_tour_sources",
"Migration20200101043500_wanderer_difficulty_on_the_sac_scale",
"Migration20200101043600_a_tour_remembers_the_import_it_was_derived_from",
"Migration20200101043700_an_import_planned_over_keeps_its_recorded_track",
"Migration20200101043800_a_tour_records_where_it_came_from",
"Migration20200101043900_a_tour_can_be_paddled",
"Migration20200101044000_a_paddle_tour_plans_its_portages_and_locks",
"Migration20200101044100_paddle_obstacles_from_openstreetmap",
"Migration20200101044200_a_paddle_tour_records_its_obstacle_decisions",
"Migration20200101044300_a_trip_links_a_journal",
"Migration20200101044400_a_paddle_region_builds_its_water_network",
"Migration20200101044500_a_tour_waypoint_can_shape_the_route",
"Migration20200101044600_a_paddle_tour_remembers_how_it_crosses_lakes",
"Migration20200101044700_paddle_water_data_loads_where_a_paddler_plans",
"Migration20200101044800_a_tour_counts_its_revisions",
"Migration20200101044900_a_tour_waypoint_can_be_a_place_of_the_trip",
"Migration20200101045000_a_hike_keeps_its_routing_preferences",
"Migration20200101045100_a_tour_remembers_the_trip_it_was_taken_from",
"Migration20200101045200_a_tour_can_be_ridden",
"Migration20200101045300_a_tour_can_be_a_city_walk",
"Migration20200101045400_a_tour_waypoint_remembers_the_kind_of_place_it_was_found_as",
"Migration20200101045500_a_hike_can_be_marked_as_a_winter_activity",
"Migration20200101045510_a_tour_can_be_a_run",
"Migration20200101045520_a_tour_can_be_a_ski_track",
"Migration20200101045600_a_tour_can_be_ridden_on_horseback",
"Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal",
"Migration20200101045710_a_saved_tour_change_can_be_taken_back",
"Migration20200101045900_a_tour_keeps_the_track_it_was_done_with",
"Migration20200101045910_a_tour_can_be_left_out_of_ones_activities",
"Migration20200101046000_a_tour_waypoint_can_end_a_stage",
"Migration20200101046010_a_day_can_hold_one_stage_of_a_tour",
"Migration20200101046100_a_collection_keeps_whole_tours",
"Migration20200101046110_a_tour_points_at_its_packing_list",
"Migration20200101046120_a_wanderer_connection_can_watch_its_sources",
"Migration20200101046130_snowshoeing_and_winter_hiking_are_ski_disciplines",
"Migration20200101046140_tours_are_on_for_every_install",
"Migration20200101046150_a_ski_tour_keeps_its_piste_router_options",
"Migration20200101046160_a_journey_keeps_its_recorded_days",
"Migration20200101046170_a_journey_entry_remembers_the_stays_it_came_from",
"Migration20200101046180_journeys_can_prepare_recorded_days",
"Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings",
"Migration20200101046200_a_tour_draft_lives_on_the_account",
"Migration20200101046200_a_user_can_connect_an_ai_provider",
"Migration20200101046210_the_trip_assistant_remembers_its_conversations",
"Migration20200101046220_a_chat_message_can_say_it_came_from_the_assistant",
"Migration20200101046230_an_admin_can_share_a_chatgpt_plan",
"Migration20200101046240_a_photo_keeps_its_quality_signals",
"Migration20200101046250_an_assistant_conversation_can_be_about_a_journey",
"Migration20200101046260_a_book_keeps_its_last_revisions",
"Migration20200101046270_a_photo_knows_its_colours_and_calm_areas",
"Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip",
"Migration20200101046290_a_removed_member_cannot_rejoin_by_invite_link",
"Migration20200101046300_an_attached_file_stays_with_its_conversation",
"Migration20200101046310_an_admin_can_run_a_plugin_outside_its_trek_range",
"Migration20200101046320_a_place_knows_where_its_details_came_from",
"Migration20200101046330_an_object_no_row_names_is_marked_before_it_goes",
"Migration20200101046340_a_released_object_outlasts_every_undo_before_it_goes"
]
}
+825
View File
@@ -0,0 +1,825 @@
-- The schema a fresh Postgres database starts from. Generated by `npm run gen:pg-baseline`; do not edit.
CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
create table "addons" ("id" text null, "name" text not null, "description" text null, "type" text not null default 'global', "icon" text null default 'Puzzle', "enabled" boolean null default false, "config" jsonb null default '{}', "sort_order" bigint null default 0, primary key ("id"));
create table "app_settings" ("key" text null, "value" text null, primary key ("key"));
create table "document_providers" ("id" text null, "name" text not null, "description" text null, "icon" text null default 'FileText', "enabled" bigint null default 0, "sort_order" bigint null default 0, primary key ("id"));
create table "document_provider_fields" ("id" bigserial primary key, "provider_id" text not null, "field_key" text not null, "label" text not null, "input_type" text not null default 'text', "placeholder" text null, "hint" text null, "required" bigint null default 0, "secret" bigint null default 0, "sort_order" bigint null default 0);
alter table "document_provider_fields" add constraint "document_provider_fields_provider_id_field_key_unique" unique ("provider_id", "field_key");
create table "ferrata_tiles" ("tile_key" text not null, "payload" text not null, "fetched_at" bigint not null, primary key ("tile_key"));
create table "google_api_usage" ("day" text null, "calls" bigint not null default 0, primary key ("day"));
create table "google_place_photo_meta" ("place_id" text null, "attribution" text null, "fetched_at" bigint not null, "error_at" bigint null, primary key ("place_id"));
create table "migrations" ("id" bigserial primary key, "timestamp" bigint not null, "name" varchar(255) not null);
create table "paddle_region_requests" ("region_id" text not null, "name" text not null, "reason" text not null, "bytes" bigint null, "requested_by" text null, "requested_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "declined_at" text null, primary key ("region_id"));
alter table "paddle_region_requests" add constraint "paddle_region_requests_reason_check" check ("reason" in ('ask', 'too_large', 'limit'));
create table "paddle_regions" ("id" text not null, "name" text not null, "boundary" text null, "min_lat" double precision null, "min_lng" double precision null, "max_lat" double precision null, "max_lng" double precision null, "status" text not null default 'queued', "source_timestamp" text null, "imported_at" text null, "feature_count" bigint not null default 0, "error" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "origin" text not null default 'admin', primary key ("id"));
alter table "paddle_regions" add constraint "paddle_regions_status_check" check ("status" in ('queued', 'importing', 'ready', 'failed'));
alter table "paddle_regions" add constraint "paddle_regions_origin_check" check ("origin" in ('admin', 'auto'));
create table "paddle_features" ("id" bigserial primary key, "region_id" text not null, "osm_ref" text not null, "kind" text not null, "group_key" text null, "name" text null, "geometry" text not null, "tags" text not null, "tag_hash" text not null, "min_lat" double precision not null, "min_lng" double precision not null, "max_lat" double precision not null, "max_lng" double precision not null);
create index "idx_paddle_features_box" on "paddle_features" ("min_lat", "max_lat", "min_lng", "max_lng");
alter table "paddle_features" add constraint "idx_paddle_features_region_ref" unique ("region_id", "osm_ref");
create table "paddle_water_graphs" ("region_id" text null, "file" text not null, "rev" text not null, "bytes" bigint not null, "built_at" text not null, "stats" text not null, "min_lat" double precision not null, "min_lng" double precision not null, "max_lat" double precision not null, "max_lng" double precision not null, primary key ("region_id"));
create index "idx_paddle_water_graphs_box" on "paddle_water_graphs" ("min_lat", "max_lat", "min_lng", "max_lng");
alter table "paddle_water_graphs" add constraint "paddle_water_graphs_region_id_unique" unique ("region_id");
create table "photo_providers" ("id" text null, "name" text not null, "description" text null, "icon" text null default 'Image', "enabled" bigint null default 0, "sort_order" bigint null default 0, primary key ("id"));
create table "photo_provider_fields" ("id" bigserial primary key, "provider_id" text not null, "field_key" text not null, "label" text not null, "input_type" text not null default 'text', "placeholder" text null, "hint" text null, "required" bigint null default 0, "secret" bigint null default 0, "settings_key" text null, "payload_key" text null, "sort_order" bigint null default 0);
alter table "photo_provider_fields" add constraint "photo_provider_fields_provider_id_field_key_unique" unique ("provider_id", "field_key");
create table "place_contrib_log" ("id" bigserial primary key, "day" text not null, "contrib_key" text not null, "place_name" text not null, "field" text not null, "value_summary" text null, "result" text not null, "reason" text null);
create index "idx_place_contrib_log_day" on "place_contrib_log" ("day");
create table "place_details_cache" ("place_id" text not null, "lang" text not null default '', "expanded" bigint not null default 0, "payload_json" text not null, "fetched_at" bigint not null, primary key ("place_id", "lang", "expanded"));
create table "place_shadow_picks" ("id" bigserial primary key, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "query" text not null, "lang" text null, "bias_lat" double precision null, "bias_lng" double precision null, "source" text not null, "live_rank" bigint not null, "live_count" bigint not null, "picked_name" text not null, "picked_lat" double precision not null, "picked_lng" double precision not null, "picked_place_id" text null);
create index "idx_place_shadow_created" on "place_shadow_picks" ("created_at");
create table "plugin_actions" ("plugin_id" text not null, "action_key" text not null, "label" text not null, "hint" text null, "danger" bigint not null default 0, "sort_order" bigint not null default 0, "scope" text not null default 'user', primary key ("plugin_id", "action_key"));
create table "plugin_capability_audit" ("id" bigserial primary key, "plugin_id" text not null, "acting_user_id" bigint null, "method" text not null, "resource" text null, "code" text not null, "ts" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "prev_hash" text null, "hash" text not null);
create index "idx_plugin_audit_plugin" on "plugin_capability_audit" ("plugin_id", "id");
create table "plugin_egress_hosts" ("id" bigserial primary key, "plugin_id" text not null, "host" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_plugin_egress_hosts_plugin" on "plugin_egress_hosts" ("plugin_id");
alter table "plugin_egress_hosts" add constraint "plugin_egress_hosts_plugin_id_host_unique" unique ("plugin_id", "host");
create table "plugin_entity_metadata" ("id" bigserial primary key, "plugin_id" text not null, "entity_type" text not null, "entity_id" bigint not null, "key" text not null, "value" text null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_plugin_meta_entity" on "plugin_entity_metadata" ("plugin_id", "entity_type", "entity_id");
alter table "plugin_entity_metadata" add constraint "plugin_entity_metadata_plugin_id_entity_type_enti_ee00f_unique" unique ("plugin_id", "entity_type", "entity_id", "key");
create table "plugin_error_log" ("id" bigserial primary key, "plugin_id" text not null, "ts" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "level" text not null default 'error', "message" text null, "stack" text null);
create index "idx_plugin_error_log_plugin" on "plugin_error_log" ("plugin_id", "ts");
create table "plugin_meta_migrations" ("plugin_id" text not null, "migration_id" text not null, "applied_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("plugin_id", "migration_id"));
create table "plugin_oauth_state" ("state" text null, "plugin_id" text not null, "user_id" bigint not null, "verifier" text not null, "created_at" bigint not null, primary key ("state"));
create table "plugin_oauth_tokens" ("plugin_id" text not null, "user_id" bigint not null, "access_token" text null, "refresh_token" text null, "expires_at" bigint null, "scope" text null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("plugin_id", "user_id"));
create table "plugins" ("id" text null, "name" text not null, "description" text null, "type" text not null default 'integration', "icon" text null default 'Blocks', "version" text null, "api_version" bigint null default 1, "min_trek_version" text null, "permissions" text null default '[]', "granted_permissions" text null default '[]', "status" text not null default 'inactive', "config" text null default '{}', "source_repo" text null, "source_commit" text null, "sha256" text null, "crash_count" bigint not null default 0, "last_error" text null, "reviewed_at" text null, "sort_order" bigint not null default 0, "installed_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "enabled" bigint not null default 0, "capabilities" text not null default '{}', "author_pubkey" text null, "dependencies" text not null default '{}', "operator_egress" bigint not null default 0, "update_block_code" text null, "update_block_detail" text null, "update_block_version" text null, "trek_range" text null, "update_hold" bigint not null default 0, "trek_range_accepted_version" text null, "trek_range_accepted_host" text null, primary key ("id"));
create table "plugin_scheduled_tasks" ("id" bigserial primary key, "plugin_id" text not null, "name" text not null, "due_at" bigint not null, "payload" text not null default 'null', "every_ms" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_plugin_sched_due" on "plugin_scheduled_tasks" ("due_at");
alter table "plugin_scheduled_tasks" add constraint "plugin_scheduled_tasks_plugin_id_name_unique" unique ("plugin_id", "name");
create table "plugin_settings_fields" ("id" bigserial primary key, "plugin_id" text not null, "field_key" text not null, "label" text null, "input_type" text not null default 'text', "placeholder" text null, "hint" text null, "required" bigint not null default 0, "secret" bigint not null default 0, "scope" text not null default 'instance', "options" text null, "oauth_config" text null, "sort_order" bigint not null default 0, "default_value" text null);
alter table "plugin_settings_fields" add constraint "plugin_settings_fields_plugin_id_field_key_unique" unique ("plugin_id", "field_key");
create table "plugin_user_config" ("plugin_id" text not null, "user_id" bigint not null, "config" text not null default '{}', "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("plugin_id", "user_id"));
create table "plugin_user_erasure_queue" ("id" bigserial primary key, "plugin_id" text not null, "user_id" bigint not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_plugin_erasure_plugin" on "plugin_user_erasure_queue" ("plugin_id");
alter table "plugin_user_erasure_queue" add constraint "plugin_user_erasure_queue_plugin_id_user_id_unique" unique ("plugin_id", "user_id");
create table "route_usage_daily" ("day" text not null, "profile" text not null, "surface" text not null, "self_hosted" bigint not null, "requests" bigint not null default 0, "waypoints" bigint not null default 0, "km" double precision not null default 0, "failed" bigint not null default 0, primary key ("day", "profile", "surface", "self_hosted"));
create index "idx_route_usage_day" on "route_usage_daily" ("day");
create table "scheduler_leases" ("name" text not null, "owner" text not null, "expires_at" bigint not null, primary key ("name"));
create table "schema_version" ("id" bigserial primary key, "version" bigint not null);
create table "school_holiday_countries" ("code" text null, "name" text not null, primary key ("code"));
create table "school_holiday_regions" ("id" bigserial primary key, "name" text collate "nocase" not null, "revision" bigint not null default 1, "country" text not null);
alter table "school_holiday_regions" add constraint "school_holiday_regions_country_name_unique" unique ("country", "name");
create table "school_holiday_periods" ("id" bigserial primary key, "region_id" bigint not null, "name" text not null, "start_date" text not null, "end_date" text not null);
create index "idx_school_holiday_periods_region" on "school_holiday_periods" ("region_id");
alter table "school_holiday_periods" add constraint "school_holiday_periods_end_date_check" check (end_date >= start_date);
create table "storage_reclaim_marks" ("category" text not null, "key" text not null, "first_seen_at" text not null, "size" bigint not null, primary key ("category", "key"));
create table "storage_release_queue" ("category" text not null, "key" text not null, "due_at" text not null, primary key ("category", "key"));
create table "tour_types" ("key" text null, "label_key" text not null, "icon" text not null, "color" text not null, "routing_profile" text null, "is_sport" bigint not null default 1, "enabled" bigint not null default 1, "sort_order" bigint not null default 0, primary key ("key"));
create table "trek_photo_cache_meta" ("cache_key" text not null, "content_type" text not null default 'image/jpeg', "fetched_at" bigint not null, primary key ("cache_key"));
create index "idx_trek_photo_cache_meta_fetched_at" on "trek_photo_cache_meta" ("fetched_at");
create table "users" ("id" bigserial primary key, "username" text not null, "email" text not null, "password_hash" text not null, "role" text not null default 'user', "maps_api_key" text null, "unsplash_api_key" text null, "amap_api_key" text null, "openweather_api_key" text null, "avatar" text null, "oidc_sub" text null, "oidc_issuer" text null, "last_login" text null, "mfa_enabled" bigint null default 0, "mfa_secret" text null, "mfa_backup_codes" text null, "immich_url" text null, "immich_access_token" text null, "synology_url" text null, "synology_username" text null, "synology_password" text null, "synology_sid" text null, "must_change_password" bigint null default 0, "password_version" bigint not null default 0, "feed_token" text null, "is_guest" bigint not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "immich_api_key" text null, "synology_skip_ssl" bigint not null default 0, "synology_did" text null, "first_seen_version" text not null default '0.0.0', "login_count" bigint not null default 0, "immich_auto_upload" bigint not null default 0, "airtrail_url" text null, "airtrail_api_key" text null, "airtrail_allow_insecure_tls" bigint null default 0, "airtrail_write_enabled" bigint null default 0, "display_name" text null, "immich_allow_insecure_tls" bigint not null default 0, "email_self_asserted" bigint not null default 0);
create index "idx_users_email" on "users" ("email");
create unique index "idx_users_feed_token" on "users" ("feed_token") where feed_token IS NOT NULL;
alter table "users" add constraint "users_email_unique" unique ("email");
alter table "users" add constraint "users_username_unique" unique ("username");
CREATE UNIQUE INDEX idx_users_email_lower ON users (lower(email));
create table "user_notice_dismissals" ("user_id" bigint not null, "notice_id" text not null, "dismissed_at" bigint not null, "dismissed_app_version" text null, primary key ("user_id", "notice_id"));
alter table "user_notice_dismissals" add constraint "user_notice_dismissals_user_id_notice_id_unique" unique ("user_id", "notice_id");
create table "trips" ("id" bigserial primary key, "user_id" bigint not null, "title" text not null, "description" text null, "start_date" text null, "end_date" text null, "currency" text null default 'EUR', "cover_image" text null, "is_archived" bigint null default 0, "reminder_days" bigint null default 3, "feed_token" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "reminder_sent_for" text null);
create index "idx_trips_user_id" on "trips" ("user_id");
create index "idx_trips_created_at" on "trips" ("created_at");
create unique index "idx_trips_feed_token" on "trips" ("feed_token") where feed_token IS NOT NULL;
create table "roadtrip_preferences" ("trip_id" bigint not null, "key" text not null, "value" text not null, primary key ("trip_id", "key"));
alter table "roadtrip_preferences" add constraint "roadtrip_preferences_trip_id_key_unique" unique ("trip_id", "key");
create table "days" ("id" bigserial primary key, "trip_id" bigint not null, "day_number" bigint not null, "date" text null, "notes" text null, "title" text null, "default_transport_mode" text null);
create index "idx_days_trip_id" on "days" ("trip_id");
alter table "days" add constraint "days_trip_id_day_number_unique" unique ("trip_id", "day_number");
create table "roadtrip_vias" ("id" bigserial primary key, "day_id" bigint not null, "after_order_index" bigint not null, "sequence" bigint not null default 0, "lat" double precision not null, "lng" double precision not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_roadtrip_vias_day" on "roadtrip_vias" ("day_id", "after_order_index", "sequence");
create table "day_notes" ("id" bigserial primary key, "day_id" bigint not null, "trip_id" bigint not null, "text" text not null, "time" text null, "icon" text null default '📝', "sort_order" double precision null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "color" text null);
create index "idx_day_notes_day_id" on "day_notes" ("day_id");
create index "idx_day_notes_trip_id" on "day_notes" ("trip_id");
create table "budget_category_order" ("trip_id" bigint not null, "category" text not null, "sort_order" bigint not null default 0, primary key ("trip_id", "category"));
alter table "budget_category_order" add constraint "budget_category_order_trip_id_category_unique" unique ("trip_id", "category");
create table "trip_members" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "added_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "invited_by" bigint null);
create index "idx_trip_members_trip_id" on "trip_members" ("trip_id");
create index "idx_trip_members_user_id" on "trip_members" ("user_id");
create index "idx_trip_members_invited_by" on "trip_members" ("invited_by");
alter table "trip_members" add constraint "trip_members_trip_id_user_id_unique" unique ("trip_id", "user_id");
create table "trip_member_removals" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "removed_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_trip_member_removals_user" on "trip_member_removals" ("user_id");
alter table "trip_member_removals" add constraint "trip_member_removals_trip_id_user_id_unique" unique ("trip_id", "user_id");
create table "trip_invite_tokens" ("id" bigserial primary key, "trip_id" bigint not null, "token" text not null, "expires_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by" bigint null);
create index "idx_trip_invite_tokens_token" on "trip_invite_tokens" ("token");
create index "idx_trip_invite_tokens_created_by" on "trip_invite_tokens" ("created_by");
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_token_unique" unique ("token");
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_trip_id_unique" unique ("trip_id");
create table "trip_album_links" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "provider" text not null, "album_id" text not null, "album_name" text not null default '', "sync_enabled" bigint not null default 1, "last_synced_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "passphrase" text null default NULL);
create index "idx_trip_album_links_trip" on "trip_album_links" ("trip_id");
create index "idx_trip_album_links_user_id" on "trip_album_links" ("user_id");
alter table "trip_album_links" add constraint "trip_album_links_trip_id_user_id_provider_album_id_unique" unique ("trip_id", "user_id", "provider", "album_id");
create table "trek_photos" ("id" bigserial primary key, "provider" text not null, "asset_id" text null, "owner_id" bigint null, "file_path" text null, "thumbnail_path" text null, "width" bigint null, "height" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "passphrase" text null default NULL, "media_type" text not null default 'image', "duration_ms" bigint null, "taken_at" text null, "lat" double precision null, "lng" double precision null);
create index "idx_trek_photos_owner" on "trek_photos" ("owner_id");
create index "idx_trek_photos_geo" on "trek_photos" ("lat", "lng") where lat IS NOT NULL AND lng IS NOT NULL;
create unique index "idx_trek_photos_provider_asset" on "trek_photos" ("provider", "asset_id", "owner_id") where asset_id IS NOT NULL;
create table "trip_photos" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "photo_id" bigint not null, "shared" bigint not null default 1, "album_link_id" bigint null, "added_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_trip_photos_trip" on "trip_photos" ("trip_id");
create index "idx_trip_photos_user_id" on "trip_photos" ("user_id");
create index "idx_trip_photos_photo" on "trip_photos" ("photo_id");
create index "idx_trip_photos_album_link_id" on "trip_photos" ("album_link_id");
alter table "trip_photos" add constraint "trip_photos_trip_id_user_id_photo_id_unique" unique ("trip_id", "user_id", "photo_id");
create table "trek_photo_signals" ("id" bigserial primary key, "photo_id" bigint not null, "algo" bigint not null, "phash" text null, "sharpness" double precision null, "luma" double precision null, "clipped" double precision null, "orig_width" bigint null, "orig_height" bigint null, "computed_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "palette" text null, "busy" text null, "sal_x" double precision null, "sal_y" double precision null);
alter table "trek_photo_signals" add constraint "trek_photo_signals_photo_id_unique" unique ("photo_id");
create table "tour_drafts" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "payload" text not null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_tour_drafts_user" on "tour_drafts" ("user_id");
alter table "tour_drafts" add constraint "tour_drafts_trip_id_user_id_unique" unique ("trip_id", "user_id");
create table "todo_items" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "checked" bigint null default 0, "category" text null, "sort_order" bigint null default 0, "due_date" text null, "description" text null, "assigned_user_id" bigint null, "priority" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "reminded_at" text null);
create index "idx_todo_items_trip_id" on "todo_items" ("trip_id");
create index "idx_todo_items_assigned_user_id" on "todo_items" ("assigned_user_id");
create table "todo_category_assignees" ("id" bigserial primary key, "trip_id" bigint not null, "category_name" text not null, "user_id" bigint not null);
create index "idx_todo_category_assignees_user_id" on "todo_category_assignees" ("user_id");
alter table "todo_category_assignees" add constraint "todo_category_assignees_trip_id_category_name_user_id_unique" unique ("trip_id", "category_name", "user_id");
create table "tags" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "color" text null default '#10b981', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_tags_user_id" on "tags" ("user_id");
create table "share_tokens" ("id" bigserial primary key, "trip_id" bigint not null, "token" text not null, "share_map" bigint null default 1, "share_bookings" bigint null default 1, "share_packing" bigint null default 0, "share_budget" bigint null default 0, "share_collab" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "expires_at" text null, "share_travel_only" bigint not null default 0, "share_hide_images" bigint not null default 0, "created_by" bigint not null);
create index "idx_share_tokens_trip_id" on "share_tokens" ("trip_id");
create index "idx_share_tokens_token" on "share_tokens" ("token");
create index "idx_share_tokens_created_by" on "share_tokens" ("created_by");
alter table "share_tokens" add constraint "share_tokens_token_unique" unique ("token");
create table "settings" ("id" bigserial primary key, "user_id" bigint not null, "key" text not null, "value" text null);
alter table "settings" add constraint "settings_user_id_key_unique" unique ("user_id", "key");
create table "push_subscriptions" ("id" bigserial primary key, "user_id" bigint not null, "endpoint" text not null, "p256dh" text not null, "auth" text not null, "vapid_public_key" text not null, "user_agent" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_success_at" text null, "failure_count" bigint not null default 0);
create index "idx_push_subscriptions_user" on "push_subscriptions" ("user_id");
alter table "push_subscriptions" add constraint "push_subscriptions_endpoint_unique" unique ("endpoint");
create table "password_reset_tokens" ("id" bigserial primary key, "user_id" bigint not null, "token_hash" text not null, "expires_at" text not null, "consumed_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_ip" text null);
create index "idx_prt_user" on "password_reset_tokens" ("user_id");
create index "idx_prt_hash" on "password_reset_tokens" ("token_hash");
alter table "password_reset_tokens" add constraint "password_reset_tokens_token_hash_unique" unique ("token_hash");
create table "packing_templates" ("id" bigserial primary key, "name" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by" bigint not null);
create index "idx_packing_templates_created_by" on "packing_templates" ("created_by");
create table "packing_template_categories" ("id" bigserial primary key, "template_id" bigint not null, "name" text not null, "sort_order" bigint not null default 0);
create index "idx_packing_template_categories_template_id" on "packing_template_categories" ("template_id");
create table "packing_template_items" ("id" bigserial primary key, "category_id" bigint not null, "name" text not null, "sort_order" bigint not null default 0, "weight_grams" bigint null, "quantity" bigint not null default 1, "bag_name" text null);
create index "idx_packing_template_items_category_id" on "packing_template_items" ("category_id");
create table "packing_category_assignees" ("id" bigserial primary key, "trip_id" bigint not null, "category_name" text not null, "user_id" bigint not null);
create index "idx_packing_category_assignees_user_id" on "packing_category_assignees" ("user_id");
alter table "packing_category_assignees" add constraint "packing_category_assignees_trip_id_category_name_user_id_unique" unique ("trip_id", "category_name", "user_id");
create table "packing_bags" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "color" text not null default '#6366f1', "weight_limit_grams" bigint null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "user_id" bigint null default NULL);
create index "idx_packing_bags_trip_id" on "packing_bags" ("trip_id");
create index "idx_packing_bags_user_id" on "packing_bags" ("user_id");
create table "packing_items" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "checked" bigint null default 0, "category" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "weight_grams" bigint null, "bag_id" bigint null, "quantity" bigint not null default 1, "updated_at" text null, "is_private" bigint not null default 0, "owner_id" bigint null, "packed_quantity" bigint null);
create index "idx_packing_items_trip_id" on "packing_items" ("trip_id");
create index "idx_packing_items_bag_id" on "packing_items" ("bag_id");
create index "idx_packing_items_owner_id" on "packing_items" ("owner_id");
create table "packing_item_contributors" ("item_id" bigint not null, "user_id" bigint not null, "status" text not null default 'accepted', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("item_id", "user_id"));
create index "idx_packing_item_contributors_user_id" on "packing_item_contributors" ("user_id");
alter table "packing_item_contributors" add constraint "packing_item_contributors_item_id_user_id_unique" unique ("item_id", "user_id");
create table "packing_item_recipients" ("item_id" bigint not null, "user_id" bigint not null, primary key ("item_id", "user_id"));
create table "packing_bag_members" ("bag_id" bigint not null, "user_id" bigint not null, primary key ("bag_id", "user_id"));
create table "oauth_clients" ("id" text null, "user_id" bigint null, "name" text not null, "client_id" text not null, "client_secret_hash" text not null, "redirect_uris" text not null default '[]', "allowed_scopes" text not null default '[]', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "is_public" bigint not null default 0, "created_via" text not null default 'settings_ui', "allows_client_credentials" bigint not null default 0, primary key ("id"));
create index "idx_oauth_clients_user" on "oauth_clients" ("user_id");
alter table "oauth_clients" add constraint "idx_oauth_clients_client_id" unique ("client_id");
alter table "oauth_clients" add constraint "oauth_clients_client_id_unique" unique ("client_id");
create table "oauth_tokens" ("id" bigserial primary key, "client_id" text not null, "user_id" bigint not null, "access_token_hash" text not null, "refresh_token_hash" text not null, "scopes" text not null default '[]', "access_token_expires_at" text not null, "refresh_token_expires_at" text not null, "revoked_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "parent_token_id" bigint null, "audience" text null);
create index "idx_oauth_tokens_client_id" on "oauth_tokens" ("client_id");
create index "idx_oauth_tokens_user" on "oauth_tokens" ("user_id");
alter table "oauth_tokens" add constraint "idx_oauth_tokens_access" unique ("access_token_hash");
alter table "oauth_tokens" add constraint "idx_oauth_tokens_refresh" unique ("refresh_token_hash");
create index "idx_oauth_tokens_parent" on "oauth_tokens" ("parent_token_id");
alter table "oauth_tokens" add constraint "oauth_tokens_refresh_token_hash_unique" unique ("refresh_token_hash");
alter table "oauth_tokens" add constraint "oauth_tokens_access_token_hash_unique" unique ("access_token_hash");
create table "oauth_consents" ("id" bigserial primary key, "client_id" text not null, "user_id" bigint not null, "scopes" text not null default '[]', "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_oauth_consents_user_id" on "oauth_consents" ("user_id");
alter table "oauth_consents" add constraint "oauth_consents_client_id_user_id_unique" unique ("client_id", "user_id");
create table "notifications" ("id" bigserial primary key, "type" text not null, "scope" text not null, "target" bigint not null, "sender_id" bigint null, "recipient_id" bigint not null, "title_key" text not null, "title_params" text null default '{}', "text_key" text not null, "text_params" text null default '{}', "positive_text_key" text null, "negative_text_key" text null, "positive_callback" text null, "negative_callback" text null, "response" text null, "navigate_text_key" text null, "navigate_target" text null, "is_read" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_notifications_sender_id" on "notifications" ("sender_id");
create index "idx_notifications_target_scope" on "notifications" ("target", "scope");
create index "idx_notifications_recipient_created" on "notifications" ("recipient_id", "created_at");
create index "idx_notifications_recipient" on "notifications" ("recipient_id", "is_read", "created_at");
create table "notification_channel_preferences" ("user_id" bigint not null, "event_type" text not null, "channel" text not null, "enabled" bigint not null default 1, primary key ("user_id", "event_type", "channel"));
create index "idx_ncp_user" on "notification_channel_preferences" ("user_id");
alter table "notification_channel_preferences" add constraint "notification_channel_preferences_user_id_event_ty_8d673_unique" unique ("user_id", "event_type", "channel");
create table "mcp_tokens" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "token_hash" text not null, "token_prefix" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_used_at" text null, "kind" text not null default 'mcp', "scope_mode" text not null default 'all', "api_scopes" text null);
create index "idx_mcp_tokens_user_id" on "mcp_tokens" ("user_id");
alter table "mcp_tokens" add constraint "idx_mcp_tokens_hash" unique ("token_hash");
create table "journeys" ("id" bigserial primary key, "user_id" bigint not null, "title" text not null, "subtitle" text null, "cover_gradient" text null, "status" text null default 'draft', "created_at" bigint not null, "updated_at" bigint not null, "cover_image" text null, "show_trip_tracks" bigint not null default 0, "show_verdict" bigint not null default 1, "show_mood" bigint not null default 1, "show_weather" bigint not null default 1, "status_override" text null, "photo_location" bigint not null default 0, "auto_prepare_recordings" bigint not null default 0);
create index "idx_journeys_user" on "journeys" ("user_id");
create table "trip_journal_links" ("id" bigserial primary key, "trip_id" bigint not null, "journey_id" bigint not null, "created_at" bigint not null, "linked_by" bigint null);
create index "idx_trip_journal_links_journey" on "trip_journal_links" ("journey_id");
create index "idx_trip_journal_links_linked_by" on "trip_journal_links" ("linked_by");
alter table "trip_journal_links" add constraint "trip_journal_links_trip_id_unique" unique ("trip_id");
create table "trip_journal_link_members" ("link_id" bigint not null, "user_id" bigint not null, "role" text not null default 'viewer', "hide_skeletons" bigint not null default 0, "added_at" bigint not null, primary key ("link_id", "user_id"));
create index "idx_trip_journal_link_members_user" on "trip_journal_link_members" ("user_id");
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_link_id_user_id_unique" unique ("link_id", "user_id");
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_role_check" check ("role" in ('viewer', 'editor'));
create table "journey_trips" ("journey_id" bigint not null, "trip_id" bigint not null, "added_at" bigint not null, primary key ("journey_id", "trip_id"));
create index "idx_journey_trips_journey" on "journey_trips" ("journey_id");
create index "idx_journey_trips_trip_id" on "journey_trips" ("trip_id");
alter table "journey_trips" add constraint "journey_trips_journey_id_trip_id_unique" unique ("journey_id", "trip_id");
create table "journey_share_tokens" ("id" bigserial primary key, "journey_id" bigint not null, "token" text not null, "share_timeline" bigint null default 1, "share_gallery" bigint null default 1, "share_map" bigint null default 1, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "newest_first" bigint not null default 0, "share_plan" bigint not null default 0, "share_recordings" bigint not null default 0, "created_by" bigint not null);
alter table "journey_share_tokens" add constraint "idx_journey_share_journey" unique ("journey_id");
create index "idx_journey_share_tokens_created_by" on "journey_share_tokens" ("created_by");
alter table "journey_share_tokens" add constraint "journey_share_tokens_token_unique" unique ("token");
create table "journey_photos" ("id" bigserial primary key, "journey_id" bigint not null, "photo_id" bigint not null, "caption" text null, "shared" bigint null default 0, "sort_order" bigint null default 0, "provider" text null, "asset_id" text null, "owner_id" bigint null, "created_at" bigint not null);
create index "idx_journey_photos_journey" on "journey_photos" ("journey_id");
create index "idx_journey_photos_photo_id" on "journey_photos" ("photo_id");
alter table "journey_photos" add constraint "journey_photos_journey_id_photo_id_unique" unique ("journey_id", "photo_id");
create table "journey_book_revisions" ("id" bigserial primary key, "journey_id" bigint not null, "version" bigint not null, "document" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_journey_book_revisions_journey" on "journey_book_revisions" ("journey_id");
create table "journey_recording_prep" ("id" bigserial primary key, "journey_id" bigint not null, "user_id" bigint not null, "last_attempt_at" text null, "last_success_at" text null, "last_error" text null);
create index "idx_journey_recording_prep_user" on "journey_recording_prep" ("user_id");
alter table "journey_recording_prep" add constraint "idx_journey_recording_prep_person" unique ("journey_id", "user_id");
create table "journey_recorded_days" ("id" bigserial primary key, "journey_id" bigint not null, "local_date" text not null, "source" text not null default 'dawarich', "source_kind" text not null, "utc_offset_minutes" bigint not null, "window_from" text not null, "window_to" text not null, "segments" text not null, "point_count" bigint not null, "distance_m" double precision null, "content_hash" text not null, "truncated" bigint not null default 0, "fetched_at" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "imported_by" bigint null);
create index "idx_journey_recorded_days_imported_by" on "journey_recorded_days" ("imported_by");
alter table "journey_recorded_days" add constraint "idx_journey_recorded_days_day" unique ("journey_id", "local_date", "source");
create table "journey_contributors" ("journey_id" bigint not null, "user_id" bigint not null, "role" text not null, "added_at" bigint not null, "hide_skeletons" bigint not null default 0, primary key ("journey_id", "user_id"));
create index "idx_journey_contributors_user" on "journey_contributors" ("user_id");
alter table "journey_contributors" add constraint "journey_contributors_journey_id_user_id_unique" unique ("journey_id", "user_id");
create table "journey_books" ("id" bigserial primary key, "journey_id" bigint not null, "title" text not null default '', "document" text not null, "version" bigint not null default 1, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_by" bigint null, "created_by" bigint null);
create index "idx_journey_books_journey" on "journey_books" ("journey_id");
create index "idx_journey_books_updated_by" on "journey_books" ("updated_by");
create index "idx_journey_books_created_by" on "journey_books" ("created_by");
create table "invite_tokens" ("id" bigserial primary key, "token" text not null, "max_uses" bigint not null default 1, "used_count" bigint not null default 0, "expires_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "trip_id" bigint null, "created_by" bigint not null);
create index "idx_invite_tokens_trip_id" on "invite_tokens" ("trip_id");
create index "idx_invite_tokens_created_by" on "invite_tokens" ("created_by");
alter table "invite_tokens" add constraint "invite_tokens_token_unique" unique ("token");
create table "idempotency_keys" ("key" text not null, "user_id" bigint not null, "method" text not null, "path" text not null, "status_code" bigint not null, "response_body" text not null, "created_at" bigint not null default CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint), primary key ("key", "user_id", "method", "path"));
create index "idx_idempotency_keys_user_id" on "idempotency_keys" ("user_id");
create index "idx_idempotency_keys_created" on "idempotency_keys" ("created_at");
alter table "idempotency_keys" add constraint "idempotency_keys_key_user_id_method_path_unique" unique ("key", "user_id", "method", "path");
create table "hidden_regions" ("id" bigserial primary key, "user_id" bigint not null, "region_code" text not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_hidden_regions_user" on "hidden_regions" ("user_id");
alter table "hidden_regions" add constraint "hidden_regions_user_id_region_code_unique" unique ("user_id", "region_code");
create table "hidden_countries" ("id" bigserial primary key, "user_id" bigint not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_hidden_countries_user" on "hidden_countries" ("user_id");
alter table "hidden_countries" add constraint "hidden_countries_user_id_country_code_unique" unique ("user_id", "country_code");
create table "document_connections" ("id" bigserial primary key, "trip_id" bigint not null, "provider_id" text not null, "owner_user_id" bigint not null, "base_url" text not null, "secrets" text null, "settings" text not null default '{}', "allow_insecure_tls" bigint not null default 0, "capabilities" text null, "last_probe_at" text null, "last_probe_state" text not null default 'never', "last_probe_error" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_document_connections_trip" on "document_connections" ("trip_id");
create index "idx_document_connections_provider_id" on "document_connections" ("provider_id");
create index "idx_document_connections_owner" on "document_connections" ("owner_user_id");
alter table "document_connections" add constraint "document_connections_trip_id_provider_id_unique" unique ("trip_id", "provider_id");
create table "trip_document_links" ("id" bigserial primary key, "trip_id" bigint not null, "connection_id" bigint not null, "provider_id" text not null, "remote_scope_key" text not null, "remote_root_id" text null, "remote_root_path" text null, "remote_label" text not null default '', "direction" text not null default 'both', "delete_policy" text not null default 'unlink', "conflict_policy" text not null default 'manual', "sync_enabled" bigint not null default 1, "webhook_token" text null, "webhook_secret" text null, "webhook_subscription_id" text null, "remote_cursor" text null, "last_sync_at" text null, "last_sync_state" text not null default 'never', "last_sync_error" text null, "failure_count" bigint not null default 0, "next_attempt_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by" bigint null);
create index "idx_trip_document_links_trip" on "trip_document_links" ("trip_id");
create index "idx_trip_document_links_connection_id" on "trip_document_links" ("connection_id");
create index "idx_trip_document_links_created_by" on "trip_document_links" ("created_by");
create index "idx_trip_document_links_due" on "trip_document_links" ("sync_enabled", "next_attempt_at");
create unique index "idx_trip_document_links_token" on "trip_document_links" ("webhook_token") where webhook_token IS NOT NULL;
alter table "trip_document_links" add constraint "trip_document_links_trip_id_connection_id_remote__1c36d_unique" unique ("trip_id", "connection_id", "remote_scope_key");
create table "dawarich_connections" ("user_id" bigint null, "url" text null, "api_key" text null, "allow_insecure_tls" bigint not null default 0, "sync_enabled" bigint not null default 1, "last_sync_at" text null, "last_sync_state" text not null default 'never', "last_sync_error" text null, "capabilities" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("user_id"));
create table "collections" ("id" bigserial primary key, "owner_id" bigint not null, "name" text not null, "description" text null, "color" text null default '#6366f1', "icon" text null default 'Bookmark', "cover_image" text null, "links" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collections_owner_id" on "collections" ("owner_id");
create table "collection_tours" ("id" bigserial primary key, "collection_id" bigint not null, "name" text not null, "description" text null, "website" text null, "route_geometry" text null, "waypoints" text not null, "distance" double precision null, "elevation_gain" double precision null, "elevation_loss" double precision null, "duration" double precision null, "planned_duration_minutes" bigint null, "break_additional_minutes" bigint null, "difficulty" text null, "wanderer_ref" text null, "match_confidence" double precision null, "max_hiking_difficulty" bigint null, "bike_profile" text null, "run_profile" text null, "run_pace_seconds_per_km" bigint null, "ski_discipline" text null, "ski_technique" text null, "boat_type" text null, "water_context" text null, "paddle_speed_kmh" double precision null, "portage_speed_kmh" double precision null, "paddle_lake_style" text null, "track_marks" text null, "hiking_preferences" text null, "origin" text not null, "origin_file_name" text null, "track_started_at" text null, "track_ended_at" text null, "source_trip_title" text not null, "source_tour_name" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "ski_options" text null, "tour_type" text not null, "saved_by" bigint null);
create index "idx_collection_tours_collection" on "collection_tours" ("collection_id");
create index "idx_collection_tours_tour_type" on "collection_tours" ("tour_type");
create index "idx_collection_tours_saved_by" on "collection_tours" ("saved_by");
create table "collection_labels" ("id" bigserial primary key, "collection_id" bigint not null, "name" text not null, "color" text null default '#6366f1', "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collection_labels_collection" on "collection_labels" ("collection_id");
create table "collection_members" ("id" bigserial primary key, "collection_id" bigint not null, "user_id" bigint not null, "status" text not null default 'pending', "role" text not null default 'editor', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collection_members_user" on "collection_members" ("user_id");
alter table "collection_members" add constraint "collection_members_collection_id_user_id_unique" unique ("collection_id", "user_id");
create table "collab_polls" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "question" text not null, "options" text not null, "multiple" bigint null default 0, "closed" bigint null default 0, "deadline" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collab_polls_trip" on "collab_polls" ("trip_id");
create index "idx_collab_polls_user_id" on "collab_polls" ("user_id");
create table "collab_poll_votes" ("id" bigserial primary key, "poll_id" bigint not null, "user_id" bigint not null, "option_index" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collab_poll_votes_user_id" on "collab_poll_votes" ("user_id");
alter table "collab_poll_votes" add constraint "collab_poll_votes_poll_id_user_id_option_index_unique" unique ("poll_id", "user_id", "option_index");
create table "collab_notes" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "category" text null default 'General', "title" text not null, "content" text null, "color" text null default '#6366f1', "pinned" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "website" text null);
create index "idx_collab_notes_trip" on "collab_notes" ("trip_id");
create index "idx_collab_notes_user_id" on "collab_notes" ("user_id");
create table "collab_messages" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "text" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "deleted" bigint null default 0, "origin" text null, "reply_to" bigint null);
create index "idx_collab_messages_trip" on "collab_messages" ("trip_id");
create index "idx_collab_messages_user_id" on "collab_messages" ("user_id");
create index "idx_collab_messages_reply_to" on "collab_messages" ("reply_to");
create table "collab_message_reactions" ("id" bigserial primary key, "message_id" bigint not null, "user_id" bigint not null, "emoji" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collab_reactions_msg" on "collab_message_reactions" ("message_id");
create index "idx_collab_message_reactions_user_id" on "collab_message_reactions" ("user_id");
alter table "collab_message_reactions" add constraint "collab_message_reactions_message_id_user_id_emoji_unique" unique ("message_id", "user_id", "emoji");
create table "collab_links" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "title" text not null, "url" text not null, "pinned" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collab_links_trip" on "collab_links" ("trip_id");
create index "idx_collab_links_user_id" on "collab_links" ("user_id");
create table "categories" ("id" bigserial primary key, "name" text not null, "color" text null default '#6366f1', "icon" text null default '📍', "user_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_categories_user_id" on "categories" ("user_id");
create table "places" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "description" text null, "lat" double precision null, "lng" double precision null, "address" text null, "category_id" bigint null, "price" double precision null, "currency" text null, "reservation_status" text null default 'none', "reservation_notes" text null, "reservation_datetime" text null, "place_time" text null, "end_time" text null, "duration_minutes" bigint null default 60, "notes" text null, "image_url" text null, "google_place_id" text null, "google_ftid" text null, "website" text null, "phone" text null, "transport_mode" text null default 'walking', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "osm_id" text null, "route_geometry" text null, "route_color" text null, "stop_type" text null, "fill_percent" bigint null, "amap_poi_id" text null, "source" text null, "email" text null, "opening_hours" text null);
create index "idx_places_trip_id" on "places" ("trip_id");
create index "idx_places_category_id" on "places" ("category_id");
create table "tours" ("place_id" bigint null, "distance" double precision null, "elevation_gain" double precision null, "elevation_loss" double precision null, "duration" double precision null, "difficulty" text null, "wanderer_ref" text null, "match_confidence" double precision null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "max_hiking_difficulty" bigint null default 2, "planned_duration_minutes" bigint null, "break_additional_minutes" bigint null, "derived_from_place_id" bigint null, "recorded_route_geometry" text null, "origin" text not null default 'trek', "origin_file_name" text null, "boat_type" text null, "water_context" text null, "paddle_speed_kmh" double precision null, "portage_speed_kmh" double precision null, "track_marks" text null, "paddle_lake_style" text null, "revision" bigint not null default 1, "hiking_preferences" text null, "taken_over_from_trip_title" text null, "taken_over_from_tour_name" text null, "bike_profile" text null, "run_profile" text null, "run_pace_seconds_per_km" bigint null, "ski_technique" text null, "track_started_at" text null, "track_ended_at" text null, "ski_discipline" text null, "ski_options" text null, "tour_type" text not null, primary key ("place_id"));
create index "idx_tours_tour_type" on "tours" ("tour_type");
create index "idx_tours_derived_from_place_id" on "tours" ("derived_from_place_id") where derived_from_place_id IS NOT NULL;
alter table "tours" add constraint "tours_run_pace_seconds_per_km_check" check (run_pace_seconds_per_km IS NULL OR (run_pace_seconds_per_km >= 120 AND run_pace_seconds_per_km <= 1200));
alter table "tours" add constraint "tours_revision_check" check (revision >= 1);
alter table "tours" add constraint "tours_origin_check" check ("origin" in ('trek', 'gpx', 'wanderer'));
alter table "tours" add constraint "tours_boat_type_check" check ("boat_type" in ('kayak', 'canoe', 'sup', 'other'));
alter table "tours" add constraint "tours_water_context_check" check ("water_context" in ('river', 'lake'));
alter table "tours" add constraint "tours_paddle_lake_style_check" check ("paddle_lake_style" in ('direct', 'shore'));
alter table "tours" add constraint "tours_bike_profile_check" check ("bike_profile" in ('touring', 'road', 'gravel', 'mtb'));
alter table "tours" add constraint "tours_run_profile_check" check ("run_profile" in ('running', 'trail'));
alter table "tours" add constraint "tours_ski_technique_check" check ("ski_technique" in ('classic', 'skating', 'unknown'));
alter table "tours" add constraint "tours_ski_discipline_check" check ("ski_discipline" in ('alpine', 'snowboard', 'cross_country', 'touring', 'snowshoe', 'winter_hike'));
create table "tour_waypoints" ("id" bigserial primary key, "place_id" bigint not null, "lat" double precision not null, "lng" double precision not null, "role" text not null, "sequence" bigint not null, "fixed_leg" text null, "lock" text null, "shaping" bigint not null default 0, "linked_place_id" bigint null, "station_key" text null, "name" text null, "stay_minutes" bigint null, "importance" text null, "protected" bigint not null default 0, "opening_hours" text null, "poi_category" text null, "stage_end" bigint not null default 0);
create index "idx_tour_waypoints_linked_place" on "tour_waypoints" ("linked_place_id") where linked_place_id IS NOT NULL;
alter table "tour_waypoints" add constraint "tour_waypoints_place_id_sequence_unique" unique ("place_id", "sequence");
alter table "tour_waypoints" add constraint "tour_waypoints_stage_end_check" check (stage_end IN (0, 1));
alter table "tour_waypoints" add constraint "tour_waypoints_protected_check" check (protected IN (0, 1));
alter table "tour_waypoints" add constraint "tour_waypoints_stay_minutes_check" check (stay_minutes IS NULL OR (stay_minutes >= 0 AND stay_minutes <= 1440));
alter table "tour_waypoints" add constraint "tour_waypoints_shaping_check" check (shaping IN (0, 1));
alter table "tour_waypoints" add constraint "tour_waypoints_importance_check" check ("importance" in ('optional', 'must'));
create table "tour_sources" ("place_id" bigint null, "provider" text not null, "instance" text not null, "external_id" text not null, "external_url" text null, "external_updated" text null, "content_hash" text not null, "local_hash" text not null, "imported_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "imported_by" bigint null, primary key ("place_id"));
create index "idx_tour_sources_imported_by" on "tour_sources" ("imported_by");
create index "idx_tour_sources_external" on "tour_sources" ("provider", "instance", "external_id");
create table "tour_source_hints" ("place_id" bigint null, "user_id" bigint not null, "state" text null, "changes" text null, "reason" text null, "external_updated" text null, "seen_hash" text null, "seen_updated" text null, "checked_at" text null, primary key ("place_id"));
create index "idx_tour_source_hints_user_id" on "tour_source_hints" ("user_id");
alter table "tour_source_hints" add constraint "tour_source_hints_state_check" check ("state" in ('possible_change', 'changed', 'unverifiable'));
alter table "tour_source_hints" add constraint "tour_source_hints_reason_check" check ("reason" in ('unavailable', 'no_change_time'));
create table "tour_packing_links" ("place_id" bigint null, "category" text null, "linked_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "linked_by" bigint null, primary key ("place_id"));
create index "idx_tour_packing_links_linked_by" on "tour_packing_links" ("linked_by");
create table "tour_obstacle_reviews" ("place_id" bigint not null, "obstacle_key" text not null, "decision" text not null, "note" text null, "route_fingerprint" text not null, "source_fingerprint" text not null, "obstacle_snapshot" text not null, "decided_at" text not null, "decided_by" bigint null, primary key ("place_id", "obstacle_key"));
alter table "tour_obstacle_reviews" add constraint "tour_obstacle_reviews_place_id_obstacle_key_unique" unique ("place_id", "obstacle_key");
alter table "tour_obstacle_reviews" add constraint "tour_obstacle_reviews_decision_check" check ("decision" in ('pass', 'portage', 'reroute', 'not_affected'));
create table "tour_change_steps" ("id" bigserial primary key, "place_id" bigint not null, "proposal_id" text not null, "base_revision" bigint not null, "revision" bigint not null, "changes" text not null, "before_state" text not null, "saved_by" bigint null, "saved_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "undone_revision" bigint null, "undone_by" bigint null, "undone_at" text null);
alter table "tour_change_steps" add constraint "tour_change_steps_place_id_revision_unique" unique ("place_id", "revision");
alter table "tour_change_steps" add constraint "tour_change_steps_undone_revision_check" check (undone_revision IS NULL OR undone_revision > revision);
alter table "tour_change_steps" add constraint "tour_change_steps_revision_check" check (revision = base_revision + 1);
alter table "tour_change_steps" add constraint "tour_change_steps_base_revision_check" check (base_revision >= 1);
create table "tour_activity_exclusions" ("id" bigserial primary key, "user_id" bigint not null, "place_id" bigint not null, "excluded_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_tour_activity_exclusions_place" on "tour_activity_exclusions" ("place_id");
alter table "tour_activity_exclusions" add constraint "tour_activity_exclusions_user_id_place_id_unique" unique ("user_id", "place_id");
create table "roadtrip_day_tracks" ("day_id" bigint null, "place_id" bigint not null, "stray_km" double precision null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("day_id"));
create index "idx_roadtrip_day_tracks_place" on "roadtrip_day_tracks" ("place_id");
create table "place_regions" ("place_id" bigint null, "country_code" text not null, "region_code" text not null, "region_name" text not null, primary key ("place_id"));
create index "idx_place_regions_country" on "place_regions" ("country_code");
create index "idx_place_regions_region" on "place_regions" ("region_code");
create table "place_ratings" ("id" bigserial primary key, "place_id" bigint not null, "user_id" bigint not null, "rating" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_place_ratings_place" on "place_ratings" ("place_id");
create index "idx_place_ratings_user_id" on "place_ratings" ("user_id");
alter table "place_ratings" add constraint "place_ratings_place_id_user_id_unique" unique ("place_id", "user_id");
create table "place_field_origin" ("place_id" bigint not null, "field" text not null, "origin" text not null, "value_hash" text not null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("place_id", "field"));
alter table "place_field_origin" add constraint "place_field_origin_place_id_field_unique" unique ("place_id", "field");
create table "place_contrib_outbox" ("id" bigserial primary key, "contrib_key" text not null, "field" text not null, "value" text not null, "place_id" bigint not null, "place_name" text not null, "lat" double precision null, "lng" double precision null, "country" text null, "cid" text not null, "attempts" bigint not null default 0, "eligible_at" text not null, "next_attempt_at" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_place_contrib_outbox_place" on "place_contrib_outbox" ("place_id");
create index "idx_place_contrib_outbox_due" on "place_contrib_outbox" ("next_attempt_at");
alter table "place_contrib_outbox" add constraint "place_contrib_outbox_contrib_key_field_unique" unique ("contrib_key", "field");
create table "place_tags" ("place_id" bigint not null, "tag_id" bigint not null, primary key ("place_id", "tag_id"));
create table "photos" ("id" bigserial primary key, "trip_id" bigint not null, "day_id" bigint null, "place_id" bigint null, "filename" text not null, "original_name" text not null, "file_size" bigint null, "mime_type" text null, "caption" text null, "taken_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_photos_trip_id" on "photos" ("trip_id");
create index "idx_photos_day_id" on "photos" ("day_id");
create index "idx_photos_place_id" on "photos" ("place_id");
create table "journey_entries" ("id" bigserial primary key, "journey_id" bigint not null, "source_trip_id" bigint null, "source_place_id" bigint null, "author_id" bigint not null, "type" text not null, "title" text null, "story" text null, "entry_date" text not null, "entry_time" text null, "location_name" text null, "location_lat" double precision null, "location_lng" double precision null, "mood" text null, "weather" text null, "tags" text null, "visibility" text null default 'private', "sort_order" bigint null default 0, "created_at" bigint not null, "updated_at" bigint not null, "pros_cons" text null, "stats_excluded" bigint not null default 0, "dismissed" bigint not null default 0, "country_code" text null, "source_assignment_id" bigint null, "is_draft" bigint not null default 0);
create index "idx_journey_entries_source_trip_id" on "journey_entries" ("source_trip_id");
create index "idx_journey_entries_source" on "journey_entries" ("source_place_id");
create index "idx_journey_entries_author_id" on "journey_entries" ("author_id");
create index "idx_journey_entries_source_assignment" on "journey_entries" ("source_place_id", "source_assignment_id");
create index "idx_journey_entries_order" on "journey_entries" ("journey_id", "entry_date", "sort_order");
create index "idx_journey_entries_journey" on "journey_entries" ("journey_id", "entry_date");
create table "journey_entry_stays" ("id" bigserial primary key, "journey_id" bigint not null, "entry_id" bigint not null, "source" text not null default 'dawarich', "source_visit_id" text not null, "name" text not null, "lat" double precision null, "lng" double precision null, "started_at" text not null, "ended_at" text not null, "duration_minutes" bigint not null default 0, "sort_order" bigint not null default 0, "user_id" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_journey_entry_stays_entry" on "journey_entry_stays" ("entry_id");
create index "idx_journey_entry_stays_user" on "journey_entry_stays" ("user_id");
alter table "journey_entry_stays" add constraint "idx_journey_entry_stays_stay" unique ("journey_id", "source", "user_id", "source_visit_id");
create table "journey_entry_photos" ("entry_id" bigint not null, "journey_photo_id" bigint not null, "sort_order" bigint null default 0, "created_at" bigint not null, primary key ("entry_id", "journey_photo_id"));
create index "idx_journey_entry_photos_entry" on "journey_entry_photos" ("entry_id");
create index "idx_journey_entry_photos_photo" on "journey_entry_photos" ("journey_photo_id");
alter table "journey_entry_photos" add constraint "journey_entry_photos_entry_id_journey_photo_id_unique" unique ("entry_id", "journey_photo_id");
create table "day_assignments" ("id" bigserial primary key, "day_id" bigint not null, "place_id" bigint not null, "order_index" bigint null default 0, "notes" text null, "reservation_status" text null default 'none', "reservation_notes" text null, "reservation_datetime" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "assignment_time" text null, "assignment_end_time" text null, "leg_transport_mode" text null, "incoming_leg_transport_mode" text null, "end_day" bigint not null default 0, "accommodation_id" bigint null, "route_excluded" bigint not null default 0, "tour_stage_key" text null);
create index "idx_day_assignments_day_id" on "day_assignments" ("day_id");
create index "idx_day_assignments_place_id" on "day_assignments" ("place_id");
create index "idx_day_assignments_accommodation_id" on "day_assignments" ("accommodation_id");
create index "idx_day_assignments_tour_stage" on "day_assignments" ("place_id", "tour_stage_key") where tour_stage_key IS NOT NULL;
create table "tour_station_visits" ("assignment_id" bigint not null, "station_key" text not null, "status" text not null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("assignment_id", "station_key"));
alter table "tour_station_visits" add constraint "tour_station_visits_assignment_id_station_key_unique" unique ("assignment_id", "station_key");
alter table "tour_station_visits" add constraint "tour_station_visits_status_check" check ("status" in ('visited', 'skipped'));
create table "tour_activities" ("id" bigserial primary key, "place_id" bigint not null, "track_place_id" bigint not null, "assignment_id" bigint null, "assigned_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "assigned_by" bigint null);
create index "idx_tour_activities_place" on "tour_activities" ("place_id");
create index "idx_tour_activities_assigned_by" on "tour_activities" ("assigned_by");
create unique index "idx_tour_activities_assignment" on "tour_activities" ("assignment_id") where assignment_id IS NOT NULL;
alter table "tour_activities" add constraint "tour_activities_track_place_id_unique" unique ("track_place_id");
create table "roadtrip_day_boundaries" ("trip_id" bigint not null, "day_number" bigint not null, "from_assignment_id" bigint not null, "to_assignment_id" bigint null, "fraction" double precision not null, primary key ("trip_id", "day_number"));
create index "idx_roadtrip_day_boundaries_from_assignment_id" on "roadtrip_day_boundaries" ("from_assignment_id");
create index "idx_roadtrip_day_boundaries_to_assignment_id" on "roadtrip_day_boundaries" ("to_assignment_id");
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_trip_id_day_number_unique" unique ("trip_id", "day_number");
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_fraction_check" check (fraction BETWEEN 0 AND 1);
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_day_number_check" check (day_number >= 1);
create table "reservations" ("id" bigserial primary key, "trip_id" bigint not null, "day_id" bigint null, "end_day_id" bigint null, "place_id" bigint null, "assignment_id" bigint null, "title" text not null, "accommodation_id" text null, "reservation_time" text null, "reservation_end_time" text null, "location" text null, "confirmation_number" text null, "notes" text null, "status" text null default 'pending', "type" text null default 'other', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "metadata" text null, "day_plan_position" double precision null default NULL, "needs_review" bigint not null default 0, "external_source" text null, "external_id" text null, "external_owner_user_id" bigint null, "external_synced_at" text null, "sync_enabled" bigint null default 1, "external_hash" text null, "url" text null, "ingest_state" text not null default 'live');
create index "idx_reservations_trip_id" on "reservations" ("trip_id");
create index "idx_reservations_day_id" on "reservations" ("day_id");
create index "idx_reservations_end_day_id" on "reservations" ("end_day_id");
create index "idx_reservations_place_id" on "reservations" ("place_id");
create index "idx_reservations_assignment_id" on "reservations" ("assignment_id");
alter table "reservations" add constraint "idx_reservations_external" unique ("external_source", "external_id", "trip_id");
create table "trip_files" ("id" bigserial primary key, "trip_id" bigint not null, "place_id" bigint null, "reservation_id" bigint null, "filename" text not null, "original_name" text not null, "file_size" bigint null, "mime_type" text null, "description" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "note_id" bigint null, "starred" bigint null default 0, "deleted_at" text null, "message_id" bigint null, "uploaded_by" bigint null);
create index "idx_trip_files_trip_id" on "trip_files" ("trip_id");
create index "idx_trip_files_place_id" on "trip_files" ("place_id");
create index "idx_trip_files_reservation_id" on "trip_files" ("reservation_id");
create index "idx_trip_files_note_id" on "trip_files" ("note_id");
create index "idx_trip_files_message_id" on "trip_files" ("message_id");
create index "idx_trip_files_uploaded_by" on "trip_files" ("uploaded_by");
create table "document_sync_items" ("id" bigserial primary key, "link_id" bigint not null, "trip_id" bigint not null, "file_id" bigint null, "trek_doc_uid" text not null, "remote_id" text null, "remote_name" text null, "remote_version" text null, "remote_size" bigint null, "remote_modified_at" text null, "content_sha256" text null, "pushed_sha256" text null, "state" text not null default 'pending', "error_code" text null, "attempts" bigint not null default 0, "next_attempt_at" text null, "remote_missing_at" text null, "first_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "synced_at" text null, "remote_trashed_at" text null);
create index "idx_document_sync_items_file_id" on "document_sync_items" ("file_id");
create index "idx_document_sync_items_due" on "document_sync_items" ("link_id", "next_attempt_at");
create index "idx_document_sync_items_hash" on "document_sync_items" ("link_id", "content_sha256");
create index "idx_document_sync_items_trip_state" on "document_sync_items" ("trip_id", "state");
alter table "document_sync_items" add constraint "idx_document_sync_items_uid" unique ("link_id", "trek_doc_uid");
create unique index "idx_document_sync_items_file" on "document_sync_items" ("link_id", "file_id") where file_id IS NOT NULL;
create unique index "idx_document_sync_items_remote" on "document_sync_items" ("link_id", "remote_id") where remote_id IS NOT NULL;
create table "reservation_travelers" ("id" bigserial primary key, "reservation_id" bigint not null, "user_id" bigint not null);
create index "idx_reservation_travelers_res" on "reservation_travelers" ("reservation_id");
create index "idx_reservation_travelers_user" on "reservation_travelers" ("user_id");
alter table "reservation_travelers" add constraint "reservation_travelers_reservation_id_user_id_unique" unique ("reservation_id", "user_id");
create table "reservation_endpoints" ("id" bigserial primary key, "reservation_id" bigint not null, "role" text not null, "sequence" bigint not null default 0, "name" text not null, "code" text null, "lat" double precision not null, "lng" double precision not null, "timezone" text null, "local_time" text null, "local_date" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_reservation_endpoints_reservation_id" on "reservation_endpoints" ("reservation_id");
create table "reservation_day_positions" ("reservation_id" bigint not null, "day_id" bigint not null, "position" double precision not null, primary key ("reservation_id", "day_id"));
create index "idx_reservation_day_positions_day_id" on "reservation_day_positions" ("day_id");
alter table "reservation_day_positions" add constraint "reservation_day_positions_reservation_id_day_id_unique" unique ("reservation_id", "day_id");
create table "day_accommodations" ("id" bigserial primary key, "trip_id" bigint not null, "place_id" bigint null, "start_day_id" bigint not null, "end_day_id" bigint not null, "check_in" text null, "check_in_end" text null, "check_out" text null, "confirmation" text null, "notes" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_day_accommodations_trip_id" on "day_accommodations" ("trip_id");
create index "idx_day_accommodations_place_id" on "day_accommodations" ("place_id");
create index "idx_day_accommodations_start_day_id" on "day_accommodations" ("start_day_id");
create index "idx_day_accommodations_end_day_id" on "day_accommodations" ("end_day_id");
create table "collection_places" ("id" bigserial primary key, "collection_id" bigint not null, "owner_id" bigint not null, "name" text not null, "description" text null, "lat" double precision null, "lng" double precision null, "address" text null, "category_id" bigint null, "price" double precision null, "currency" text null, "notes" text null, "image_url" text null, "google_place_id" text null, "google_ftid" text null, "osm_id" text null, "website" text null, "phone" text null, "status" text not null default 'idea', "source_trip_id" bigint null, "source_place_id" bigint null, "links" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "saved_by" bigint null);
create index "idx_collection_places_collection" on "collection_places" ("collection_id");
create index "idx_collection_places_owner_id" on "collection_places" ("owner_id");
create index "idx_collection_places_category_id" on "collection_places" ("category_id");
create index "idx_collection_places_saved_by" on "collection_places" ("saved_by");
create table "collection_place_ratings" ("id" bigserial primary key, "collection_place_id" bigint not null, "user_id" bigint not null, "rating" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_collection_place_ratings_place" on "collection_place_ratings" ("collection_place_id");
create index "idx_collection_place_ratings_user_id" on "collection_place_ratings" ("user_id");
alter table "collection_place_ratings" add constraint "collection_place_ratings_collection_place_id_user_id_unique" unique ("collection_place_id", "user_id");
create table "collection_place_tags" ("collection_place_id" bigint not null, "tag_id" bigint not null, primary key ("collection_place_id", "tag_id"));
create table "collection_place_labels" ("collection_place_id" bigint not null, "label_id" bigint not null, primary key ("collection_place_id", "label_id"));
create table "budget_settlements" ("id" bigserial primary key, "trip_id" bigint not null, "from_user_id" bigint not null, "to_user_id" bigint not null, "amount" double precision not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by_user_id" bigint null, "currency" text null, "exchange_rate" double precision not null default 1, "settled_at" text null, "note" text null);
create index "idx_budget_settlements_trip" on "budget_settlements" ("trip_id");
create index "idx_budget_settlements_from_user_id" on "budget_settlements" ("from_user_id");
create index "idx_budget_settlements_to_user_id" on "budget_settlements" ("to_user_id");
create index "idx_budget_settlements_created_by_user_id" on "budget_settlements" ("created_by_user_id");
create table "budget_items" ("id" bigserial primary key, "trip_id" bigint not null, "category" text not null default 'Other', "name" text not null, "total_price" double precision not null default 0, "persons" bigint null default NULL, "days" bigint null default NULL, "note" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "paid_by_user_id" bigint null, "expense_date" text null default NULL, "reservation_id" bigint null default NULL, "currency" text null, "exchange_rate" double precision not null default 1, "ticket_json" text null, "place_id" bigint null default NULL);
create index "idx_budget_items_trip_id" on "budget_items" ("trip_id");
create index "idx_budget_items_paid_by_user_id" on "budget_items" ("paid_by_user_id");
create index "idx_budget_items_reservation_id" on "budget_items" ("reservation_id");
create index "idx_budget_items_place_id" on "budget_items" ("place_id");
create table "file_links" ("id" bigserial primary key, "file_id" bigint not null, "reservation_id" bigint null, "assignment_id" bigint null, "place_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "budget_item_id" bigint null);
create index "idx_file_links_reservation_id" on "file_links" ("reservation_id");
create index "idx_file_links_assignment_id" on "file_links" ("assignment_id");
create index "idx_file_links_place_id" on "file_links" ("place_id");
create index "idx_file_links_budget_item_id" on "file_links" ("budget_item_id");
alter table "file_links" add constraint "idx_file_links_file_budget" unique ("file_id", "budget_item_id");
alter table "file_links" add constraint "file_links_file_id_place_id_unique" unique ("file_id", "place_id");
alter table "file_links" add constraint "file_links_file_id_assignment_id_unique" unique ("file_id", "assignment_id");
alter table "file_links" add constraint "file_links_file_id_reservation_id_unique" unique ("file_id", "reservation_id");
create table "budget_item_payers" ("id" bigserial primary key, "budget_item_id" bigint not null, "user_id" bigint not null, "amount" double precision not null default 0);
create index "idx_budget_item_payers_item" on "budget_item_payers" ("budget_item_id");
create index "idx_budget_item_payers_user_id" on "budget_item_payers" ("user_id");
alter table "budget_item_payers" add constraint "budget_item_payers_budget_item_id_user_id_unique" unique ("budget_item_id", "user_id");
create table "budget_item_members" ("id" bigserial primary key, "budget_item_id" bigint not null, "user_id" bigint not null, "paid" bigint not null default 0, "amount" double precision null);
create index "idx_budget_item_members_item" on "budget_item_members" ("budget_item_id");
create index "idx_budget_item_members_user" on "budget_item_members" ("user_id");
alter table "budget_item_members" add constraint "budget_item_members_budget_item_id_user_id_unique" unique ("budget_item_id", "user_id");
create table "bucket_list" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "lat" double precision null, "lng" double precision null, "country_code" text null, "notes" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "target_date" text null default NULL, "visited_at" text null, "visited_source" text null, "region_code" text null);
create index "idx_bucket_list_user_id" on "bucket_list" ("user_id");
create table "dawarich_visit_suggestions" ("id" bigserial primary key, "user_id" bigint not null, "source_visit_id" text not null, "trip_id" bigint null, "name" text not null, "lat" double precision null, "lng" double precision null, "started_at" text not null, "ended_at" text not null, "duration_minutes" bigint not null default 0, "local_date" text not null, "source_status" text not null default 'suggested', "confidence" double precision null, "confidence_band" text null, "country_code" text null, "state" text not null default 'new', "target" text null, "accepted_place_id" bigint null, "accepted_journal_entry_id" bigint null, "accepted_bucket_list_item_id" bigint null, "matched_bucket_list_item_id" bigint null, "source_hash" text not null, "accepted_hash" text null, "source_missing_at" text null, "first_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_dawarich_suggestions_trip" on "dawarich_visit_suggestions" ("trip_id");
create index "idx_dawarich_visit_suggestions_accepted_place_id" on "dawarich_visit_suggestions" ("accepted_place_id");
create index "idx_dawarich_visit_suggestions_accepted_bucket_list_item_id" on "dawarich_visit_suggestions" ("accepted_bucket_list_item_id");
create index "idx_dawarich_visit_suggestions_matched_bucket_list_item_id" on "dawarich_visit_suggestions" ("matched_bucket_list_item_id");
create index "idx_dawarich_suggestions_user_state" on "dawarich_visit_suggestions" ("user_id", "state");
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_user_id_source_visit_id_unique" unique ("user_id", "source_visit_id");
create table "audit_log" ("id" bigserial primary key, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "user_id" bigint null, "action" text not null, "resource" text null, "details" text null, "ip" text null);
create index "idx_audit_log_created" on "audit_log" ("created_at");
create index "idx_audit_log_user_id" on "audit_log" ("user_id");
create table "assistant_usage" ("user_id" bigint not null, "day" text not null, "paid_by" text not null, "turns" bigint not null default 0, "input_tokens" bigint not null default 0, "output_tokens" bigint not null default 0, primary key ("user_id", "day", "paid_by"));
alter table "assistant_usage" add constraint "assistant_usage_user_id_day_paid_by_unique" unique ("user_id", "day", "paid_by");
create table "assistant_threads" ("id" bigserial primary key, "user_id" bigint not null, "trip_id" bigint null, "journey_id" bigint null, "title" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_message_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_assistant_threads_trip" on "assistant_threads" ("trip_id");
create index "idx_assistant_threads_journey" on "assistant_threads" ("journey_id");
create index "idx_assistant_threads_user_trip" on "assistant_threads" ("user_id", "trip_id", "last_message_at");
create index "idx_assistant_threads_user_journey" on "assistant_threads" ("user_id", "journey_id", "last_message_at");
create table "assistant_messages" ("id" bigserial primary key, "thread_id" bigint not null, "role" text not null, "parts" text not null, "provider_state" text null, "status" text not null default 'complete', "model" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_assistant_messages_thread" on "assistant_messages" ("thread_id", "id");
create table "assistant_tool_calls" ("id" text not null, "thread_id" bigint not null, "message_id" bigint not null, "provider_call_id" text not null, "tool_name" text not null, "args" text not null, "preview" text not null, "state" text not null default 'approval_requested', "result" text null, "undo_until" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "decided_at" text null, primary key ("id"));
create index "idx_assistant_tool_calls_message" on "assistant_tool_calls" ("message_id");
alter table "assistant_tool_calls" add constraint "assistant_tool_calls_thread_id_provider_call_id_unique" unique ("thread_id", "provider_call_id");
create table "assistant_attachments" ("id" text not null, "thread_id" bigint not null, "user_id" bigint not null, "trip_id" bigint not null, "name" text not null, "mime" text not null, "size" bigint not null, "sha256" text not null, "storage_key" text not null, "text" text null, "text_status" text not null, "shared_at" text null, "file_id" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("id"));
create index "idx_assistant_attachments_user" on "assistant_attachments" ("user_id");
create index "idx_assistant_attachments_trip" on "assistant_attachments" ("trip_id");
create index "idx_assistant_attachments_file" on "assistant_attachments" ("file_id");
create index "idx_assistant_attachments_created" on "assistant_attachments" ("created_at");
create index "idx_assistant_attachments_thread" on "assistant_attachments" ("thread_id", "created_at");
create table "assignment_participants" ("id" bigserial primary key, "assignment_id" bigint not null, "user_id" bigint not null);
create index "idx_assignment_participants_assignment" on "assignment_participants" ("assignment_id");
create index "idx_assignment_participants_user_id" on "assignment_participants" ("user_id");
alter table "assignment_participants" add constraint "assignment_participants_assignment_id_user_id_unique" unique ("assignment_id", "user_id");
create table "ai_connections" ("id" bigserial primary key, "scope" text not null, "user_id" bigint null, "kind" text not null, "model" text not null, "base_url" text null, "secrets" text null, "secrets_version" bigint not null default 0, "hint" text null, "account" text null, "status" text not null default 'ok', "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create unique index "idx_ai_connections_instance" on "ai_connections" ("scope") where user_id IS NULL;
create unique index "idx_ai_connections_user" on "ai_connections" ("user_id") where user_id IS NOT NULL;
create table "user_sessions" ("id" text not null, "user_id" bigint not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "expires_at" text not null, "revoked_at" text null, "user_agent" text null, primary key ("id"));
create index "idx_user_sessions_user" on "user_sessions" ("user_id");
create index "idx_user_sessions_expires" on "user_sessions" ("expires_at");
create table "vacay_plans" ("id" bigserial primary key, "owner_id" bigint not null, "block_weekends" bigint null default 1, "holidays_enabled" bigint null default 0, "holidays_region" text null default '', "school_holidays_enabled" bigint null default 0, "company_holidays_enabled" bigint null default 1, "carry_over_enabled" bigint null default 1, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "weekend_days" text null default '0,6', "week_start" bigint not null default 1);
alter table "vacay_plans" add constraint "vacay_plans_owner_id_unique" unique ("owner_id");
create table "vacay_plan_members" ("id" bigserial primary key, "plan_id" bigint not null, "user_id" bigint not null, "status" text null default 'pending', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_vacay_plan_members_user_id" on "vacay_plan_members" ("user_id");
alter table "vacay_plan_members" add constraint "vacay_plan_members_plan_id_user_id_unique" unique ("plan_id", "user_id");
create table "vacay_holiday_calendars" ("id" bigserial primary key, "plan_id" bigint not null, "type" text not null default 'public_holiday', "region" text not null, "label" text null, "color" text not null default '#fecaca', "sort_order" bigint not null default 0);
create index "idx_vacay_holiday_calendars_plan_id" on "vacay_holiday_calendars" ("plan_id");
create table "vacay_entries" ("id" bigserial primary key, "plan_id" bigint not null, "user_id" bigint not null, "date" text not null, "note" text null default '', "fraction" double precision not null default 1, "kind" text not null default 'vacation');
create index "idx_vacay_entries_plan_id" on "vacay_entries" ("plan_id");
alter table "vacay_entries" add constraint "vacay_entries_user_id_plan_id_date_unique" unique ("user_id", "plan_id", "date");
create table "vacay_company_holidays" ("id" bigserial primary key, "plan_id" bigint not null, "date" text not null, "note" text null default '', "fraction" double precision not null default 1);
alter table "vacay_company_holidays" add constraint "vacay_company_holidays_plan_id_date_unique" unique ("plan_id", "date");
create table "vacay_shares" ("id" bigserial primary key, "owner_id" bigint not null, "user_id" bigint not null, "hidden" bigint not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_vacay_shares_user" on "vacay_shares" ("user_id");
alter table "vacay_shares" add constraint "vacay_shares_owner_id_user_id_unique" unique ("owner_id", "user_id");
create table "vacay_user_colors" ("id" bigserial primary key, "user_id" bigint not null, "plan_id" bigint not null, "color" text null default '#6366f1');
create index "idx_vacay_user_colors_plan_id" on "vacay_user_colors" ("plan_id");
alter table "vacay_user_colors" add constraint "vacay_user_colors_user_id_plan_id_unique" unique ("user_id", "plan_id");
create table "vacay_user_settings" ("user_id" bigint null, "year_type" text not null default 'calendar', "year_start_month" bigint not null default 1, "year_start_day" bigint not null default 1, "hire_date" text null, primary key ("user_id"));
create table "vacay_user_years" ("id" bigserial primary key, "user_id" bigint not null, "plan_id" bigint not null, "year" bigint not null, "vacation_days" bigint null default 30, "carried_over" bigint null default 0);
create index "idx_vacay_user_years_plan_id" on "vacay_user_years" ("plan_id");
alter table "vacay_user_years" add constraint "vacay_user_years_user_id_plan_id_year_unique" unique ("user_id", "plan_id", "year");
create table "vacay_years" ("id" bigserial primary key, "plan_id" bigint not null, "year" bigint not null);
alter table "vacay_years" add constraint "vacay_years_plan_id_year_unique" unique ("plan_id", "year");
create table "visited_countries" ("id" bigserial primary key, "user_id" bigint not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "source" text not null default 'manual');
alter table "visited_countries" add constraint "visited_countries_user_id_country_code_unique" unique ("user_id", "country_code");
create table "visited_regions" ("id" bigserial primary key, "user_id" bigint not null, "region_code" text not null, "region_name" text not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_visited_regions_country" on "visited_regions" ("country_code");
alter table "visited_regions" add constraint "visited_regions_user_id_region_code_unique" unique ("user_id", "region_code");
create table "wanderer_connections" ("user_id" bigint null, "url" text not null, "token" text null, "allow_insecure_tls" bigint not null default 0, "last_checked_at" text null, "last_check_ok" bigint null, "last_check_error" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "watch_enabled" bigint not null default 0, "watch_last_run_at" text null, "watch_failures" bigint not null default 0, "watch_paused_until" text null, primary key ("user_id"));
create table "webauthn_challenges" ("id" bigserial primary key, "challenge" text not null, "user_id" bigint null, "type" text not null, "expires_at" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
create index "idx_webauthn_challenges_user_id" on "webauthn_challenges" ("user_id");
create index "idx_webauthn_challenges_expires" on "webauthn_challenges" ("expires_at");
alter table "webauthn_challenges" add constraint "webauthn_challenges_challenge_unique" unique ("challenge");
create table "webauthn_credentials" ("id" bigserial primary key, "user_id" bigint not null, "credential_id" text not null, "public_key" bytea not null, "counter" bigint not null default 0, "transports" text null, "device_type" text null, "backed_up" bigint not null default 0, "name" text null, "aaguid" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_used_at" text null);
create index "idx_webauthn_credentials_user" on "webauthn_credentials" ("user_id");
alter table "webauthn_credentials" add constraint "webauthn_credentials_credential_id_unique" unique ("credential_id");
alter table "document_provider_fields" add constraint "document_provider_fields_provider_id_foreign" foreign key ("provider_id") references "document_providers" ("id") on delete cascade;
alter table "paddle_features" add constraint "paddle_features_region_id_foreign" foreign key ("region_id") references "paddle_regions" ("id") on delete cascade;
alter table "paddle_water_graphs" add constraint "paddle_water_graphs_region_id_foreign" foreign key ("region_id") references "paddle_regions" ("id") on update cascade on delete cascade;
alter table "photo_provider_fields" add constraint "photo_provider_fields_provider_id_foreign" foreign key ("provider_id") references "photo_providers" ("id") on delete cascade;
alter table "school_holiday_regions" add constraint "school_holiday_regions_country_foreign" foreign key ("country") references "school_holiday_countries" ("code");
alter table "school_holiday_periods" add constraint "school_holiday_periods_region_id_foreign" foreign key ("region_id") references "school_holiday_regions" ("id") on delete cascade;
alter table "user_notice_dismissals" add constraint "user_notice_dismissals_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "trips" add constraint "trips_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "roadtrip_preferences" add constraint "roadtrip_preferences_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "days" add constraint "days_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "roadtrip_vias" add constraint "roadtrip_vias_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete cascade;
alter table "day_notes" add constraint "day_notes_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete cascade;
alter table "day_notes" add constraint "day_notes_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "budget_category_order" add constraint "budget_category_order_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_members" add constraint "trip_members_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_members" add constraint "trip_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "trip_members" add constraint "trip_members_invited_by_foreign" foreign key ("invited_by") references "users" ("id") on delete no action;
alter table "trip_member_removals" add constraint "trip_member_removals_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_member_removals" add constraint "trip_member_removals_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete set null;
alter table "trip_album_links" add constraint "trip_album_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_album_links" add constraint "trip_album_links_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "trek_photos" add constraint "trek_photos_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete set null;
alter table "trip_photos" add constraint "trip_photos_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_photos" add constraint "trip_photos_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "trip_photos" add constraint "trip_photos_photo_id_foreign" foreign key ("photo_id") references "trek_photos" ("id") on delete cascade;
alter table "trip_photos" add constraint "trip_photos_album_link_id_foreign" foreign key ("album_link_id") references "trip_album_links" ("id") on delete set null;
alter table "trek_photo_signals" add constraint "trek_photo_signals_photo_id_foreign" foreign key ("photo_id") references "trek_photos" ("id") on delete cascade;
alter table "tour_drafts" add constraint "tour_drafts_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "tour_drafts" add constraint "tour_drafts_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "todo_items" add constraint "todo_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "todo_items" add constraint "todo_items_assigned_user_id_foreign" foreign key ("assigned_user_id") references "users" ("id") on delete set null;
alter table "todo_category_assignees" add constraint "todo_category_assignees_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "todo_category_assignees" add constraint "todo_category_assignees_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "tags" add constraint "tags_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "share_tokens" add constraint "share_tokens_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "share_tokens" add constraint "share_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id");
alter table "settings" add constraint "settings_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "push_subscriptions" add constraint "push_subscriptions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "password_reset_tokens" add constraint "password_reset_tokens_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "packing_templates" add constraint "packing_templates_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete cascade;
alter table "packing_template_categories" add constraint "packing_template_categories_template_id_foreign" foreign key ("template_id") references "packing_templates" ("id") on delete cascade;
alter table "packing_template_items" add constraint "packing_template_items_category_id_foreign" foreign key ("category_id") references "packing_template_categories" ("id") on delete cascade;
alter table "packing_category_assignees" add constraint "packing_category_assignees_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "packing_category_assignees" add constraint "packing_category_assignees_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "packing_bags" add constraint "packing_bags_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "packing_bags" add constraint "packing_bags_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
alter table "packing_items" add constraint "packing_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "packing_items" add constraint "packing_items_bag_id_foreign" foreign key ("bag_id") references "packing_bags" ("id") on delete set null;
alter table "packing_items" add constraint "packing_items_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete set null;
alter table "packing_item_contributors" add constraint "packing_item_contributors_item_id_foreign" foreign key ("item_id") references "packing_items" ("id") on update cascade on delete cascade;
alter table "packing_item_contributors" add constraint "packing_item_contributors_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "packing_item_recipients" add constraint "packing_item_recipients_item_id_foreign" foreign key ("item_id") references "packing_items" ("id") on update cascade on delete cascade;
alter table "packing_item_recipients" add constraint "packing_item_recipients_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "packing_bag_members" add constraint "packing_bag_members_bag_id_foreign" foreign key ("bag_id") references "packing_bags" ("id") on update cascade on delete cascade;
alter table "packing_bag_members" add constraint "packing_bag_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "oauth_clients" add constraint "oauth_clients_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "oauth_tokens" add constraint "oauth_tokens_client_id_foreign" foreign key ("client_id") references "oauth_clients" ("client_id") on delete cascade;
alter table "oauth_tokens" add constraint "oauth_tokens_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "oauth_tokens" add constraint "oauth_tokens_parent_token_id_foreign" foreign key ("parent_token_id") references "oauth_tokens" ("id") on delete no action;
alter table "oauth_consents" add constraint "oauth_consents_client_id_foreign" foreign key ("client_id") references "oauth_clients" ("client_id") on delete cascade;
alter table "oauth_consents" add constraint "oauth_consents_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "notifications" add constraint "notifications_sender_id_foreign" foreign key ("sender_id") references "users" ("id") on delete set null;
alter table "notifications" add constraint "notifications_recipient_id_foreign" foreign key ("recipient_id") references "users" ("id") on delete cascade;
alter table "notification_channel_preferences" add constraint "notification_channel_preferences_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "mcp_tokens" add constraint "mcp_tokens_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "journeys" add constraint "journeys_user_id_foreign" foreign key ("user_id") references "users" ("id");
alter table "trip_journal_links" add constraint "trip_journal_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_journal_links" add constraint "trip_journal_links_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "trip_journal_links" add constraint "trip_journal_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null;
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_link_id_foreign" foreign key ("link_id") references "trip_journal_links" ("id") on update cascade on delete cascade;
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "journey_trips" add constraint "journey_trips_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on update cascade on delete cascade;
alter table "journey_trips" add constraint "journey_trips_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on update cascade on delete cascade;
alter table "journey_share_tokens" add constraint "journey_share_tokens_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_share_tokens" add constraint "journey_share_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id");
alter table "journey_photos" add constraint "journey_photos_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_photos" add constraint "journey_photos_photo_id_foreign" foreign key ("photo_id") references "trek_photos" ("id") on delete cascade;
alter table "journey_book_revisions" add constraint "journey_book_revisions_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_recording_prep" add constraint "journey_recording_prep_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_recording_prep" add constraint "journey_recording_prep_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "journey_recorded_days" add constraint "journey_recorded_days_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_recorded_days" add constraint "journey_recorded_days_imported_by_foreign" foreign key ("imported_by") references "users" ("id") on delete set null;
alter table "journey_contributors" add constraint "journey_contributors_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on update cascade on delete cascade;
alter table "journey_contributors" add constraint "journey_contributors_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete no action;
alter table "journey_books" add constraint "journey_books_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_books" add constraint "journey_books_updated_by_foreign" foreign key ("updated_by") references "users" ("id") on delete set null;
alter table "journey_books" add constraint "journey_books_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete set null;
alter table "invite_tokens" add constraint "invite_tokens_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete set null;
alter table "invite_tokens" add constraint "invite_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete cascade;
alter table "idempotency_keys" add constraint "idempotency_keys_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "hidden_regions" add constraint "hidden_regions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "hidden_countries" add constraint "hidden_countries_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "document_connections" add constraint "document_connections_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "document_connections" add constraint "document_connections_provider_id_foreign" foreign key ("provider_id") references "document_providers" ("id") on delete cascade;
alter table "document_connections" add constraint "document_connections_owner_user_id_foreign" foreign key ("owner_user_id") references "users" ("id") on delete cascade;
alter table "trip_document_links" add constraint "trip_document_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_document_links" add constraint "trip_document_links_connection_id_foreign" foreign key ("connection_id") references "document_connections" ("id") on delete cascade;
alter table "trip_document_links" add constraint "trip_document_links_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete set null;
alter table "dawarich_connections" add constraint "dawarich_connections_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "collections" add constraint "collections_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
alter table "collection_tours" add constraint "collection_tours_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
alter table "collection_tours" add constraint "collection_tours_tour_type_foreign" foreign key ("tour_type") references "tour_types" ("key");
alter table "collection_tours" add constraint "collection_tours_saved_by_foreign" foreign key ("saved_by") references "users" ("id") on delete set null;
alter table "collection_labels" add constraint "collection_labels_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
alter table "collection_members" add constraint "collection_members_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
alter table "collection_members" add constraint "collection_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collab_polls" add constraint "collab_polls_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "collab_polls" add constraint "collab_polls_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collab_poll_votes" add constraint "collab_poll_votes_poll_id_foreign" foreign key ("poll_id") references "collab_polls" ("id") on delete cascade;
alter table "collab_poll_votes" add constraint "collab_poll_votes_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collab_notes" add constraint "collab_notes_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "collab_notes" add constraint "collab_notes_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collab_messages" add constraint "collab_messages_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "collab_messages" add constraint "collab_messages_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collab_messages" add constraint "collab_messages_reply_to_foreign" foreign key ("reply_to") references "collab_messages" ("id") on delete set null;
alter table "collab_message_reactions" add constraint "collab_message_reactions_message_id_foreign" foreign key ("message_id") references "collab_messages" ("id") on delete cascade;
alter table "collab_message_reactions" add constraint "collab_message_reactions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collab_links" add constraint "collab_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "collab_links" add constraint "collab_links_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "categories" add constraint "categories_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
alter table "places" add constraint "places_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "places" add constraint "places_category_id_foreign" foreign key ("category_id") references "categories" ("id") on delete set null;
alter table "tours" add constraint "tours_place_id_foreign" foreign key ("place_id") references "places" ("id") on update cascade on delete cascade;
alter table "tours" add constraint "tours_derived_from_place_id_foreign" foreign key ("derived_from_place_id") references "places" ("id") on delete set null;
alter table "tours" add constraint "tours_tour_type_foreign" foreign key ("tour_type") references "tour_types" ("key");
alter table "tour_waypoints" add constraint "tour_waypoints_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
alter table "tour_waypoints" add constraint "tour_waypoints_linked_place_id_foreign" foreign key ("linked_place_id") references "places" ("id") on delete set null;
alter table "tour_sources" add constraint "tour_sources_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on update cascade on delete cascade;
alter table "tour_sources" add constraint "tour_sources_imported_by_foreign" foreign key ("imported_by") references "users" ("id") on delete set null;
alter table "tour_source_hints" add constraint "tour_source_hints_place_id_foreign" foreign key ("place_id") references "tour_sources" ("place_id") on update cascade on delete cascade;
alter table "tour_source_hints" add constraint "tour_source_hints_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "tour_packing_links" add constraint "tour_packing_links_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on update cascade on delete cascade;
alter table "tour_packing_links" add constraint "tour_packing_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null;
alter table "tour_obstacle_reviews" add constraint "tour_obstacle_reviews_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
alter table "tour_change_steps" add constraint "tour_change_steps_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
alter table "tour_activity_exclusions" add constraint "tour_activity_exclusions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "tour_activity_exclusions" add constraint "tour_activity_exclusions_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
alter table "roadtrip_day_tracks" add constraint "roadtrip_day_tracks_day_id_foreign" foreign key ("day_id") references "days" ("id") on update cascade on delete cascade;
alter table "roadtrip_day_tracks" add constraint "roadtrip_day_tracks_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
alter table "place_regions" add constraint "place_regions_place_id_foreign" foreign key ("place_id") references "places" ("id") on update cascade on delete cascade;
alter table "place_ratings" add constraint "place_ratings_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
alter table "place_ratings" add constraint "place_ratings_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "place_field_origin" add constraint "place_field_origin_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
alter table "place_contrib_outbox" add constraint "place_contrib_outbox_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
alter table "place_tags" add constraint "place_tags_place_id_foreign" foreign key ("place_id") references "places" ("id") on update cascade on delete cascade;
alter table "place_tags" add constraint "place_tags_tag_id_foreign" foreign key ("tag_id") references "tags" ("id") on update cascade on delete cascade;
alter table "photos" add constraint "photos_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "photos" add constraint "photos_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete set null;
alter table "photos" add constraint "photos_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
alter table "journey_entries" add constraint "journey_entries_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_entries" add constraint "journey_entries_source_trip_id_foreign" foreign key ("source_trip_id") references "trips" ("id") on delete set null;
alter table "journey_entries" add constraint "journey_entries_source_place_id_foreign" foreign key ("source_place_id") references "places" ("id") on delete set null;
alter table "journey_entries" add constraint "journey_entries_author_id_foreign" foreign key ("author_id") references "users" ("id");
alter table "journey_entry_stays" add constraint "journey_entry_stays_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "journey_entry_stays" add constraint "journey_entry_stays_entry_id_foreign" foreign key ("entry_id") references "journey_entries" ("id") on delete cascade;
alter table "journey_entry_stays" add constraint "journey_entry_stays_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
alter table "journey_entry_photos" add constraint "journey_entry_photos_entry_id_foreign" foreign key ("entry_id") references "journey_entries" ("id") on update cascade on delete cascade;
alter table "journey_entry_photos" add constraint "journey_entry_photos_journey_photo_id_foreign" foreign key ("journey_photo_id") references "journey_photos" ("id") on update cascade on delete cascade;
alter table "day_assignments" add constraint "day_assignments_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete cascade;
alter table "day_assignments" add constraint "day_assignments_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
alter table "tour_station_visits" add constraint "tour_station_visits_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete cascade;
alter table "tour_activities" add constraint "tour_activities_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
alter table "tour_activities" add constraint "tour_activities_track_place_id_foreign" foreign key ("track_place_id") references "tours" ("place_id") on delete cascade;
alter table "tour_activities" add constraint "tour_activities_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete set null;
alter table "tour_activities" add constraint "tour_activities_assigned_by_foreign" foreign key ("assigned_by") references "users" ("id") on delete set null;
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_from_assignment_id_foreign" foreign key ("from_assignment_id") references "day_assignments" ("id") on delete cascade;
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_to_assignment_id_foreign" foreign key ("to_assignment_id") references "day_assignments" ("id") on delete cascade;
alter table "reservations" add constraint "reservations_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "reservations" add constraint "reservations_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete set null;
alter table "reservations" add constraint "reservations_end_day_id_foreign" foreign key ("end_day_id") references "days" ("id") on delete set null;
alter table "reservations" add constraint "reservations_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
alter table "reservations" add constraint "reservations_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete set null;
alter table "trip_files" add constraint "trip_files_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "trip_files" add constraint "trip_files_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
alter table "trip_files" add constraint "trip_files_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete set null;
alter table "trip_files" add constraint "trip_files_note_id_foreign" foreign key ("note_id") references "collab_notes" ("id") on delete set null;
alter table "trip_files" add constraint "trip_files_message_id_foreign" foreign key ("message_id") references "collab_messages" ("id") on delete cascade;
alter table "trip_files" add constraint "trip_files_uploaded_by_foreign" foreign key ("uploaded_by") references "users" ("id") on delete set null;
alter table "document_sync_items" add constraint "document_sync_items_link_id_foreign" foreign key ("link_id") references "trip_document_links" ("id") on delete cascade;
alter table "document_sync_items" add constraint "document_sync_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "document_sync_items" add constraint "document_sync_items_file_id_foreign" foreign key ("file_id") references "trip_files" ("id") on delete set null;
alter table "reservation_travelers" add constraint "reservation_travelers_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade;
alter table "reservation_travelers" add constraint "reservation_travelers_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "reservation_endpoints" add constraint "reservation_endpoints_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade;
alter table "reservation_day_positions" add constraint "reservation_day_positions_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on update cascade on delete cascade;
alter table "reservation_day_positions" add constraint "reservation_day_positions_day_id_foreign" foreign key ("day_id") references "days" ("id") on update cascade on delete cascade;
alter table "day_accommodations" add constraint "day_accommodations_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "day_accommodations" add constraint "day_accommodations_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
alter table "day_accommodations" add constraint "day_accommodations_start_day_id_foreign" foreign key ("start_day_id") references "days" ("id") on delete cascade;
alter table "day_accommodations" add constraint "day_accommodations_end_day_id_foreign" foreign key ("end_day_id") references "days" ("id") on delete cascade;
alter table "collection_places" add constraint "collection_places_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
alter table "collection_places" add constraint "collection_places_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
alter table "collection_places" add constraint "collection_places_category_id_foreign" foreign key ("category_id") references "categories" ("id") on delete set null;
alter table "collection_places" add constraint "collection_places_saved_by_foreign" foreign key ("saved_by") references "users" ("id") on delete set null;
alter table "collection_place_ratings" add constraint "collection_place_ratings_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade;
alter table "collection_place_ratings" add constraint "collection_place_ratings_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "collection_place_tags" add constraint "collection_place_tags_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on update cascade on delete cascade;
alter table "collection_place_tags" add constraint "collection_place_tags_tag_id_foreign" foreign key ("tag_id") references "tags" ("id") on update cascade on delete cascade;
alter table "collection_place_labels" add constraint "collection_place_labels_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on update cascade on delete cascade;
alter table "collection_place_labels" add constraint "collection_place_labels_label_id_foreign" foreign key ("label_id") references "collection_labels" ("id") on update cascade on delete cascade;
alter table "budget_settlements" add constraint "budget_settlements_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "budget_settlements" add constraint "budget_settlements_from_user_id_foreign" foreign key ("from_user_id") references "users" ("id") on delete cascade;
alter table "budget_settlements" add constraint "budget_settlements_to_user_id_foreign" foreign key ("to_user_id") references "users" ("id") on delete cascade;
alter table "budget_settlements" add constraint "budget_settlements_created_by_user_id_foreign" foreign key ("created_by_user_id") references "users" ("id") on delete no action;
alter table "budget_items" add constraint "budget_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "budget_items" add constraint "budget_items_paid_by_user_id_foreign" foreign key ("paid_by_user_id") references "users" ("id") on delete no action;
alter table "budget_items" add constraint "budget_items_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete set null;
alter table "budget_items" add constraint "budget_items_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
alter table "file_links" add constraint "file_links_file_id_foreign" foreign key ("file_id") references "trip_files" ("id") on delete cascade;
alter table "file_links" add constraint "file_links_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade;
alter table "file_links" add constraint "file_links_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete cascade;
alter table "file_links" add constraint "file_links_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
alter table "file_links" add constraint "file_links_budget_item_id_foreign" foreign key ("budget_item_id") references "budget_items" ("id") on delete set null;
alter table "budget_item_payers" add constraint "budget_item_payers_budget_item_id_foreign" foreign key ("budget_item_id") references "budget_items" ("id") on delete cascade;
alter table "budget_item_payers" add constraint "budget_item_payers_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "budget_item_members" add constraint "budget_item_members_budget_item_id_foreign" foreign key ("budget_item_id") references "budget_items" ("id") on delete cascade;
alter table "budget_item_members" add constraint "budget_item_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "bucket_list" add constraint "bucket_list_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete set null;
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_accepted_place_id_foreign" foreign key ("accepted_place_id") references "places" ("id") on delete set null;
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_accepted_bucket_list_item_id_foreign" foreign key ("accepted_bucket_list_item_id") references "bucket_list" ("id") on delete set null;
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_matched_bucket_list_item_id_foreign" foreign key ("matched_bucket_list_item_id") references "bucket_list" ("id") on delete set null;
alter table "audit_log" add constraint "audit_log_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
alter table "assistant_usage" add constraint "assistant_usage_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "assistant_threads" add constraint "assistant_threads_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "assistant_threads" add constraint "assistant_threads_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "assistant_threads" add constraint "assistant_threads_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
alter table "assistant_messages" add constraint "assistant_messages_thread_id_foreign" foreign key ("thread_id") references "assistant_threads" ("id") on delete cascade;
alter table "assistant_tool_calls" add constraint "assistant_tool_calls_thread_id_foreign" foreign key ("thread_id") references "assistant_threads" ("id") on delete cascade;
alter table "assistant_tool_calls" add constraint "assistant_tool_calls_message_id_foreign" foreign key ("message_id") references "assistant_messages" ("id") on delete cascade;
alter table "assistant_attachments" add constraint "assistant_attachments_thread_id_foreign" foreign key ("thread_id") references "assistant_threads" ("id") on delete cascade;
alter table "assistant_attachments" add constraint "assistant_attachments_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "assistant_attachments" add constraint "assistant_attachments_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
alter table "assistant_attachments" add constraint "assistant_attachments_file_id_foreign" foreign key ("file_id") references "trip_files" ("id") on delete set null;
alter table "assignment_participants" add constraint "assignment_participants_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete cascade;
alter table "assignment_participants" add constraint "assignment_participants_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "ai_connections" add constraint "ai_connections_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "user_sessions" add constraint "user_sessions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "vacay_plans" add constraint "vacay_plans_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
alter table "vacay_plan_members" add constraint "vacay_plan_members_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "vacay_plan_members" add constraint "vacay_plan_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "vacay_holiday_calendars" add constraint "vacay_holiday_calendars_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "vacay_entries" add constraint "vacay_entries_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "vacay_entries" add constraint "vacay_entries_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "vacay_company_holidays" add constraint "vacay_company_holidays_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "vacay_shares" add constraint "vacay_shares_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
alter table "vacay_shares" add constraint "vacay_shares_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "vacay_user_colors" add constraint "vacay_user_colors_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "vacay_user_colors" add constraint "vacay_user_colors_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "vacay_user_settings" add constraint "vacay_user_settings_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "vacay_user_years" add constraint "vacay_user_years_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "vacay_user_years" add constraint "vacay_user_years_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "vacay_years" add constraint "vacay_years_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
alter table "visited_countries" add constraint "visited_countries_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "visited_regions" add constraint "visited_regions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "wanderer_connections" add constraint "wanderer_connections_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
alter table "webauthn_challenges" add constraint "webauthn_challenges_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
alter table "webauthn_credentials" add constraint "webauthn_credentials_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
insert into "app_settings" ("key", "value") values ('app_version', '3.0.15'), ('places_photos_enabled', 'true'), ('places_autocomplete_enabled', 'true'), ('places_details_enabled', 'true');
insert into "addons" ("id", "name", "description", "type", "icon", "enabled", "config", "sort_order") values ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', '1', '{}', '6'), ('memories', 'Photos', NULL, 'trip', 'Image', '0', '{}', '7'), ('mcp', 'MCP', 'Model Context Protocol for AI assistant integration', 'integration', 'Terminal', '0', '{}', '12'), ('naver_list_import', 'Naver List Import', 'Import places from shared Naver Maps lists', 'integration', 'Link2', '1', '{}', '13'), ('journey', 'Journey', 'Trip tracking & travel journal — check-ins, photos, daily stories', 'global', 'Compass', '0', '{}', '35'), ('airtrail', 'AirTrail', 'Sync flights from your self-hosted AirTrail instance', 'integration', 'Plane', '0', '{}', '14'), ('collections', 'Collections', 'Personal place library — save places across trips into named lists, copy into any trip, share with others', 'global', 'Bookmark', '0', '{}', '16');
insert into "photo_providers" ("id", "name", "description", "icon", "enabled", "sort_order") values ('synologyphotos', 'Synology Photos', 'Synology Photos integration with separate account settings', 'Image', '0', '1');
insert into "photo_provider_fields" ("id", "provider_id", "field_key", "label", "input_type", "placeholder", "hint", "required", "secret", "settings_key", "payload_key", "sort_order") values ('1', 'synologyphotos', 'synology_url', 'providerUrl', 'url', 'https://synology.example.com', 'providerUrlHintSynology', '1', '0', 'synology_url', 'synology_url', '0'), ('2', 'synologyphotos', 'synology_username', 'providerUsername', 'text', 'Username', NULL, '1', '0', 'synology_username', 'synology_username', '1'), ('3', 'synologyphotos', 'synology_password', 'providerPassword', 'password', 'Password', NULL, '1', '1', NULL, 'synology_password', '2'), ('4', 'synologyphotos', 'synology_otp', 'providerOTP', 'text', '123456', NULL, '0', '0', NULL, 'synology_otp', '3'), ('5', 'synologyphotos', 'synology_skip_ssl', 'skipSSLVerification', 'checkbox', NULL, NULL, '0', '0', 'synology_skip_ssl', 'synology_skip_ssl', '4');
select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('"photo_provider_fields"', 'id') as seq, max("id") as max_id from "photo_provider_fields") ids where seq is not null;
insert into "document_providers" ("id", "name", "description", "icon", "enabled", "sort_order") values ('paperless', 'Paperless-ngx', 'Two-way document sync with a Paperless-ngx instance, scoped by tag', 'FileText', '0', '0'), ('papra', 'Papra', 'Two-way document sync with a Papra organisation, scoped by tag', 'FileText', '0', '1'), ('nextcloud', 'Nextcloud', 'Two-way document sync with a Nextcloud folder over WebDAV', 'Cloud', '0', '2'), ('opencloud', 'OpenCloud', 'Two-way document sync with an OpenCloud space over WebDAV', 'Cloud', '0', '3'), ('synologydrive', 'Synology Drive', 'Two-way document sync with a folder on a Synology NAS', 'HardDrive', '0', '4');
insert into "document_provider_fields" ("id", "provider_id", "field_key", "label", "input_type", "placeholder", "hint", "required", "secret", "sort_order") values ('1', 'paperless', 'base_url', 'providerUrl', 'url', 'https://paperless.example.com', NULL, '1', '0', '0'), ('2', 'paperless', 'api_token', 'providerApiToken', 'password', 'API token', 'hintPaperlessToken', '1', '1', '1'), ('3', 'paperless', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '2'), ('4', 'papra', 'base_url', 'providerUrl', 'url', 'https://papra.example.com', NULL, '1', '0', '0'), ('5', 'papra', 'api_key', 'providerApiKey', 'password', 'ppapi_…', 'hintPapraKey', '1', '1', '1'), ('6', 'papra', 'organization_id', 'providerOrganization', 'text', 'org_…', 'hintPapraOrg', '1', '0', '2'), ('7', 'papra', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '3'), ('8', 'nextcloud', 'base_url', 'providerUrl', 'url', 'https://cloud.example.com', NULL, '1', '0', '0'), ('9', 'nextcloud', 'login_name', 'providerUsername', 'text', 'username', 'hintNextcloudLogin', '1', '0', '1'), ('10', 'nextcloud', 'app_password', 'providerAppPassword', 'password', 'app password', 'hintNextcloudAppPassword', '1', '1', '2'), ('11', 'nextcloud', 'base_path', 'providerBasePath', 'text', '/TREK', 'hintBasePath', '0', '0', '3'), ('12', 'nextcloud', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '4'), ('13', 'opencloud', 'base_url', 'providerUrl', 'url', 'https://opencloud.example.com', NULL, '1', '0', '0'), ('14', 'opencloud', 'username', 'providerUsername', 'text', 'username', NULL, '1', '0', '1'), ('15', 'opencloud', 'app_token', 'providerAppToken', 'password', 'app token', 'hintOpenCloudToken', '1', '1', '2'), ('16', 'opencloud', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '3'), ('17', 'synologydrive', 'base_url', 'providerUrl', 'url', 'https://nas.example.com:5001', 'hintSynologyUrl', '1', '0', '0'), ('18', 'synologydrive', 'username', 'providerUsername', 'text', 'username', 'hintSynologyUser', '1', '0', '1'), ('19', 'synologydrive', 'password', 'providerPassword', 'password', 'password', NULL, '1', '1', '2'), ('20', 'synologydrive', 'otp_code', 'providerOTP', 'text', '123456', 'hintSynologyOtp', '0', '1', '3'), ('21', 'synologydrive', 'base_path', 'providerBasePath', 'text', '/trek', 'hintBasePath', '0', '0', '4'), ('22', 'synologydrive', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '5');
select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('"document_provider_fields"', 'id') as seq, max("id") as max_id from "document_provider_fields") ids where seq is not null;
insert into "tour_types" ("key", "label_key", "icon", "color", "routing_profile", "is_sport", "enabled", "sort_order") values ('hike', 'tourTypes.hike', 'Mountain', '#16a34a', 'pedestrian', '1', '1', '0'), ('bike', 'tourTypes.bike', 'Bike', '#2563eb', 'bicycle', '1', '1', '1'), ('run', 'tourTypes.run', 'Footprints', '#dc2626', 'pedestrian', '1', '1', '2'), ('ski', 'tourTypes.ski', 'MountainSnow', '#0891b2', NULL, '1', '1', '3'), ('kayak', 'tourTypes.kayak', 'Sailboat', '#0d9488', NULL, '1', '1', '4'), ('walk', 'tourTypes.walk', 'Landmark', '#9333ea', 'pedestrian', '0', '1', '5'), ('food', 'tourTypes.food', 'UtensilsCrossed', '#ea580c', 'pedestrian', '0', '0', '6'), ('horse', 'tourTypes.horse', 'Horseshoe', '#a16207', NULL, '1', '1', '7');
CREATE FUNCTION trg_release_stop_on_stay_delete() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
UPDATE day_assignments SET accommodation_id = NULL WHERE accommodation_id = OLD.id;
RETURN OLD;
END
$$;
CREATE TRIGGER trg_release_stop_on_stay_delete AFTER DELETE ON day_accommodations FOR EACH ROW EXECUTE FUNCTION trg_release_stop_on_stay_delete();
CREATE FUNCTION trg_place_regions_follow_place() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
DELETE FROM place_regions WHERE place_id = NEW.id;
RETURN NEW;
END
$$;
CREATE TRIGGER trg_place_regions_follow_place AFTER UPDATE OF lat, lng, address ON places FOR EACH ROW WHEN (OLD.lat IS DISTINCT FROM NEW.lat OR OLD.lng IS DISTINCT FROM NEW.lng OR OLD.address IS DISTINCT FROM NEW.address) EXECUTE FUNCTION trg_place_regions_follow_place();
+2
View File
@@ -37,6 +37,8 @@
"check:entities": "node --import tsx scripts/generate-entities.ts --check",
"gen:db-types": "node --import tsx scripts/generate-db-types.ts",
"check:db-types": "node --import tsx scripts/generate-db-types.ts --check",
"gen:pg-baseline": "node --import tsx scripts/generate-pg-baseline.ts",
"check:pg-baseline": "node --import tsx scripts/generate-pg-baseline.ts --check",
"probe:pg": "node --import tsx scripts/pg-probe.ts",
"format": "prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\"",
+182
View File
@@ -0,0 +1,182 @@
/**
* Generates the Postgres baseline: the schema a fresh Postgres database starts
* from (src/db/engine/postgres/baseline.ts says how a boot uses it).
*
* The entities describe the migrated SQLite schema and are pinned to it
* (`check:entities`), so the baseline is MikroORM's schema generator over the
* entities, for the Postgres platform, after the adjustments every Postgres
* schema in this repository shares (src/db/engine/postgres/schema-adjust.ts):
* TEXT timestamps, portable defaults, the `nocase` collation. Unlike the
* probe's schema it keeps the foreign keys. No database is needed: the
* generator reads only the metadata and the platform.
*
* The baseline stands for every migration up to the newest one when it was
* generated (`through`). Once a migration lands after it, the baseline is
* frozen like a shipped migration: the newer migration runs on Postgres
* through the migrator, and `--check` only verifies the manifest.
*
* Usage:
* node --import tsx scripts/generate-pg-baseline.ts # rewrite server/assets/postgres/
* node --import tsx scripts/generate-pg-baseline.ts --check # exit 1 when it drifted (CI)
*/
import { baselineMatches, readPostgresBaseline, writePostgresBaseline, type PostgresBaseline } from '../src/db/engine/postgres/baseline';
import {
adjustColumns,
NOCASE_COLLATION_SQL,
POSTGRES_TRIGGERS,
splitStatements,
type ColumnMeta,
} from '../src/db/engine/postgres/schema-adjust';
import { ALL_ENTITIES } from '../src/db/entities';
import { knownMigrationNames } from '../src/db/known-migrations';
import type { EntityProperty } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/postgresql';
import { migrateTempDb, tempDbPath } from './generate-entities';
import Database from 'better-sqlite3';
import fs from 'node:fs';
/** The baseline the entities and the migrations on disk describe now. */
export async function generatePostgresBaseline(known: Set<string> = knownMigrationNames()): Promise<PostgresBaseline> {
const migrations = [...known].sort();
const through = migrations.at(-1);
if (!through) throw new Error('no migrations found');
const orm = await MikroORM.init({
// Never contacted: init() only discovers metadata, and the schema generator needs nothing else.
clientUrl: 'postgresql://generator@localhost/trek',
entities: [...ALL_ENTITIES],
discovery: { warnWhenNoEntities: false },
});
try {
for (const meta of orm.getMetadata().getAll().values()) adjustColumns(meta.props as EntityProperty[] as ColumnMeta[]);
const migrated = await readMigratedSqlite();
const statements = [
NOCASE_COLLATION_SQL,
...splitStatements(await orm.schema.getCreateSchemaSQL({ wrap: false })),
...migrated.tables.flatMap((table) => rowStatements(table.name, table.rows)),
...Object.values(POSTGRES_TRIGGERS).flat(),
];
return { through, migrations, statements };
} finally {
await orm.close();
}
}
/**
* What `--check` holds. While no migration is newer than the committed
* baseline, the baseline must be exactly what the entities generate. Once one
* is, the baseline is frozen and only its manifest is checked: every migration
* it names exists, and it names every migration up to `through`.
*/
export function checkBaseline(committed: PostgresBaseline, generated: PostgresBaseline, matches: boolean): string[] {
const known = new Set(generated.migrations);
const problems: string[] = [];
const missing = committed.migrations.filter((name) => !known.has(name));
if (missing.length > 0) problems.push(`the baseline names migrations that do not exist: ${missing.join(', ')}`);
const unlisted = generated.migrations.filter((name) => name <= committed.through && !committed.migrations.includes(name));
if (unlisted.length > 0) problems.push(`migrations up to ${committed.through} are missing from it: ${unlisted.join(', ')}`);
if (committed.through === generated.through && !matches) {
problems.push('the entities generate a different schema; run npm run gen:pg-baseline');
}
return problems;
}
/** Migration bookkeeping: the baseline's manifest stands for it on Postgres. */
const BOOKKEEPING_TABLES = new Set(['mikro_orm_migrations', 'migrations', 'schema_version']);
type Row = Record<string, unknown>;
/** What the migrations leave in a SQLite database: its triggers, and the rows they insert, table by table in creation order. */
async function readMigratedSqlite(): Promise<{ triggers: string[]; tables: Array<{ name: string; rows: Row[] }> }> {
const dbPath = tempDbPath();
try {
await migrateTempDb(dbPath);
const conn = new Database(dbPath, { readonly: true });
try {
const objects = conn
.prepare("select type, name from sqlite_master where type in ('table', 'trigger') and name not like 'sqlite_%' order by rowid")
.all() as Array<{ type: string; name: string }>;
const tables = objects
.filter((object) => object.type === 'table' && !BOOKKEEPING_TABLES.has(object.name))
.map((object) => ({ name: object.name, rows: conn.prepare(`select * from "${object.name}" order by rowid`).all() as Row[] }))
.filter((table) => table.rows.length > 0);
const triggers = objects.filter((object) => object.type === 'trigger').map((object) => object.name).sort();
return { triggers, tables };
} finally {
conn.close();
}
} finally {
fs.rmSync(dbPath, { force: true });
}
}
/** A value as a Postgres literal the column's own type takes in: quoted text, which Postgres casts on insert. */
function literal(value: unknown): string {
if (value === null || value === undefined) return 'NULL';
if (Buffer.isBuffer(value)) throw new Error('a migration inserted binary data, which the baseline cannot carry');
return `'${String(value).replace(/'/g, "''")}'`;
}
/**
* The rows a migration inserted into `table` (reference data such as the tour
* types and the provider catalogues), as the statements that put them in a
* Postgres database the baseline creates, then move the table's id sequence,
* if it has one, past them. A migration up to the cut never runs on Postgres,
* so without these the database would start without what every SQLite
* install has before its first seeder.
*/
export function rowStatements(table: string, rows: readonly Row[]): string[] {
if (rows.length === 0) return [];
const columns = Object.keys(rows[0]);
const values = rows.map((row) => `(${columns.map((column) => literal(row[column])).join(', ')})`);
const statements = [`insert into "${table}" (${columns.map((c) => `"${c}"`).join(', ')}) values ${values.join(', ')}`];
// A text key (addons.id) has no sequence; a numeric one may.
if (rows.every((row) => typeof row.id === 'number')) {
statements.push(
`select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('"${table}"', 'id') as seq, ` +
`max("id") as max_id from "${table}") ids where seq is not null`,
);
}
return statements;
}
/**
* The SQLite triggers without a Postgres port in `POSTGRES_TRIGGERS`, and the
* ports whose trigger is gone. The entities carry no triggers, so this is
* what keeps the hand-written ports level with the migrations.
*/
export function triggerPortProblems(sqliteTriggers: readonly string[], ported: readonly string[]): string[] {
const problems: string[] = [];
const missing = sqliteTriggers.filter((name) => !ported.includes(name));
if (missing.length > 0) problems.push(`SQLite triggers without a Postgres port in POSTGRES_TRIGGERS: ${missing.join(', ')}`);
const stale = ported.filter((name) => !sqliteTriggers.includes(name));
if (stale.length > 0) problems.push(`POSTGRES_TRIGGERS ports triggers the migrations no longer create: ${stale.join(', ')}`);
return problems;
}
async function main(): Promise<void> {
const generated = await generatePostgresBaseline();
if (!process.argv.slice(2).includes('--check')) {
writePostgresBaseline(generated);
console.log(`[generate-pg-baseline] wrote ${generated.statements.length} statements through ${generated.through}`);
return;
}
const committed = readPostgresBaseline();
const problems = checkBaseline(committed, generated, baselineMatches(generated));
// Once frozen, a later migration's trigger reaches Postgres through the migrator, not this list.
if (committed.through === generated.through) {
problems.push(...triggerPortProblems((await readMigratedSqlite()).triggers, Object.keys(POSTGRES_TRIGGERS)));
}
if (problems.length > 0) {
for (const problem of problems) console.error(`[generate-pg-baseline] ${problem}`);
process.exit(1);
}
console.log('[generate-pg-baseline] --check: the Postgres baseline matches the entities and the migrations');
}
if (require.main === module) {
main().catch((error: unknown) => {
console.error(error);
process.exit(1);
});
}
+1 -1
View File
@@ -6,7 +6,7 @@
* repositories. Nothing tested that claim until this probe. Given an empty
* Postgres database it
*
* 1. derives a Postgres schema from the entities (pg-probe/schema.ts);
* 1. derives a Postgres schema from the entities (src/db/engine/postgres/schema-adjust.ts);
* 2. runs every dialect helper on SQLite and on Postgres and checks both
* return what the helper promises (pg-probe/helper-cases.ts); every
* case must pass;
+1 -1
View File
@@ -18,7 +18,7 @@ import {
} from './helper-cases';
import { ProbePostgresDialect, type StatementRecorder } from './recorder';
import type { MethodResult } from './report';
import { adjustColumns, NOCASE_COLLATION_SQL, splitStatements, type ColumnMeta } from './schema';
import { adjustColumns, NOCASE_COLLATION_SQL, splitStatements, type ColumnMeta } from '../../src/db/engine/postgres/schema-adjust';
import { RequestContext, type Configuration, type EntityManager, type EntityProperty } from '@mikro-orm/core';
import { MikroORM, PostgreSqlConnection, PostgreSqlDriver, type Options } from '@mikro-orm/postgresql';
import { SqlitePlatform } from '@mikro-orm/sql';
-106
View File
@@ -1,106 +0,0 @@
/**
* The Postgres schema the probe runs against, derived from the entities.
*
* The entities are generated from the migrated SQLite schema and a parity
* test pins them to it (`npm run check:entities`), so they are the one
* description of the tables both engines can read. MikroORM's schema
* generator turns them into Postgres DDL after three adjustments that keep
* the probe about the SQL the repositories send, not about the storage
* decisions a real Postgres port still has to make:
*
* - timestamps stay TEXT, the storage model the services and the dialect
* helpers are written for (server/CLAUDE.md, "Storage model");
* - a SQLite-only default (`datetime('now')`, `strftime('%s','now')`) gets
* its Postgres equivalent, and a column declared `COLLATE NOCASE` uses
* the `nocase` collation `collateNoCase()` names on Postgres;
* - no foreign keys, so a statement is never refused only because the
* sample row it writes points at nothing (every statement meets empty
* tables).
*
* Unique and partial unique indexes stay, because `ON CONFLICT` needs them.
*/
import { pgTimestampText, PG_UTC_NOW } from '../../src/db/dialect/platform';
/** SQLite's timestamp text on Postgres, for a column default. */
export const PG_NOW_TEXT_DEFAULT = pgTimestampText(PG_UTC_NOW);
/** The case-insensitive collation `collateNoCase()` names on Postgres. */
export const NOCASE_COLLATION_SQL =
"CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)";
/** The Postgres spelling of a column default the entities carry in SQLite's. */
export function portableDefault(raw: string): string {
const text = raw
.trim()
.replace(/^\((.*)\)$/s, '$1')
.trim();
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
return raw;
}
/**
* Splits generated DDL into single statements on `;` outside quotes, so one
* statement Postgres refuses does not take the rest of the schema with it.
*/
export function splitStatements(sql: string): string[] {
const statements: string[] = [];
let current = '';
let quote: '"' | "'" | null = null;
for (const char of sql) {
if (quote) {
if (char === quote) quote = null;
current += char;
} else if (char === "'" || char === '"') {
quote = char;
current += char;
} else if (char === ';') {
if (current.trim()) statements.push(current.trim());
current = '';
} else {
current += char;
}
}
if (current.trim()) statements.push(current.trim());
return statements.filter((statement) => !/^set\s/i.test(statement));
}
/** The subset of MikroORM's property metadata the schema adjustments touch. */
export interface ColumnMeta {
name: string;
defaultRaw?: string;
collation?: string;
columnTypes?: string[];
customType?: { constructor: { name: string } };
}
/**
* Applies the adjustments above to one entity's properties in place:
* timestamp columns become `text`, SQLite-only defaults and the NOCASE
* collation their Postgres spelling. Returns the names of the properties
* it changed, for the log.
*/
export function adjustColumns(properties: readonly ColumnMeta[]): string[] {
const changed: string[] = [];
for (const property of properties) {
let touched = false;
if (property.customType?.constructor.name === 'DbTimestampType' && property.columnTypes) {
property.columnTypes = property.columnTypes.map(() => 'text');
touched = true;
}
if (typeof property.defaultRaw === 'string') {
const next = portableDefault(property.defaultRaw);
if (next !== property.defaultRaw) {
property.defaultRaw = next;
touched = true;
}
}
if (property.collation?.toUpperCase() === 'NOCASE') {
property.collation = 'nocase';
touched = true;
}
if (touched) changed.push(property.name);
}
return changed;
}
+5 -13
View File
@@ -105,10 +105,6 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
);
}
/** Why a boot with TREK_DB_URL is refused until the Postgres engine can run TREK. */
export const POSTGRES_NOT_READY =
'Postgres support is not complete in this release; unset TREK_DB_URL to run on the SQLite file.';
/** The SQLite settings that mean nothing next to TREK_DB_URL. */
const SQLITE_ONLY_DB_KEYS = ['TREK_DB_FILE', 'TREK_DB_JOURNAL_MODE', 'TREK_DB_SYNCHRONOUS'] as const;
@@ -120,16 +116,12 @@ const SQLITE_ONLY_DB_KEYS = ['TREK_DB_FILE', 'TREK_DB_JOURNAL_MODE', 'TREK_DB_SY
*/
function databasePreconditions(raw: RawEnv): string[] {
if (!raw.TREK_DB_URL?.trim()) return [];
const problems: string[] = [];
const sqliteKeys = SQLITE_ONLY_DB_KEYS.filter((key) => raw[key]?.trim());
if (sqliteKeys.length > 0) {
problems.push(
` - ambiguous database configuration: TREK_DB_URL is set together with ${sqliteKeys.join(', ')}, ` +
'which only apply to the SQLite file. Unset one side.',
);
}
problems.push(` - TREK_DB_URL: ${POSTGRES_NOT_READY}`);
return problems;
if (sqliteKeys.length === 0) return [];
return [
` - ambiguous database configuration: TREK_DB_URL is set together with ${sqliteKeys.join(', ')}, ` +
'which only apply to the SQLite file. Unset one side.',
];
}
/**
+28
View File
@@ -0,0 +1,28 @@
import { isPostgres, isSqlite, unsupported } from './platform';
import type { Platform } from '@mikro-orm/core';
/**
* The schema catalog, for the migrations' helpers (`db/migration-utils.ts`):
* which tables and columns exist, each spelled the way its engine keeps them.
* Both statements take the table name as their one bound parameter and answer
* one row per hit with the name in `name`. Postgres reads the current schema
* only, the one TREK's own tables live in.
*/
/** Lists the columns of the table bound as `?`, one `name` per row; none for a missing table. */
export function columnNamesSql(platform: Platform): string {
if (isSqlite(platform)) return 'select name from pragma_table_info(?)';
if (isPostgres(platform)) {
return 'select column_name as name from information_schema.columns where table_schema = current_schema() and table_name = ?';
}
return unsupported(platform);
}
/** One row when the table bound as `?` exists, none otherwise. */
export function tableExistsSql(platform: Platform): string {
if (isSqlite(platform)) return "select name from sqlite_master where type = 'table' and name = ?";
if (isPostgres(platform)) {
return 'select table_name as name from information_schema.tables where table_schema = current_schema() and table_name = ?';
}
return unsupported(platform);
}
+10 -5
View File
@@ -18,13 +18,18 @@ export async function ensureEmailCaseIndex(connection: Connection): Promise<void
const pending: unknown[] = await connection.execute(`SELECT value FROM app_settings WHERE key = ?`, [PENDING_KEY]);
if (pending.length === 0) return;
const duplicates: Array<{ ids: string }> = await connection.execute(
`SELECT group_concat(id, ', ') AS ids FROM (SELECT id, email FROM users ORDER BY id) GROUP BY lower(email) HAVING COUNT(*) > 1`,
// Grouped here rather than with group_concat, which Postgres spells string_agg.
const rows: Array<{ id: number; email_key: string }> = await connection.execute(
`SELECT id, lower(email) AS email_key FROM users WHERE lower(email) IN ` +
`(SELECT lower(email) FROM users GROUP BY lower(email) HAVING COUNT(*) > 1) ORDER BY id`,
);
if (duplicates.length > 0) {
const duplicates = new Map<string, number[]>();
for (const row of rows) duplicates.set(row.email_key, [...(duplicates.get(row.email_key) ?? []), row.id]);
if (duplicates.size > 0) {
const ids = [...duplicates.values()].map((group) => group.join(', '));
console.warn(
`[DB] ${duplicates.length} email address(es) still belong to more than one account when case is ignored ` +
`(user ids ${duplicates.map((row) => row.ids).join('; ')}), so users.email has no case-insensitive unique ` +
`[DB] ${duplicates.size} email address(es) still belong to more than one account when case is ignored ` +
`(user ids ${ids.join('; ')}), so users.email has no case-insensitive unique ` +
'index yet. Give each of those accounts its own address under Admin > Users; the next start creates it.',
);
return;
+24 -7
View File
@@ -1,23 +1,40 @@
import type { AnyOrm } from '../orm';
import type { Options } from '@mikro-orm/core';
/** The databases TREK can be pointed at. MySQL/MariaDB are out of scope (server/CLAUDE.md). */
type EngineId = 'sqlite' | 'postgres';
/**
* One database engine: what the ORM needs to reach it and how to name it in a
* log line. Code that differs by engine dispatches through this, or through
* the helpers in `db/dialect/`, never through its own platform check
* (`lint:engine-dispatch`).
* One database engine: what the ORM needs to reach it, how the connection
* opens, closes and comes back after a restore, and how a database is brought
* to the current schema. Code that differs by engine dispatches through this,
* or through the helpers in `db/dialect/`, never through its own platform
* check (`lint:engine-dispatch`).
*
* Free of Nest like every other file under `db/`: `src/db` does not import
* `src/nest` (`lint:boundaries`).
* `src/nest` (`lint:boundaries`). `DatabaseLifecycle` is the provider that
* calls it.
*/
export interface DatabaseEngine {
readonly id: EngineId;
/** Whether this release can run TREK on the engine; `buildOrmConfig` refuses one that cannot. */
readonly ready: boolean;
/** For log lines and errors: the file path, or the URL without its password. */
describe(): string;
/** What MikroORM needs to reach the database: the driver and its target, the pool, driver options. */
ormOptions(): Partial<Options>;
/**
* Called once at boot, before the schema bootstrap. `onReopened` is what
* has to follow a later reopen (rebinding the ORM, migrating the restored
* database forward).
*/
open(onReopened: () => Promise<void>): void;
/** Closes what the engine itself holds; the ORM's own pool is closed with the Nest container. */
close(): void;
/** Comes back after the database was replaced by a restore, then runs `onReopened`. */
reopen(): Promise<void>;
/**
* Brings the database to the current schema, then seeds it. `snapshot:
* false` skips the copy taken before pending migrations (a restore, whose
* archive is the copy).
*/
schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void>;
}
+1 -4
View File
@@ -1,5 +1,4 @@
import { readEnv } from '../../app-config';
import { POSTGRES_NOT_READY } from '../../app-config/env';
import { ALL_ENTITIES } from '../entities';
import type { DatabaseEngine } from './engine';
import { PostgresEngine } from './postgres/postgres-engine';
@@ -25,11 +24,9 @@ export function resolveEngine(db: ReturnType<typeof readEnv>['db'] = readEnv().d
* The MikroORM config for `engine`: what every engine shares (entities,
* migrations, seeders) and what the engine adds. `src/mikro-orm.config.ts`
* exports it for the CLI and the Nest container, so both reach the same
* database. An engine this release cannot run is refused here, before
* anything connects; the boot check refuses it earlier with the same words.
* database.
*/
export function buildOrmConfig(engine: DatabaseEngine): Options {
if (!engine.ready) throw new Error(`${POSTGRES_NOT_READY} (${engine.describe()})`);
return defineConfig({
entities: ALL_ENTITIES,
extensions: [Migrator, SeedManager],
+84
View File
@@ -0,0 +1,84 @@
import { splitStatements } from './schema-adjust';
import fs from 'node:fs';
import path from 'node:path';
/**
* Where the Postgres baseline lives: `server/assets/postgres/`, which the
* Docker image copies beside `dist/` (the same place the airports and atlas
* data are read from), reached the same way from `src/` and from `dist/`.
*/
const BASELINE_DIR = path.join(__dirname, '..', '..', '..', '..', 'assets', 'postgres');
const SQL_FILE = 'baseline.sql';
const MANIFEST_FILE = 'baseline.json';
/** The manifest beside the SQL: the last migration the baseline stands for, and every migration it replaces. */
interface BaselineManifest {
through: string;
migrations: string[];
}
/**
* The schema a fresh Postgres database starts from.
*
* The 331 migrations up to `through` are written in SQLite and frozen, so a
* Postgres database does not replay them: it runs these statements, generated
* from the entities (`npm run gen:pg-baseline`), and records every migration
* in `migrations` as executed in the same transaction. Migrations after
* `through` run on both engines through the migrator.
*/
export interface PostgresBaseline extends BaselineManifest {
statements: string[];
}
/** The two files a baseline is written as, ready to compare or write. */
export function renderBaseline(baseline: PostgresBaseline): { sql: string; manifest: string } {
return {
sql:
'-- The schema a fresh Postgres database starts from. Generated by `npm run gen:pg-baseline`; do not edit.\n' +
baseline.statements.map((statement) => `${statement};\n`).join(''),
manifest: `${JSON.stringify({ through: baseline.through, migrations: baseline.migrations }, null, 2)}\n`,
};
}
function parseManifest(text: string, file: string): BaselineManifest {
const data: unknown = JSON.parse(text);
const manifest = data as Partial<BaselineManifest>;
const valid =
typeof manifest.through === 'string' &&
Array.isArray(manifest.migrations) &&
manifest.migrations.length > 0 &&
manifest.migrations.every((name) => typeof name === 'string') &&
manifest.migrations.includes(manifest.through);
if (!valid) throw new Error(`${file} must name "through" and list it among "migrations"`);
return { through: manifest.through as string, migrations: manifest.migrations as string[] };
}
/** Reads the committed baseline; a missing or malformed one throws, so a boot cannot start from half a schema. */
export function readPostgresBaseline(dir = BASELINE_DIR): PostgresBaseline {
const manifestFile = path.join(dir, MANIFEST_FILE);
const manifest = parseManifest(fs.readFileSync(manifestFile, 'utf8'), manifestFile);
const statements = splitStatements(fs.readFileSync(path.join(dir, SQL_FILE), 'utf8').replace(/^--[^\n]*\n/gm, ''));
if (statements.length === 0) throw new Error(`${path.join(dir, SQL_FILE)} holds no statements`);
// The boot sends the baseline as one statement without parameters, where a `?` would be read as a binding.
if (statements.some((statement) => statement.includes('?'))) {
throw new Error(`${path.join(dir, SQL_FILE)} holds a "?", which the boot would read as a parameter`);
}
return { ...manifest, statements };
}
/** Writes the two files (the generator's `--write`). */
export function writePostgresBaseline(baseline: PostgresBaseline, dir = BASELINE_DIR): void {
const { sql, manifest } = renderBaseline(baseline);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, SQL_FILE), sql);
fs.writeFileSync(path.join(dir, MANIFEST_FILE), manifest);
}
/** Whether the committed files are what `baseline` renders to (the generator's `--check`). */
export function baselineMatches(baseline: PostgresBaseline, dir = BASELINE_DIR): boolean {
const { sql, manifest } = renderBaseline(baseline);
const read = (file: string) =>
fs.existsSync(path.join(dir, file)) ? fs.readFileSync(path.join(dir, file), 'utf8') : null;
return read(SQL_FILE) === sql && read(MANIFEST_FILE) === manifest;
}
@@ -0,0 +1,58 @@
import { type Configuration } from '@mikro-orm/core';
import { PostgreSqlConnection, PostgreSqlDriver } from '@mikro-orm/postgresql';
/** The `pg` type id of `bigint` (`int8`): every integer column and every `count(*)` on Postgres. */
const INT8_OID = 20;
/**
* Reads a `bigint` as a JavaScript number, the way better-sqlite3 hands
* SQLite's 64-bit INTEGER to the services. `pg` returns it as a string to
* keep precision past 2^53; no TREK value comes near that (ids, counts,
* epoch milliseconds, cents), so one that does is refused rather than
* rounded.
*/
export function parseInt8(text: string): number {
const value = Number(text);
if (!Number.isSafeInteger(value)) throw new Error(`A bigint of ${text} is beyond what TREK reads exactly (2^53).`);
return value;
}
/** The `pg` type id of `numeric`: what `sum()` of a bigint and `avg()` answer. */
const NUMERIC_OID = 1700;
/**
* Reads a `numeric` as a number, as SQLite answers `sum()` and `avg()`. An
* integral result past 2^53 is refused like a bigint; a fraction is a double,
* the precision SQLite's REAL has.
*/
export function parseNumeric(text: string): number {
const value = Number(text);
if (!Number.isFinite(value) || (/^-?\d+$/.test(text) && !Number.isSafeInteger(value))) {
throw new Error(`A numeric of ${text} is beyond what TREK reads exactly (2^53).`);
}
return value;
}
/** The pool's own parsers (MikroORM keeps dates as text), plus `int8` and `numeric` as numbers. */
class Int8NumberConnection extends PostgreSqlConnection {
override mapOptions(overrides: Parameters<PostgreSqlConnection['mapOptions']>[0]) {
const options = super.mapOptions(overrides);
const types = options.types as { setTypeParser(oid: number, parse: (text: string) => unknown): void };
types.setTypeParser(INT8_OID, parseInt8);
types.setTypeParser(NUMERIC_OID, parseNumeric);
return options;
}
}
/**
* MikroORM's Postgres driver on a connection that reads `bigint` as a number.
* The parsers belong to this pool only: nothing global in `pg` changes.
*/
export class TrekPostgreSqlDriver extends PostgreSqlDriver {
constructor(config: Configuration) {
super(config);
// PostgreSqlDriver's constructor hardcodes its connection class, as
// SqliteDriver's does (`db/orm-driver.ts`); replaced before anything connects.
(this as unknown as { connection: PostgreSqlConnection }).connection = new Int8NumberConnection(config);
}
}
@@ -1,6 +1,8 @@
import { finishSchemaBootstrap, type AnyOrm } from '../../orm';
import type { DatabaseEngine } from '../engine';
import { redactUrl } from '../redact-url';
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
import { TrekPostgreSqlDriver } from './postgres-driver';
import { bootstrapPostgresSchema, defaultPostgresBootstrapDeps, type PostgresBootstrapDeps } from './schema-bootstrap';
import { readFileSync } from 'node:fs';
@@ -54,14 +56,34 @@ export function sslOptionFor(url: string): PgSslOption | undefined {
/**
* The Postgres engine: MikroORM's own `pg` driver on `TREK_DB_URL`, with a
* pool of at most `TREK_DB_POOL_MAX` connections that keeps none open while
* idle. Not ready in this release: `buildOrmConfig` refuses it until the
* engine can bring a database to the schema.
* idle. The pool belongs to the ORM, which the Nest container closes; the
* schema comes from the baseline plus the migrations after it
* (`schema-bootstrap.ts`).
*/
export class PostgresEngine implements DatabaseEngine {
readonly id = 'postgres';
readonly ready = false;
constructor(private readonly settings: PostgresSettings) {}
constructor(
private readonly settings: PostgresSettings,
private readonly bootstrapDeps: () => PostgresBootstrapDeps = defaultPostgresBootstrapDeps,
) {}
open(): void {
// Nothing of its own to open: the ORM connects the pool.
}
close(): void {
// Nothing of its own to close: the pool goes with the ORM.
}
reopen(): Promise<void> {
return Promise.reject(new Error('Restoring a backup into a Postgres database is not available in this release.'));
}
async schemaBootstrap(orm: AnyOrm): Promise<void> {
await bootstrapPostgresSchema(orm, this.bootstrapDeps());
await finishSchemaBootstrap(orm);
}
describe(): string {
return `Postgres ${redactUrl(this.settings.url)}`;
@@ -70,7 +92,7 @@ export class PostgresEngine implements DatabaseEngine {
ormOptions() {
const ssl = sslOptionFor(this.settings.url);
return {
driver: PostgreSqlDriver,
driver: TrekPostgreSqlDriver,
clientUrl: this.settings.url,
pool: { min: 0, max: this.settings.poolMax },
driverOptions: ssl === undefined ? {} : { ssl },
@@ -0,0 +1,164 @@
/**
* How the entities' schema is written in Postgres: the one definition the
* Postgres baseline (`scripts/generate-pg-baseline.ts`), the schema parity
* check and the probe (`scripts/pg-probe.ts`) share.
*
* The entities are generated from the migrated SQLite schema and a parity
* test pins them to it (`npm run check:entities`), so they are the one
* description of the tables both engines can read. MikroORM's schema
* generator turns them into Postgres DDL after the adjustments below, which
* keep the storage model the services and the dialect helpers are written
* for (server/CLAUDE.md, "Storage model"):
*
* - timestamps stay TEXT;
* - an INTEGER column is `bigint`: SQLite's INTEGER holds 64 bits, so a
* column written with epoch milliseconds or a byte count past 2 GB would
* overflow Postgres's 32-bit `integer` (the engine's driver reads
* `bigint` back as a number, `postgres-driver.ts`);
* - a SQLite-only default (`datetime('now')`, `strftime('%s','now')`,
* `CURRENT_TIMESTAMP` in a TEXT column) gets its Postgres equivalent, and
* a column declared `COLLATE NOCASE` uses the `nocase` collation
* `collateNoCase()` names on Postgres.
*
* The baseline keeps the foreign keys; the probe leaves them out, so a
* statement it sends is never refused only because the sample row it writes
* points at nothing.
*/
import { pgTimestampText, PG_UTC_NOW } from '../../dialect/platform';
/** SQLite's timestamp text on Postgres, for a column default. */
export const PG_NOW_TEXT_DEFAULT = pgTimestampText(PG_UTC_NOW);
/** The case-insensitive collation `collateNoCase()` names on Postgres. */
export const NOCASE_COLLATION_SQL =
"CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)";
/** The Postgres spelling of a column default the entities carry in SQLite's. */
export function portableDefault(raw: string): string {
const text = raw
.trim()
.replace(/^\((.*)\)$/s, '$1')
.trim();
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
return raw;
}
/**
* The SQLite schema's triggers, as Postgres writes them: a trigger function
* and the trigger that runs it, under the SQLite trigger's name. The entities
* describe tables only, so the baseline adds these after the tables, and
* `check:pg-baseline` fails while a trigger in the migrated SQLite schema has
* no entry here.
*/
export const POSTGRES_TRIGGERS: Readonly<Record<string, readonly string[]>> = {
// A deleted stay releases the day stops it claimed (no foreign key holds the link).
trg_release_stop_on_stay_delete: [
`CREATE FUNCTION trg_release_stop_on_stay_delete() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
UPDATE day_assignments SET accommodation_id = NULL WHERE accommodation_id = OLD.id;
RETURN OLD;
END
$$`,
'CREATE TRIGGER trg_release_stop_on_stay_delete AFTER DELETE ON day_accommodations ' +
'FOR EACH ROW EXECUTE FUNCTION trg_release_stop_on_stay_delete()',
],
// A place that moved or was renamed drops the region it was resolved to (#2527).
trg_place_regions_follow_place: [
`CREATE FUNCTION trg_place_regions_follow_place() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
DELETE FROM place_regions WHERE place_id = NEW.id;
RETURN NEW;
END
$$`,
'CREATE TRIGGER trg_place_regions_follow_place AFTER UPDATE OF lat, lng, address ON places FOR EACH ROW ' +
'WHEN (OLD.lat IS DISTINCT FROM NEW.lat OR OLD.lng IS DISTINCT FROM NEW.lng OR OLD.address IS DISTINCT FROM NEW.address) ' +
'EXECUTE FUNCTION trg_place_regions_follow_place()',
],
};
/**
* Splits generated DDL into single statements on `;` outside quotes and
* `$$` bodies, so one statement Postgres refuses does not take the rest of the
* schema with it.
*/
export function splitStatements(sql: string): string[] {
const statements: string[] = [];
let current = '';
let quote: '"' | "'" | '$$' | null = null;
for (let i = 0; i < sql.length; i++) {
const char = sql[i];
const dollar = sql.startsWith('$$', i);
if (quote === '$$') {
if (dollar) {
quote = null;
current += '$';
i++;
}
current += char;
} else if (quote) {
if (char === quote) quote = null;
current += char;
} else if (dollar) {
quote = '$$';
current += '$$';
i++;
} else if (char === "'" || char === '"') {
quote = char;
current += char;
} else if (char === ';') {
if (current.trim()) statements.push(current.trim());
current = '';
} else {
current += char;
}
}
if (current.trim()) statements.push(current.trim());
return statements.filter((statement) => !/^set\s/i.test(statement));
}
/** A column type SQLite stores as its 64-bit INTEGER. */
const INTEGER_TYPE = /^(integer|int)$/i;
/** The subset of MikroORM's property metadata the schema adjustments touch. */
export interface ColumnMeta {
name: string;
defaultRaw?: string;
collation?: string;
columnTypes?: string[];
customType?: { constructor: { name: string } };
}
/**
* Applies the adjustments above to one entity's properties in place:
* timestamp columns become `text`, integer columns `bigint`, SQLite-only defaults and the NOCASE
* collation their Postgres spelling. Returns the names of the properties
* it changed, for the log.
*/
export function adjustColumns(properties: readonly ColumnMeta[]): string[] {
const changed: string[] = [];
for (const property of properties) {
let touched = false;
if (property.customType?.constructor.name === 'DbTimestampType' && property.columnTypes) {
property.columnTypes = property.columnTypes.map(() => 'text');
touched = true;
} else if (property.columnTypes?.some((type) => INTEGER_TYPE.test(type))) {
property.columnTypes = property.columnTypes.map((type) => (INTEGER_TYPE.test(type) ? 'bigint' : type));
touched = true;
}
if (typeof property.defaultRaw === 'string') {
const next = portableDefault(property.defaultRaw);
if (next !== property.defaultRaw) {
property.defaultRaw = next;
touched = true;
}
}
if (property.collation?.toUpperCase() === 'NOCASE') {
property.collation = 'nocase';
touched = true;
}
if (touched) changed.push(property.name);
}
return changed;
}
@@ -0,0 +1,109 @@
import { readEnv, type AppEnv } from '../../../app-config';
import { knownMigrationNames } from '../../known-migrations';
import { migrationLabel, REFUSAL, refuseNewerDatabase, type MigrationSafetyNet } from '../../legacy-baseline';
import type { AnyOrm } from '../../orm';
import { readPostgresBaseline, type PostgresBaseline } from './baseline';
import type { Connection } from '@mikro-orm/core';
import type { Migrator } from '@mikro-orm/migrations';
import { Logger } from '@nestjs/common';
const logger = new Logger('DB');
/** What a Postgres bootstrap reads, passed in so a test can supply its own. */
export interface PostgresBootstrapDeps {
baseline: () => PostgresBaseline;
known: Set<string>;
safetyNet: MigrationSafetyNet;
}
/**
* The tables in the current schema. A database with no TREK migration history
* must hold none: TREK creates its schema in an empty database and never
* adopts tables something else made. Read before anything is written, so a
* refused database is left exactly as it was.
*/
async function currentTables(connection: Connection): Promise<string[]> {
const rows: Array<{ table_name: string }> = await connection.execute(
'select table_name from information_schema.tables where table_schema = current_schema() order by table_name',
);
return rows.map((row) => row.table_name);
}
/**
* Brings a Postgres database to the current schema.
*
* - No migration recorded and no table: the baseline runs and every migration
* it stands for is recorded as executed, in one transaction (DDL is
* transactional on Postgres, so the database ends with all of it or none).
* - No migration recorded but tables present: refused, naming a few of them.
* - Migrations recorded: refused when one is unknown to this build (a newer
* TREK migrated it), else the pending migrations run, after the safety net.
* A database the baseline just created runs the migrations after the
* baseline's cut without it: there is nothing yet to lose.
*/
export async function bootstrapPostgresSchema(orm: AnyOrm, deps: PostgresBootstrapDeps): Promise<void> {
const migrator = orm.config.getExtension('@mikro-orm/migrator') as Migrator;
const connection = orm.em.getConnection();
const storage = migrator.getStorage();
const historyTable = orm.config.get('migrations').tableName ?? 'mikro_orm_migrations';
const tables = await currentTables(connection);
const executed = tables.includes(historyTable) ? (await migrator.getExecuted()).map((row) => row.name) : [];
const created = executed.length === 0;
if (created) {
const foreign = tables.filter((table) => table !== historyTable);
if (foreign.length > 0) {
throw new Error(
`${REFUSAL} the database holds ${foreign.length} table(s) (${foreign.slice(0, 5).join(', ')}) but no TREK ` +
'migration history. Point TREK_DB_URL at an empty database.',
);
}
await storage.ensureTable();
const baseline = deps.baseline();
logger.log(`Creating the schema in an empty Postgres database (through ${migrationLabel(baseline.through)})`);
await connection.transactional(async (trx) => {
// One round trip: without parameters pg sends it as a simple query, which may hold many statements.
await connection.execute(baseline.statements.join(';\n'), [], 'run', trx);
await Promise.all(baseline.migrations.map((name) => storage.logMigration({ name }, trx)));
});
} else {
refuseNewerDatabase(executed, deps.known);
}
const pending = await migrator.getPending();
if (pending.length === 0) return;
// A database created just now holds nothing a migration could lose.
if (!created) await deps.safetyNet.beforeMigrate(migrationLabel([...executed].sort().at(-1) as string));
logger.log(`Applying ${pending.length} pending migration(s)`);
await migrator.up();
}
/**
* The Postgres safety net before pending migrations. This release cannot copy
* a Postgres database (the SQLite engine's `VACUUM INTO` has no Postgres
* equivalent short of `pg_dump`), so it refuses unless the operator turned
* the copy off: fail closed, rather than migrate with nothing to go back to.
* Off under NODE_ENV=test unless a suite asks for it, as on SQLite.
*/
export function postgresSafetyNet(env: () => AppEnv = readEnv): MigrationSafetyNet {
return {
async beforeMigrate() {
const { db, app } = env();
if (db.preMigrateSnapshot === undefined && app.isTest) return;
if (db.preMigrateSnapshot === false) {
logger.warn('TREK_DB_PRE_MIGRATE_SNAPSHOT is off: migrating the Postgres database without a copy');
return;
}
throw new Error(
`${REFUSAL} migrations are pending and TREK cannot copy a Postgres database before migrating it in this ` +
'release. Back it up with pg_dump, then start once with TREK_DB_PRE_MIGRATE_SNAPSHOT=false.',
);
},
restoreHint: async () => null,
};
}
/** What a production boot passes: the committed baseline, the migrations on disk, the safety net above. */
export function defaultPostgresBootstrapDeps(): PostgresBootstrapDeps {
return { baseline: readPostgresBaseline, known: knownMigrationNames(), safetyNet: postgresSafetyNet() };
}
+24 -2
View File
@@ -1,15 +1,18 @@
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../database';
import { resolveDbPath } from '../../db-path';
import { runSchemaBootstrap, type AnyOrm } from '../../orm';
import { SharedSqliteDriver } from '../../orm-driver';
import type { DatabaseEngine } from '../engine';
/**
* The SQLite file engine, TREK's default: one better-sqlite3 handle that
* `db/database.ts` owns and the ORM's bound driver shares (`db/orm-driver.ts`),
* on `TREK_DB_FILE` or `data/travel.db` (`:memory:` under test).
* on `TREK_DB_FILE` or `data/travel.db` (`:memory:` under test). A restore
* swaps the file and reopens the handle; the schema comes from the migration
* chain (`db/orm.ts`).
*/
export class SqliteEngine implements DatabaseEngine {
readonly id = 'sqlite';
readonly ready = true;
describe(): string {
return `SQLite file ${resolveDbPath()}`;
@@ -18,4 +21,23 @@ export class SqliteEngine implements DatabaseEngine {
ormOptions() {
return { driver: SharedSqliteDriver, dbName: resolveDbPath() };
}
open(onReopened: () => Promise<void>): void {
// Normally a no-op: the ORM's first connect inside NestFactory.create()
// already opened it. Said here so the boot does not depend on that.
getRawConnection();
registerReinitializeHook(onReopened);
}
close(): void {
closeDb();
}
reopen(): Promise<void> {
return reinitialize();
}
schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
return runSchemaBootstrap(orm, options);
}
}
+13 -11
View File
@@ -1,3 +1,5 @@
import { columnNamesSql, tableExistsSql } from './dialect/catalog';
import { TableNotFoundException } from '@mikro-orm/core';
import type { Migration } from '@mikro-orm/migrations';
/**
@@ -8,7 +10,7 @@ import type { Migration } from '@mikro-orm/migrations';
* a migration class.
*/
/** A single `pragma_table_info` row — only the column name is ever read. */
/** A catalog row (`dialect/catalog.ts`): only the name is ever read. */
interface ColumnRow {
name: string;
}
@@ -30,21 +32,18 @@ export async function addColumnIfMissing(
column: string,
definition: string,
): Promise<void> {
const existing = (await migration.execute('select name from pragma_table_info(?) where name = ?', [
table,
column,
])) as ColumnRow[];
if (existing.length > 0) return;
await migration.execute(`alter table \`${table}\` add column ${definition}`);
if ((await columnNames(migration, table)).has(column)) return;
const platform = migration.getEntityManager().getPlatform();
await migration.execute(`alter table ${platform.quoteIdentifier(table)} add column ${definition}`);
}
/** True when `table` exists in the current database. */
export async function tableExists(migration: Migration, table: string): Promise<boolean> {
const rows = await migration.execute(`select name from sqlite_master where type = 'table' and name = ?`, [table]);
const rows = await migration.execute(tableExistsSql(migration.getEntityManager().getPlatform()), [table]);
return rows.length > 0;
}
/** The `CREATE TABLE` DDL SQLite stored for `table`, or null when it does not exist. */
/** The `CREATE TABLE` DDL SQLite stored for `table`, or null when it does not exist. SQLite only: Postgres keeps no such text. */
export async function tableSql(migration: Migration, table: string): Promise<string | null> {
const rows = (await migration.execute(`select sql from sqlite_master where name = ?`, [table])) as {
sql: string | null;
@@ -68,7 +67,8 @@ export async function execBestEffort(migration: Migration, sql: string, params?:
/** The column names of `table`, or an empty set when the table does not exist. */
export async function columnNames(migration: Migration, table: string): Promise<Set<string>> {
const rows = (await migration.execute('select name from pragma_table_info(?)', [table])) as ColumnRow[];
const sql = columnNamesSql(migration.getEntityManager().getPlatform());
const rows = (await migration.execute(sql, [table])) as ColumnRow[];
return new Set(rows.map((r) => r.name));
}
@@ -80,7 +80,9 @@ export async function execUnlessTableMissing(migration: Migration, sql: string,
try {
await migration.execute(sql, params);
} catch (err: unknown) {
if (!(err instanceof Error) || !err.message.includes('no such table')) throw err;
const missing =
err instanceof TableNotFoundException || (err instanceof Error && err.message.includes('no such table'));
if (!missing) throw err;
}
}
+9 -25
View File
@@ -1,4 +1,3 @@
import mikroOrmConfig from '../mikro-orm.config';
import { withRequestContext } from '../nest/database/request-context';
import { runDemoSeed } from './database';
import { ensureEmailCaseIndex } from './email-case-index';
@@ -6,7 +5,6 @@ import { migrateToHead, NO_SAFETY_NET } from './legacy-baseline';
import { preMigrateSnapshot } from './pre-migrate-snapshot';
import type { AnyEntity, EntityClass, EntityManager, EntitySchema, IDatabaseDriver, MikroORM } from '@mikro-orm/core';
import type { Migrator } from '@mikro-orm/migrations';
import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
/**
* Schema ownership at startup.
@@ -52,8 +50,16 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
undefined,
snapshot ? preMigrateSnapshot(connection) : NO_SAFETY_NET,
);
await finishSchemaBootstrap(orm);
}
/**
* What every engine does once its schema is at head: the deferred index, the
* seeders, the demo seed. Idempotent, like the migration step before it.
*/
export async function finishSchemaBootstrap(orm: AnyOrm): Promise<void> {
// The one index a migration may have had to defer (see email-case-index.ts).
await ensureEmailCaseIndex(connection);
await ensureEmailCaseIndex(orm.em.getConnection());
const defaultSeeder = orm.config.get('seeder').defaultSeeder;
if (defaultSeeder) await orm.seeder.seedString(defaultSeeder);
@@ -77,25 +83,3 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
// fully-synchronous version had by construction.
await withRequestContext(orm, () => runDemoSeed());
}
/**
* An ORM instance outside Nest, for the vitest global setup that builds the
* schema snapshot. Production uses the container-owned one from
* `MikroOrmModule.forRoot()` instead of creating a second.
*/
export function createStandaloneOrm(): Promise<AnyOrm> {
return SqliteMikroORM.init({
...mikroOrmConfig,
// Entity discovery is skipped deliberately. Migrations and seeders are raw
// SQL and need no metadata, and the global setup that calls this runs as ESM
// in vitest's main process, where discovering `*.entity.ts` fails on Node's
// extensionless import resolution.
entities: [],
entitiesTs: [],
discovery: { warnWhenNoEntities: false },
// The migrator's per-migration progress log is production boot output; the
// global setup already reports the snapshot in one line of its own, and a
// failing migration still throws.
migrations: { ...mikroOrmConfig.migrations, silent: true },
});
}
+25
View File
@@ -0,0 +1,25 @@
import mikroOrmConfig from '../mikro-orm.config';
import type { AnyOrm } from './orm';
import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
/**
* An ORM instance outside Nest, for the vitest global setup that builds the
* schema snapshot. Production uses the container-owned one from
* `MikroOrmModule.forRoot()` instead of creating a second.
*/
export function createStandaloneOrm(): Promise<AnyOrm> {
return SqliteMikroORM.init({
...mikroOrmConfig,
// Entity discovery is skipped deliberately. Migrations and seeders are raw
// SQL and need no metadata, and the global setup that calls this runs as ESM
// in vitest's main process, where discovering `*.entity.ts` fails on Node's
// extensionless import resolution.
entities: [],
entitiesTs: [],
discovery: { warnWhenNoEntities: false },
// The migrator's per-migration progress log is production boot output; the
// global setup already reports the snapshot in one line of its own, and a
// failing migration still throws.
migrations: { ...mikroOrmConfig.migrations, silent: true },
});
}
@@ -1,11 +1,14 @@
import { DATABASE_BACKUP } from '../database/database-backup.interface';
import { resolveEngine } from '../../db/engine';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
import { DatabaseLifecycleModule } from '../database/database-lifecycle.module';
import { MaintenanceModule } from '../database/maintenance.module';
import { PostgresDatabaseBackup } from './postgres-database-backup';
import { SqliteDatabaseBackup } from './sqlite-database-backup';
import { Global, Module } from '@nestjs/common';
/**
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use.
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use
* (`TREK_DB_URL`, read at boot through `resolveEngine()`).
*
* Global because its consumers sit in two domains: the backup domain itself
* and the admin domain (the demo reset job and the baseline route). Admin
@@ -20,7 +23,16 @@ import { Global, Module } from '@nestjs/common';
@Global()
@Module({
imports: [DatabaseLifecycleModule, MaintenanceModule],
providers: [SqliteDatabaseBackup, { provide: DATABASE_BACKUP, useExisting: SqliteDatabaseBackup }],
providers: [
SqliteDatabaseBackup,
PostgresDatabaseBackup,
{
provide: DATABASE_BACKUP,
useFactory: (sqlite: SqliteDatabaseBackup, postgres: PostgresDatabaseBackup): DatabaseBackupStrategy =>
({ sqlite, postgres })[resolveEngine().id],
inject: [SqliteDatabaseBackup, PostgresDatabaseBackup],
},
],
exports: [DATABASE_BACKUP],
})
export class DatabaseBackupModule {}
@@ -0,0 +1,48 @@
import { resolveEngine } from '../../db/engine';
import { DomainError } from '../common/domain-error';
import type { DatabaseBackupStrategy } from '../database/database-backup.interface';
import { Injectable } from '@nestjs/common';
/** Why a backup or a restore of a Postgres database is refused in this release. */
export const POSTGRES_BACKUP_UNAVAILABLE =
'Backups of a Postgres database are not available in this release: back it up with pg_dump.';
/**
* The backup port on a Postgres database, before TREK can dump and load one.
* Fails closed: a backup reports that it wrote nothing (rather than writing an
* archive with the uploads and no database), a restore is refused before
* anything is replaced, and the demo reset never gets a baseline to swap in.
*/
@Injectable()
export class PostgresDatabaseBackup implements DatabaseBackupStrategy {
readonly archiveEntry = 'database.dump';
location(): string {
return resolveEngine().describe();
}
canSnapshot(): boolean {
return true;
}
async checkpoint(): Promise<void> {
// Postgres keeps nothing beside its store that a copy would need flushed.
}
snapshot(): Promise<void> {
return Promise.reject(new Error(POSTGRES_BACKUP_UNAVAILABLE));
}
/** Refuses before anything is replaced; the restore removes what it unpacked and answers 400. */
verify(): never {
throw new DomainError(400, POSTGRES_BACKUP_UNAVAILABLE);
}
async keepCopyBeforeRestore(): Promise<string | null> {
return null;
}
replace(): Promise<{ reopenError: unknown }> {
return Promise.reject(new Error(POSTGRES_BACKUP_UNAVAILABLE));
}
}
@@ -1,6 +1,5 @@
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../db/database';
import { resolveDbPath } from '../../db/db-path';
import { runSchemaBootstrap } from '../../db/orm';
import { resolveEngine } from '../../db/engine';
import { MikroORM } from '@mikro-orm/core';
import { Injectable } from '@nestjs/common';
@@ -16,13 +15,14 @@ import { Injectable } from '@nestjs/common';
* port), and the shutdown closes through this. Nothing opens the database at
* import any more; the first connect does, and this provider makes it explicit.
*
* Only the SQLite file engine exists today. The engine specific parts (the file
* path, the swap) are confined to `file` and to the backup port's SQLite
* implementation, so another engine changes this provider and that one class.
* What differs by engine (a file to open or not, how a database reaches the
* schema) is the engine's (`db/engine/`), chosen from `TREK_DB_URL`: this
* provider decides when, the engine decides how.
*/
@Injectable()
export class DatabaseLifecycle {
private readonly reopenListeners: Array<() => Promise<void>> = [];
private readonly engine = resolveEngine();
constructor(private readonly orm: MikroORM) {}
@@ -37,21 +37,19 @@ export class DatabaseLifecycle {
/**
* Opens the connection, binds the ORM to its later swaps and brings the schema
* to head (legacy baseline, migrations, the deferred index, seeders, demo
* seed, in that order: see `db/orm.ts`). Called once by `buildApp()`, before
* anything reads the database.
* to head (on SQLite: legacy baseline, migrations, the deferred index,
* seeders, demo seed, in that order, see `db/orm.ts`; on Postgres: the
* baseline or the migrations after it, then the same seeding). Called once
* by `buildApp()`, before anything reads the database.
*/
async open(): Promise<void> {
// Normally a no-op: the ORM's first connect inside NestFactory.create()
// already opened it. Said here so the boot does not depend on that.
getRawConnection();
registerReinitializeHook(() => this.rebindOrm());
await runSchemaBootstrap(this.orm);
this.engine.open(() => this.rebindOrm());
await this.engine.schemaBootstrap(this.orm, { snapshot: true });
}
/** Checkpoints and closes the connection. A closed connection stays closed until `reopen()`. */
close(): void {
closeDb();
this.engine.close();
}
/**
@@ -60,7 +58,7 @@ export class DatabaseLifecycle {
* restored backup may predate this release).
*/
async reopen(): Promise<void> {
await reinitialize();
await this.engine.reopen();
}
/**
@@ -90,7 +88,7 @@ export class DatabaseLifecycle {
await connection.connect();
// No pre-migrate snapshot: the file was just unpacked from an archive that
// is still there to go back to.
await runSchemaBootstrap(this.orm, { snapshot: false });
await this.engine.schemaBootstrap(this.orm, { snapshot: false });
for (const listener of this.reopenListeners) await listener();
}
}
+2 -1
View File
@@ -18,7 +18,8 @@ async function main(): Promise<void> {
fs.rmSync(schemaSnapshotPath(), { force: true });
const { getRawConnection } = await import('../src/db/database');
const { createStandaloneOrm, runSchemaBootstrap } = await import('../src/db/orm');
const { runSchemaBootstrap } = await import('../src/db/orm');
const { createStandaloneOrm } = await import('../src/db/standalone-orm');
// The shared driver binds to the connection database.ts opens on the ORM's
// first connect, so this migrates that in-memory database and it can be
@@ -369,11 +369,8 @@ describe('validateEnvAtBoot: the database engine', () => {
}
});
it('DB-BOOT-004: refuses a Postgres database while this release cannot run on one', () => {
const { thrown, printed } = bootReport({ TREK_DB_URL: 'postgresql://u:p@db:5432/trek?sslmode=require' });
expect(thrown).toMatch(/Invalid environment configuration/);
expect(printed).toContain('Postgres support is not complete in this release');
expect(printed).not.toContain('u:p@');
it('DB-BOOT-004: accepts a Postgres database on its own', () => {
expect(() => validateEnvAtBoot({ TREK_DB_URL: 'postgresql://u:p@db:5432/trek?sslmode=require' })).not.toThrow();
});
it('DB-BOOT-005: refuses a pool size outside 1 to 100', () => {
@@ -0,0 +1,85 @@
/**
* The schema catalog per engine (src/db/dialect/catalog.ts) and the migration
* helpers built on it (src/db/migration-utils.ts), so a migration after the
* Postgres baseline's cut can ask what exists on either engine.
*/
import { columnNamesSql, tableExistsSql } from '../../../../src/db/dialect/catalog';
import {
addColumnIfMissing,
columnNames,
execUnlessTableMissing,
tableExists,
} from '../../../../src/db/migration-utils';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { Platform, TableNotFoundException } from '@mikro-orm/core';
import type { Migration } from '@mikro-orm/migrations';
import { BasePostgreSqlPlatform, SqlitePlatform } from '@mikro-orm/sql';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
const sqlite = new SqlitePlatform();
const postgres = new BasePostgreSqlPlatform();
describe('catalog statements', () => {
it('CATALOG-001: SQLite reads its own catalog, Postgres the information schema of the current schema', () => {
expect(columnNamesSql(sqlite)).toBe('select name from pragma_table_info(?)');
expect(tableExistsSql(sqlite)).toBe("select name from sqlite_master where type = 'table' and name = ?");
expect(columnNamesSql(postgres)).toBe(
'select column_name as name from information_schema.columns where table_schema = current_schema() and table_name = ?',
);
expect(tableExistsSql(postgres)).toBe(
'select table_name as name from information_schema.tables where table_schema = current_schema() and table_name = ?',
);
});
it('CATALOG-002: any other engine is refused', () => {
class OtherPlatform extends Platform {}
expect(() => columnNamesSql(new OtherPlatform())).toThrow();
expect(() => tableExistsSql(new OtherPlatform())).toThrow();
});
});
describe('migration helpers', () => {
const testDb = createSnapshotTestDb();
let t: TestOrm;
let migration: Migration;
const execute = vi.fn();
beforeAll(async () => {
t = await createTestOrm(testDb);
execute.mockImplementation((sql: string, params?: unknown[]) => t.em.getConnection().execute(sql, params));
migration = { execute, getEntityManager: () => t.em } as unknown as Migration;
});
afterAll(async () => {
await t.close();
testDb.close();
});
it('CATALOG-010: tableExists and columnNames answer from the live SQLite schema', async () => {
expect(await tableExists(migration, 'users')).toBe(true);
expect(await tableExists(migration, 'no_such_table')).toBe(false);
expect((await columnNames(migration, 'users')).has('email')).toBe(true);
expect((await columnNames(migration, 'no_such_table')).size).toBe(0);
});
it('CATALOG-011: addColumnIfMissing adds once, quoting the table the way the engine does', async () => {
execute.mockClear();
await addColumnIfMissing(migration, 'users', 'catalog_probe', 'catalog_probe TEXT');
await addColumnIfMissing(migration, 'users', 'catalog_probe', 'catalog_probe TEXT');
const alters = execute.mock.calls.map(([sql]) => String(sql)).filter((sql) => sql.startsWith('alter table'));
expect(alters).toEqual(['alter table `users` add column catalog_probe TEXT']);
expect((await columnNames(migration, 'users')).has('catalog_probe')).toBe(true);
expect(postgres.quoteIdentifier('users')).toBe('"users"');
});
it('CATALOG-012: execUnlessTableMissing tolerates a missing table on either engine, and nothing else', async () => {
const failing = (error: Error) => ({ execute: vi.fn(async () => Promise.reject(error)) }) as unknown as Migration;
await expect(execUnlessTableMissing(failing(new Error('no such table: x')), 'x')).resolves.toBeUndefined();
const pgMissing = new TableNotFoundException(
Object.assign(new Error('relation "x" does not exist'), { code: '42P01' }),
);
await expect(execUnlessTableMissing(failing(pgMissing), 'x')).resolves.toBeUndefined();
await expect(execUnlessTableMissing(failing(new Error('syntax error')), 'x')).rejects.toThrow('syntax error');
});
});
+14 -8
View File
@@ -1,10 +1,9 @@
import { deriveDb } from '../../../../src/app-config/derive';
import { POSTGRES_NOT_READY } from '../../../../src/app-config/env';
import { buildOrmConfig, resolveEngine } from '../../../../src/db/engine';
import { TrekPostgreSqlDriver } from '../../../../src/db/engine/postgres/postgres-driver';
import { sslOptionFor } from '../../../../src/db/engine/postgres/postgres-engine';
import { redactUrl } from '../../../../src/db/engine/redact-url';
import { SharedSqliteDriver } from '../../../../src/db/orm-driver';
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -17,7 +16,6 @@ describe('resolveEngine', () => {
it('ENGINE-001: SQLite when no TREK_DB_URL is set, which is the test environment', () => {
const engine = resolveEngine();
expect(engine.id).toBe('sqlite');
expect(engine.ready).toBe(true);
expect(engine.ormOptions()).toEqual({ driver: SharedSqliteDriver, dbName: ':memory:' });
expect(engine.describe()).toBe('SQLite file :memory:');
});
@@ -25,9 +23,8 @@ describe('resolveEngine', () => {
it('ENGINE-002: Postgres when TREK_DB_URL names a database, with the pool size and no SSL by default', () => {
const engine = resolveEngine(deriveDb({ TREK_DB_URL: PG_URL, TREK_DB_POOL_MAX: '7' }));
expect(engine.id).toBe('postgres');
expect(engine.ready).toBe(false);
expect(engine.ormOptions()).toEqual({
driver: PostgreSqlDriver,
driver: TrekPostgreSqlDriver,
clientUrl: PG_URL,
pool: { min: 0, max: 7 },
driverOptions: {},
@@ -102,9 +99,18 @@ describe('buildOrmConfig', () => {
expect(Array.isArray(config.entities) && config.entities.length).toBeGreaterThan(100);
});
it('ENGINE-031: refuses an engine this release cannot run, before anything connects, without the password', () => {
it('ENGINE-031: the Postgres config carries the same entities and migrations, on the pg driver', () => {
const config = buildOrmConfig(resolveEngine(deriveDb({ TREK_DB_URL: PG_URL })));
expect(config.driver).toBe(TrekPostgreSqlDriver);
expect(config.clientUrl).toBe(PG_URL);
expect(config.migrations).toMatchObject({ pathTs: 'src/db/migrations', snapshot: false });
expect(config.entities).toBe(buildOrmConfig(resolveEngine()).entities);
});
it('ENGINE-032: a Postgres engine opens and closes nothing of its own, and refuses a reopen (no restore yet)', async () => {
const engine = resolveEngine(deriveDb({ TREK_DB_URL: PG_URL }));
expect(() => buildOrmConfig(engine)).toThrow(POSTGRES_NOT_READY);
expect(() => buildOrmConfig(engine)).not.toThrow(/s3cret/);
expect(() => engine.open(() => undefined)).not.toThrow();
expect(() => engine.close()).not.toThrow();
await expect(engine.reopen()).rejects.toThrow(/not available in this release/);
});
});
@@ -0,0 +1,145 @@
/**
* The committed Postgres baseline (server/assets/postgres/) and what keeps it
* honest: reading and writing it (src/db/engine/postgres/baseline.ts) and the
* generator's --check (scripts/generate-pg-baseline.ts).
*/
import { checkBaseline, rowStatements, triggerPortProblems } from '../../../../../scripts/generate-pg-baseline';
import {
baselineMatches,
readPostgresBaseline,
renderBaseline,
writePostgresBaseline,
type PostgresBaseline,
} from '../../../../../src/db/engine/postgres/baseline';
import { knownMigrationNames } from '../../../../../src/db/known-migrations';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
const A = 'Migration20200101000000_a';
const B = 'Migration20200101000100_b';
const C = 'Migration20200101000200_c';
const sample: PostgresBaseline = {
through: B,
migrations: [A, B],
statements: ['create table "t" ("note" text default \'x;y\')', 'create index "i" on "t" ("note")'],
};
let dir: string | undefined;
afterEach(() => {
if (dir) rmSync(dir, { recursive: true, force: true });
dir = undefined;
});
const scratch = () => (dir = mkdtempSync(path.join(tmpdir(), 'trek-pg-baseline-')));
describe('Postgres baseline files', () => {
it('PGBASE-001: what is written reads back the same, comment line and all', () => {
const target = scratch();
writePostgresBaseline(sample, target);
expect(readPostgresBaseline(target)).toEqual(sample);
expect(baselineMatches(sample, target)).toBe(true);
expect(baselineMatches({ ...sample, statements: [sample.statements[0]] }, target)).toBe(false);
expect(renderBaseline(sample).sql.startsWith('-- ')).toBe(true);
});
it('PGBASE-002: a manifest that does not list its own cut, or an empty SQL file, is refused', () => {
const target = scratch();
writePostgresBaseline(sample, target);
writeFileSync(path.join(target, 'baseline.json'), JSON.stringify({ through: C, migrations: [A, B] }));
expect(() => readPostgresBaseline(target)).toThrow(/must name "through"/);
writePostgresBaseline(sample, target);
writeFileSync(path.join(target, 'baseline.sql'), '-- nothing\n');
expect(() => readPostgresBaseline(target)).toThrow(/holds no statements/);
writeFileSync(path.join(target, 'baseline.sql'), 'create table "q" ("a" text default \'?\');\n');
expect(() => readPostgresBaseline(target)).toThrow(/holds a "\?"/);
expect(baselineMatches(sample, path.join(target, 'missing'))).toBe(false);
});
it('PGBASE-003: the committed baseline names every migration on disk up to its cut, and only those', () => {
const committed = readPostgresBaseline();
const known = [...knownMigrationNames()].sort();
expect(committed.migrations).toEqual(known.filter((name) => name <= committed.through));
expect(committed.statements.some((statement) => /^create table "users"/.test(statement))).toBe(true);
expect(committed.statements.join('\n')).not.toMatch(/\binteger\b/);
});
});
describe('checkBaseline', () => {
const generated = (through: string, migrations: string[]): PostgresBaseline => ({
through,
migrations,
statements: [],
});
it('PGBASE-010: at the newest migration the baseline must be exactly what the entities generate', () => {
expect(checkBaseline(sample, generated(B, [A, B]), true)).toEqual([]);
expect(checkBaseline(sample, generated(B, [A, B]), false)).toEqual([
'the entities generate a different schema; run npm run gen:pg-baseline',
]);
});
it('PGBASE-011: once a migration lands after the cut, the baseline is frozen and only its manifest is checked', () => {
expect(checkBaseline(sample, generated(C, [A, B, C]), false)).toEqual([]);
});
it('PGBASE-012: a manifest naming a migration that is gone, or missing one before its cut, is reported', () => {
expect(checkBaseline(sample, generated(C, [B, C]), true)).toEqual([
`the baseline names migrations that do not exist: ${A}`,
]);
const skipped = { ...sample, migrations: [B] };
expect(checkBaseline(skipped, generated(B, [A, B]), true)).toEqual([
`migrations up to ${B} are missing from it: ${A}`,
]);
});
});
describe('triggerPortProblems', () => {
it('PGBASE-020: every SQLite trigger needs a Postgres port, and a port without its trigger is stale', () => {
expect(triggerPortProblems(['a', 'b'], ['b', 'a'])).toEqual([]);
expect(triggerPortProblems(['a', 'b'], ['a', 'c'])).toEqual([
'SQLite triggers without a Postgres port in POSTGRES_TRIGGERS: b',
'POSTGRES_TRIGGERS ports triggers the migrations no longer create: c',
]);
});
it('PGBASE-021: the committed baseline carries every trigger port after the tables', () => {
const statements = readPostgresBaseline().statements;
const firstTrigger = statements.findIndex((statement) => statement.startsWith('CREATE FUNCTION'));
expect(firstTrigger).toBeGreaterThan(0);
expect(statements.slice(firstTrigger).every((statement) => /^CREATE (FUNCTION|TRIGGER) /.test(statement))).toBe(
true,
);
});
});
describe('rowStatements', () => {
it("PGBASE-030: a migration's rows go in as quoted literals the column casts, and a numeric id moves its sequence past them", () => {
expect(
rowStatements('photo_provider_fields', [
{ id: 1, provider_id: 'immich', label: "Server's URL", required: 1, hint: null },
{ id: 2, provider_id: 'immich', label: 'API key', required: 0, hint: 'x' },
]),
).toEqual([
'insert into "photo_provider_fields" ("id", "provider_id", "label", "required", "hint") values ' +
"('1', 'immich', 'Server''s URL', '1', NULL), ('2', 'immich', 'API key', '0', 'x')",
"select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('\"photo_provider_fields\"', 'id') as seq, " +
'max("id") as max_id from "photo_provider_fields") ids where seq is not null',
]);
});
it('PGBASE-031: a text key has no sequence to move, an empty table writes nothing, and binary data is refused', () => {
expect(rowStatements('addons', [{ id: 'mcp', enabled: 0 }])).toEqual([
'insert into "addons" ("id", "enabled") values (\'mcp\', \'0\')',
]);
expect(rowStatements('addons', [])).toEqual([]);
expect(() => rowStatements('blobs', [{ data: Buffer.from('x') }])).toThrow(/binary data/);
});
it('PGBASE-032: the committed baseline carries the reference rows the migrations insert', () => {
const sql = readPostgresBaseline().statements.join('\n');
expect(sql).toContain('insert into "tour_types"');
expect(sql).toContain('insert into "app_settings"');
});
});
@@ -0,0 +1,46 @@
/**
* The Postgres driver reads `bigint` as a number, on its own pool only
* (src/db/engine/postgres/postgres-driver.ts). Nothing here connects.
*/
import { parseInt8, parseNumeric, TrekPostgreSqlDriver } from '../../../../../src/db/engine/postgres/postgres-driver';
import { Configuration } from '@mikro-orm/core';
import type { PostgreSqlConnection } from '@mikro-orm/postgresql';
import { describe, expect, it } from 'vitest';
type Parsers = { getTypeParser(oid: number): (text: string) => unknown };
describe('postgres driver', () => {
it('PGDRIVER-001: a bigint is a number up to 2^53 and refused past it, never rounded', () => {
expect(parseInt8('0')).toBe(0);
expect(parseInt8('1793636850006')).toBe(1793636850006);
expect(parseInt8('-42')).toBe(-42);
expect(() => parseInt8('9007199254740993')).toThrow(/beyond what TREK reads exactly/);
});
it('PGDRIVER-003: a numeric (sum of a bigint, avg) is a number like SQLite answers, an integral one past 2^53 refused', () => {
expect(parseNumeric('4200')).toBe(4200);
expect(parseNumeric('2.5000000000000000')).toBe(2.5);
expect(parseNumeric('-7')).toBe(-7);
expect(() => parseNumeric('9007199254740993')).toThrow(/beyond what TREK reads exactly/);
expect(() => parseNumeric('NaN')).toThrow(/beyond what TREK reads exactly/);
});
it("PGDRIVER-002: the pool parses int8 as a number and keeps MikroORM's text dates", () => {
const config = new Configuration(
{
driver: TrekPostgreSqlDriver,
clientUrl: 'postgresql://u@localhost/trek',
entities: [],
discovery: { warnWhenNoEntities: false },
},
false,
);
const driver = new TrekPostgreSqlDriver(config);
const options = (driver.getConnection() as PostgreSqlConnection).mapOptions({});
const types = options.types as unknown as Parsers;
expect(types.getTypeParser(20)('12')).toBe(12);
expect(types.getTypeParser(1700)('12.5')).toBe(12.5);
expect(types.getTypeParser(1114)('2026-01-01 00:00:00')).toBe('2026-01-01 00:00:00');
});
});
@@ -1,6 +1,6 @@
/**
* How the Postgres probe turns the entities into a Postgres schema
* (scripts/pg-probe/schema.ts): SQLite-only defaults, TEXT timestamps, the
* How the entities' schema is written in Postgres
* (src/db/engine/postgres/schema-adjust.ts): SQLite-only defaults, TEXT timestamps, the
* NOCASE collation, and splitting the generated DDL so one refused statement
* does not take the rest with it.
*/
@@ -9,9 +9,10 @@ import {
NOCASE_COLLATION_SQL,
PG_NOW_TEXT_DEFAULT,
portableDefault,
POSTGRES_TRIGGERS,
splitStatements,
type ColumnMeta,
} from '../../../../scripts/pg-probe/schema';
} from '../../../../../src/db/engine/postgres/schema-adjust';
import { describe, expect, it } from 'vitest';
@@ -39,19 +40,30 @@ describe('pg-probe schema', () => {
{ name: 'title', customType: new TextType(), columnTypes: ['text'], defaultRaw: "'x'" },
{ name: 'stamp', columnTypes: ['int'], defaultRaw: "(strftime('%s','now'))" },
{ name: 'region', columnTypes: ['text'], collation: 'NOCASE' },
{ name: 'id', columnTypes: ['int'] },
{ name: 'body', columnTypes: ['text'] },
];
expect(adjustColumns(columns)).toEqual(['created_at', 'stamp', 'region']);
expect(columns[0]).toMatchObject({ columnTypes: ['text'], defaultRaw: PG_NOW_TEXT_DEFAULT });
expect(columns[1]).toMatchObject({ columnTypes: ['text'], defaultRaw: "'x'" });
expect(columns[2]).toMatchObject({
columnTypes: ['int'],
columnTypes: ['bigint'],
defaultRaw: 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)',
});
expect(columns[3]).toMatchObject({ collation: 'nocase' });
expect(NOCASE_COLLATION_SQL).toContain('CREATE COLLATION IF NOT EXISTS nocase');
});
it('PGPROBE-043: an integer column is bigint, as wide as SQLite INTEGER (epoch milliseconds overflow integer)', () => {
const columns: ColumnMeta[] = [
{ name: 'id', columnTypes: ['integer'] },
{ name: 'next_run_at', columnTypes: ['int'] },
{ name: 'enabled', columnTypes: ['boolean'] },
{ name: 'note', columnTypes: ['text'] },
];
expect(adjustColumns(columns)).toEqual(['id', 'next_run_at']);
expect(columns.map((column) => column.columnTypes)).toEqual([['bigint'], ['bigint'], ['boolean'], ['text']]);
});
it('PGPROBE-042: splits DDL on semicolons outside quotes and drops session settings', () => {
const ddl = [
"set names 'utf8';",
@@ -67,4 +79,17 @@ describe('pg-probe schema', () => {
]);
expect(splitStatements(' ; ; ')).toEqual([]);
});
it('PGPROBE-044: a $$ body stays one statement, semicolons and all, and every trigger port splits into its two', () => {
const fn =
"CREATE FUNCTION f() RETURNS trigger LANGUAGE plpgsql AS $$\nBEGIN\n UPDATE t SET x = ';';\n RETURN NEW;\nEND\n$$";
expect(splitStatements(`${fn};\nCREATE TRIGGER g AFTER UPDATE ON t FOR EACH ROW EXECUTE FUNCTION f();`)).toEqual([
fn,
'CREATE TRIGGER g AFTER UPDATE ON t FOR EACH ROW EXECUTE FUNCTION f()',
]);
for (const [name, statements] of Object.entries(POSTGRES_TRIGGERS)) {
expect(splitStatements(statements.join(';\n')), name).toEqual([...statements]);
expect(statements.at(-1), name).toContain(`CREATE TRIGGER ${name} `);
}
});
});
@@ -0,0 +1,201 @@
/**
* How a Postgres database reaches the schema (src/db/engine/postgres/schema-bootstrap.ts):
* the three states the plan names (empty, foreign tables, TREK's own) and the
* safety net before pending migrations, over a fake migrator and connection.
*/
import type { AppEnv } from '../../../../../src/app-config';
import {
bootstrapPostgresSchema,
postgresSafetyNet,
type PostgresBootstrapDeps,
} from '../../../../../src/db/engine/postgres/schema-bootstrap';
import type { MigrationSafetyNet } from '../../../../../src/db/legacy-baseline';
import type { AnyOrm } from '../../../../../src/db/orm';
import { Logger } from '@nestjs/common';
import { afterEach, describe, expect, it, vi } from 'vitest';
const M1 = 'Migration20200101000000_baseline_schema';
const M2 = 'Migration20200101000100_second';
const M3 = 'Migration20200101000200_after_the_cut';
interface FakeDb {
executed: string[];
pending: string[];
tables: string[];
/** Whether mikro_orm_migrations exists: from the start when anything is recorded. */
history: boolean;
ensureTable: ReturnType<typeof vi.fn>;
sql: string[];
logged: string[];
inTransaction: boolean[];
up: ReturnType<typeof vi.fn>;
}
function fakeOrm(state: Pick<FakeDb, 'executed' | 'pending' | 'tables'> & { history?: boolean }): {
orm: AnyOrm;
db: FakeDb;
} {
const db: FakeDb = {
...state,
history: state.history ?? state.executed.length > 0,
ensureTable: vi.fn(async () => {
db.history = true;
}),
sql: [],
logged: [],
inTransaction: [],
up: vi.fn(async () => undefined),
};
const trx = { trx: true };
const connection = {
execute: vi.fn(async (sql: string, _params?: unknown[], _method?: string, ctx?: unknown) => {
if (sql.includes('information_schema.tables')) {
return [...db.tables, ...(db.history ? ['mikro_orm_migrations'] : [])].map((table_name) => ({ table_name }));
}
db.sql.push(sql);
db.inTransaction.push(ctx === trx);
return [];
}),
transactional: vi.fn(async (work: (ctx: unknown) => Promise<void>) => work(trx)),
};
const storage = {
ensureTable: db.ensureTable,
logMigration: vi.fn(async ({ name }: { name: string }, ctx?: unknown) => {
db.logged.push(name);
db.inTransaction.push(ctx === trx);
db.executed = [...db.executed, name];
db.pending = db.pending.filter((pending) => pending !== name);
}),
};
const migrator = {
getStorage: () => storage,
getExecuted: vi.fn(async () => db.executed.map((name) => ({ name }))),
getPending: vi.fn(async () => db.pending.map((name) => ({ name }))),
up: db.up,
};
const orm = {
config: { getExtension: () => migrator, get: () => ({}) },
em: { getConnection: () => connection },
} as unknown as AnyOrm;
return { orm, db };
}
function deps(
safetyNet: MigrationSafetyNet = { beforeMigrate: vi.fn(async () => undefined), restoreHint: async () => null },
) {
const value: PostgresBootstrapDeps = {
baseline: () => ({
through: M2,
migrations: [M1, M2],
statements: ['create table "a" ("id" bigserial)', 'create index "x" on "a" ("id")'],
}),
known: new Set([M1, M2, M3]),
safetyNet,
};
return value;
}
afterEach(() => vi.restoreAllMocks());
describe('bootstrapPostgresSchema', () => {
it('PGBOOT-001: an empty database gets the baseline and its migrations recorded, all in one transaction', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2], tables: [] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(db.sql).toEqual(['create table "a" ("id" bigserial);\ncreate index "x" on "a" ("id")']);
expect(db.logged).toEqual([M1, M2]);
expect(db.inTransaction.every(Boolean)).toBe(true);
expect(db.up).not.toHaveBeenCalled();
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
it('PGBOOT-002: a fresh database runs the migrations after the cut without the safety net (nothing to lose)', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2, M3], tables: [] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(db.logged).toEqual([M1, M2]);
expect(db.up).toHaveBeenCalledTimes(1);
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
it('PGBOOT-003: tables without TREK history are refused, named, and nothing is written', async () => {
const { orm, db } = fakeOrm({ executed: [], pending: [M1], tables: ['customers', 'orders'] });
await expect(bootstrapPostgresSchema(orm, deps())).rejects.toThrow(
/Refusing to boot: the database holds 2 table\(s\) \(customers, orders\) but no TREK migration history/,
);
expect(db.sql).toEqual([]);
expect(db.logged).toEqual([]);
expect(db.ensureTable).not.toHaveBeenCalled();
});
it('PGBOOT-008: an empty history table beside no other table is a fresh database (a first boot cut short)', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2], tables: [], history: true });
await bootstrapPostgresSchema(orm, deps());
expect(db.logged).toEqual([M1, M2]);
});
it('PGBOOT-004: a database a newer TREK migrated is refused before anything runs', async () => {
const { orm, db } = fakeOrm({ executed: [M1, 'Migration20990101000000_from_the_future'], pending: [], tables: [] });
await expect(bootstrapPostgresSchema(orm, deps())).rejects.toThrow(/migrated by a newer TREK/);
expect(db.up).not.toHaveBeenCalled();
});
it('PGBOOT-005: pending migrations on a database in use run after the safety net, labelled by the last one', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [M2, M1], pending: [M3], tables: ['users'] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(net.safetyNet.beforeMigrate).toHaveBeenCalledWith('20200101000100');
expect(db.up).toHaveBeenCalledTimes(1);
expect(db.sql).toEqual([]);
});
it('PGBOOT-006: a refusing safety net stops the migration', async () => {
const { orm, db } = fakeOrm({ executed: [M1, M2], pending: [M3], tables: ['users'] });
const refusing = {
beforeMigrate: vi.fn(async () => Promise.reject(new Error('no copy'))),
restoreHint: async () => null,
};
await expect(bootstrapPostgresSchema(orm, deps(refusing))).rejects.toThrow('no copy');
expect(db.up).not.toHaveBeenCalled();
});
it('PGBOOT-007: a database at head does nothing', async () => {
const { orm, db } = fakeOrm({ executed: [M1, M2, M3], pending: [], tables: ['users'] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(db.sql).toEqual([]);
expect(db.up).not.toHaveBeenCalled();
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
});
describe('postgresSafetyNet', () => {
const envWith = (preMigrateSnapshot: boolean | undefined, isTest: boolean) => () =>
({ db: { preMigrateSnapshot }, app: { isTest } }) as unknown as AppEnv;
it.each([undefined, true])(
'PGBOOT-010: refuses by default (setting %s), naming pg_dump and the switch, since this release cannot copy a Postgres database',
async (setting) => {
await expect(postgresSafetyNet(envWith(setting, false)).beforeMigrate('1')).rejects.toThrow(
/cannot copy a Postgres database.*pg_dump.*TREK_DB_PRE_MIGRATE_SNAPSHOT=false/,
);
},
);
it('PGBOOT-011: migrates without a copy when the operator turned it off, and says so', async () => {
const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
await expect(postgresSafetyNet(envWith(false, false)).beforeMigrate('1')).resolves.toBeUndefined();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('without a copy'));
});
it('PGBOOT-012: stays out of the way under test unless a suite asks for it, and has no restore hint', async () => {
const net = postgresSafetyNet(envWith(undefined, true));
await expect(net.beforeMigrate('1')).resolves.toBeUndefined();
await expect(net.restoreHint('1')).resolves.toBeNull();
});
});
@@ -68,8 +68,8 @@ describe('DatabaseLifecycle', () => {
await new DatabaseLifecycle(orm).open();
expect(calls).toEqual(['getRawConnection', 'registerReinitializeHook', 'runSchemaBootstrap:{}']);
expect(ormMock.runSchemaBootstrap).toHaveBeenCalledWith(orm);
expect(calls).toEqual(['getRawConnection', 'registerReinitializeHook', 'runSchemaBootstrap:{"snapshot":true}']);
expect(ormMock.runSchemaBootstrap).toHaveBeenCalledWith(orm, { snapshot: true });
});
it('DBLIFE-002: the hook open() registers rebuilds the ORM client and migrates the new file without a pre-migrate copy', async () => {
@@ -0,0 +1,40 @@
/**
* PostgresDatabaseBackup: the backup port on a Postgres database before TREK
* can dump one. Every path fails closed, before anything is written or swapped.
*/
import { resolveEngine } from '../../../src/db/engine';
import { POSTGRES_BACKUP_UNAVAILABLE, PostgresDatabaseBackup } from '../../../src/nest/backup/postgres-database-backup';
import { DomainError } from '../../../src/nest/common/domain-error';
import { describe, expect, it } from 'vitest';
describe('PostgresDatabaseBackup', () => {
const backup = new PostgresDatabaseBackup();
it('PGBACKUP-001: a backup attempt reports that it wrote nothing, rather than an archive without the database', async () => {
expect(backup.canSnapshot()).toBe(true);
await expect(backup.checkpoint()).resolves.toBeUndefined();
await expect(backup.snapshot()).rejects.toThrow(POSTGRES_BACKUP_UNAVAILABLE);
});
it('PGBACKUP-002: a restore is refused at the verify step with a 400, and nothing is swapped', async () => {
const refusal = (() => {
try {
return backup.verify();
} catch (error) {
return error;
}
})();
expect(refusal).toBeInstanceOf(DomainError);
expect((refusal as DomainError).getStatus()).toBe(400);
expect((refusal as DomainError).publicMessage).toBe(POSTGRES_BACKUP_UNAVAILABLE);
await expect(backup.keepCopyBeforeRestore()).resolves.toBeNull();
await expect(backup.replace()).rejects.toThrow(POSTGRES_BACKUP_UNAVAILABLE);
});
it('PGBACKUP-003: names the database the way the engine describes it (no password) and points at pg_dump', () => {
expect(backup.location()).toBe(resolveEngine().describe());
expect(backup.archiveEntry).toBe('database.dump');
expect(POSTGRES_BACKUP_UNAVAILABLE).toContain('pg_dump');
});
});
+1 -1
View File
@@ -4,5 +4,5 @@
"rootDir": ".",
"noEmit": true
},
"include": ["scripts/generate-entities.ts", "scripts/generate-db-types.ts", "scripts/migrate-encryption.ts", "scripts/pg-probe.ts", "scripts/pg-probe/*.ts"]
"include": ["scripts/generate-entities.ts", "scripts/generate-db-types.ts", "scripts/generate-pg-baseline.ts", "scripts/migrate-encryption.ts", "scripts/pg-probe.ts", "scripts/pg-probe/*.ts"]
}