データモデル Data model

Parky の Supabase PostgreSQL は 5 schema (public / admin / marketing / analytics / extensions) に分離した 128 BASE TABLE + 12 VIEW + 2 MATERIALIZED VIEW で構成されています(infra/supabase/baseline/ 集計、ADR-0011)。 加えて RPC 専用の bff_only schema と pg_cron 管理用の infra schema が併存します(client から GRANT しない / RPC は ADR-0012)。 全クライアント(モバイル / Web / 3 ポータル)が同一データベースに接続するため、本ページがプロダクト横断の正となります。 プロダクト固有のクエリ例は各セクションのデータモデルページを参照してください。 最新の件数は SELECT table_schema, table_type, COUNT(*) FROM information_schema.tables WHERE table_schema IN ('public','admin','marketing','analytics','extensions') GROUP BY 1,2 で確認できます。

Parky's Supabase PostgreSQL is split across 5 schemas (public / admin / marketing / analytics / extensions) totalling 128 base tables, 12 views, and 2 materialized views (counted from infra/supabase/baseline/; see ADR-0011). Two more schemas live alongside: bff_only for RPC-only functions (no client GRANT — see ADR-0012) and infra for pg_cron job tracking. Every client (mobile / web / the three portals) talks to this single database, making this page the cross-product source of truth. For product-specific queries see each product's own data-model page. Verify the live count with SELECT table_schema, table_type, COUNT(*) FROM information_schema.tables WHERE table_schema IN ('public','admin','marketing','analytics','extensions') GROUP BY 1,2.

Schema 構成Schema layout

新規テーブル作成時は必ずどの schema に置くか判定すること(parky/CLAUDE.md §「DB スキーマ構成」)。 admin / marketing / analytics は anon / authenticated に GRANT されておらず、アプリから触る場合は必ず BFF / Edge Function 経由になります。

Always decide which schema a new table belongs in (see parky/CLAUDE.md). admin / marketing / analytics are not granted to anon / authenticated, so the app talks to them only via the BFF / Edge Functions.

Schema役割PurposeアクセスAccessBASEVIEW
publicエンドユーザー向け業務ドメインEnd-user business domainanon / authenticated + RLSanon / authenticated + RLS9110 (+ 2 matview)
admin内部運営者データ (RBAC / 監査)Internal operator data (RBAC, audit)service_role onlyservice_role only102
marketingMarketing Portal 専用 (X / メルマガ / ストア)Marketing Portal only (X / newsletter / stores)service_role onlyservice_role only200
analyticsappend-only テレメトリ。retention 戦略が public と別Append-only telemetry with separate retentionservice_role onlyservice_role only70
extensionspostgis / pg_net / pg_stat_statements / pgcrypto / citext / uuid-ossp / pgtap 等postgis / pg_net / pg_stat_statements / pgcrypto / citext / uuid-ossp / pgtapUSAGE は全ロールUSAGE granted to all roles
bff_onlyBFF 経由のみ呼べる RPC (SECURITY DEFINER)。client は直叩き禁止 (ADR-0012)RPCs that only the BFF may call (SECURITY DEFINER); no client GRANT (ADR-0012)service_role onlyservice_role only
infrapg_cron ジョブ管理 (pg_cron_managed_jobs / pg_cron_status_v)pg_cron job management (pg_cron_managed_jobs / pg_cron_status_v)service_role onlyservice_role only11
flowchart LR
  subgraph Client["Clients (mobile / web / portals)"]
    direction TB
    C[anon / authenticated]
  end
  subgraph BFF["Cloudflare Workers (service_role)"]
    direction TB
    W[Workers]
  end
  subgraph DB["Supabase Postgres"]
    direction TB
    PUBLIC["public
91 base + 10 view + 2 matview
RLS gated"] ADMIN["admin
10 base + 2 view"] MARKETING["marketing
20 base"] ANALYTICS["analytics
7 base (append-only)"] EXT["extensions
postgis / pg_net / pg_stat_statements ..."] BFFONLY["bff_only
SECURITY DEFINER RPCs"] INFRA["infra
pg_cron mgmt"] end C ==>|/v1/* HTTPS| W C -.->|RLS-scoped reads| PUBLIC W -->|service_role| PUBLIC W -->|service_role| ADMIN W -->|service_role| MARKETING W -->|service_role| ANALYTICS W -->|callRpc| BFFONLY W --> EXT W -.->|cron mgmt| INFRA classDef client fill:#e3f2fd,stroke:#1976d2; classDef bff fill:#fff3e0,stroke:#ef6c00; classDef db fill:#f3e5f5,stroke:#7b1fa2; class C client class W bff class PUBLIC,ADMIN,MARKETING,ANALYTICS,EXT,BFFONLY,INFRA db

ドメイングループDomain groups

1. ユーザー・管理者・権限1. Users, admins, permissions

SchemaTable役割Purpose
publicapp_usersエンドユーザー。auth_user_idauth.users と 1:1 紐付け、RLS は auth_user_id = auth.uid() で自己行のみEnd users; linked 1:1 to auth.users via auth_user_id. RLS limits to own row.
publicuser_vehiclesユーザー登録車両(複数可)User-registered vehicles (multiple).
publicuser_search_presets名前付き検索プリセット(最大 20 / デフォルト 1)Named search presets (max 20, one default).
publicuser_search_preferences検索ソート設定(徒歩 1 分 = N 円のレート等)Per-user search sort prefs (walking-cost rate, …).
publicuser_subscriptions / subscription_plansサブスク契約とプランマスターSubscription rows and plan master.
publicuser_consents / consent_types同意取得履歴 (append-only) と種別マスター。current_version で再同意誘導Append-only consent history and type master.
publicuser_device_permissionsOS パーミッションの現在値 (location / push)Current OS-level permission state.
publicuser_notification_prefs通知種別ごとの push / in_app / email ON-OFFPer-notification-type push / in_app / email toggles.
publicuser_referral_codes / user_referral_usages招待コードと利用履歴 (referrer / referee ペア)Referral codes and per-pair usage records.
publicowners駐車場オーナー (法人/個人)。user_idauth.users と紐付け、status (active / reviewing / suspended) で認可判定Parking owners. Status drives authorization.
publicowner_applications既存ユーザーからのオーナー昇格申請Owner-upgrade applications from existing users.
publicowner_inquiries / owner_inquiry_assets / owner_inquiry_upload_tokens公開 LP /for-owners/ からの初回問合せ専用テーブル群(未認証ユーザー)Public-LP first-touch inquiries (no account yet) plus document upload tokens.
publicowner_credits / credit_transactionsオーナー側のクレジット残高と増減台帳 (purchase / consumption / admin_charge / refund)Owner credit balance + ledger.
adminadmins管理者マスター。auth_user_id 1:1、RBAC は role_id で。Marketing Portal も同テーブルを共有Admin master, shared with the Marketing Portal.
adminroles / role_permissionsRBAC。marketing:* 系権限はマーケティングポータル認可に使用RBAC. marketing:* permissions gate the Marketing Portal.
adminblocked_email_hashesブロック済 email の SHA-256。再登録判定で参照、PII 平文は保持しないSHA-256 hashes of blocked emails (no plaintext PII).

2. 駐車場・スポット・料金2. Parking lots, spots, pricing

2026-04-24 に lot → pricing_group → spot の 3 階層化を導入。parking_sessions.parking_spot_idNOT NULL なので、セッション作成時には必ず spot を確定させる必要がある。

Lots gained a 3-level hierarchy on 2026-04-24: lot → pricing_group → spot. parking_sessions.parking_spot_id is NOT NULL, so a session always pins to a specific spot.

SchemaTable役割Purpose
publicparking_lots駐車場本体。location (geography 4326) が座標の SoT、lat/lng はトリガー派生。shape_type で point/line/area を切替、code (citext) は自然キー、operator_code / place_id / entry_difficulty / max_parking_duration_min ほかLot master. location is SoT, lat/lng are derived. shape_type picks point/line/area; code (citext) is the natural key.
publicparking_lot_pricing_groups駐車場内の料金ポリシー集約単位。複数 spot が同一 group を参照することで料金を共通編集できる。(parking_lot_id, code) 一意Pricing-policy aggregation unit. Spots reference a group so pricing can be edited in bulk.
publicparking_spots駐車場内の個別車室。pricing_group_id NOT NULL、車種 / EV 充電 / アクセシビリティ / 寸法 / フロアプラン座標を保持。(parking_lot_id, code) partial UNIQUE (soft delete 考慮)Individual parking spot. NOT NULL pricing_group_id; carries vehicle limits, EV, accessibility, dimensions, floor-plan XY.
publicparking_lot_hours時間窓。1 行 = 1 種別 (window_type: business / entry / exit / after_hours_exit)。day_type / day_of_week で曜日条件、open_time/close_timetext 型 (24:00 表記許容)、effective_from/to で時期別ルールTime windows. One row per window kind. open_time/close_time are text to allow 24:00.
publicparking_lot_date_overrides特定日付の営業時間・料金オーバーライド (花火大会 / 元旦特別営業 等)。hours jsonb / pricing jsonb 配列 / label で 1 日 1 行管理Per-day overrides (fireworks night, New-Year special, …) keyed by date.
publicparking_lot_pricing_rules料金エンジンのルール。pricing_group_id NOT NULL、rule_order で優先順、category / day_type / time_start/time_end (text) で条件絞り込み、cap_type / cap_duration_hours / cap_price_minor / cap_repeat / cap_scope で上限。金額は price_minor (bigint, JPY は 1 倍)Fee-engine rules. pricing_group_id NOT NULL, rule_order sets priority, caps via the cap_* family, money in price_minor (bigint).
publicparking_lot_images駐車場ギャラリー。is_main=true の画像をカード表示に使用Gallery; is_main=true drives the card thumbnail.
publictagsタグ辞書。slug / category (text。値は codes.tag_category から: facility / marketing / payment / other) / icon_name。設備属性・決済手段はすべてタグで表現するTag dictionary; category values come from codes.tag_category. Facilities and payment methods are modeled as tags.
publicparking_lot_tags駐車場 ↔ タグのリンク。stateboolean NOT NULL(true=有り / false=無し)。「未確認」は行が存在しないことで表現するLot ↔ tag link. state is boolean NOT NULL; "unknown" is encoded by row absence (not a NULL value).
publicparking_lot_owners駐車場 ↔ オーナーのリンク (M:N)Lot ↔ owner link (M:N).
publicparking_operators駐車場運営会社のマスター (Phase 0.5 / 2026-05-04 追加)。タイムズ / akippa / コインパーク 等。master.operator_id から FK 参照。検索 facet / Marketing 集計用Parking operators master (Phase 0.5, added 2026-05-04). Times / akippa / Coinpark etc. Referenced by master.operator_id; used for search facets and marketing analytics.
publicparking_reviewsユーザーレビュー。status: pending / approved / rejected / hidden。owner_reply / owner_replied_at / owner_replied_by でオーナー返信、exp_awarded_at で EXP 付与済みかUser reviews. Status: pending / approved / rejected / hidden. Owner replies and EXP-grant timestamp are tracked here.
publicreview_reportsレビュー通報。ユーザーが parking_reviews を不適切として運営に報告Review abuse reports.
publicparking_lot_ratings駐車場ごとの評価集計(parking_reviews とは別軸の text-粒度評価)Per-lot rating aggregates (text-granularity, separate from reviews).
publicplace_discounts周辺施設オーナーが提示する駐車場利用割引Discounts offered by nearby place owners.

3. 駐車セッション・売上3. Sessions & revenue

SchemaTable役割Purpose
publicparking_sessions駐車セッション (入出庫)。parking_spot_id NOT NULL、status: parking / completed / cancelled、金額は total_amount_minor (bigint)、geo_verified / geo_distance_m / client_request_id で位置検証 / 冪等性、fee_mismatch_flag / user_entered_fee_minor でユーザー手入力金額の検証Parking sessions. NOT NULL parking_spot_id, status parking / completed / cancelled, money in total_amount_minor, geo verification + idempotency tracked.
publicparking_session_photosセッション写真 (R2 保存)。phase (before/after) × slot で用途を区別Session photos in R2; phase × slot distinguish purpose.
publicparking_session_sharesセッション共有リンク。share_token でトークン認証、expires_at で期限管理Family-share links via share_token.
publicsession_notificationsセッション中のユーザー設定通知。price_reached / max_price_reached / time_reached / planned_end_minus の 4 trigger を cron (1 分) が評価Session-time triggers (price/time targets). Cron evaluates per minute.
publicrevenue_transactions売上明細。掲載料・広告・送客フィー・App Store IAP・Google Play IAP・admin 手動入力を統一スキーマに集約。月次集計は revenue_monthly_summary view(駐車場予約・決済はスコープ外、プロダクトスコープ参照)Unified revenue ledger covering listing fees, ads, referral fees, App Store / Play IAP, and manual admin entries. Monthly rollup via revenue_monthly_summary view (parking booking / payment is out of scope — see Product scope).
publiccredit_transactionsオーナークレジット増減 (append-only)Owner-credit ledger (append-only).
publicuser_saved_parkingsお気に入り駐車場User favorites.
publicuser_destinations目的地オートコンプリート履歴。Mapbox place_id 重複判定で use_count をインクリメントDestination autocomplete history; use_count increments on dupes.

4. ゲーミフィケーション4. Gamification

SchemaTable / View役割Purpose
publicuser_exp / level_definitionsEXP とレベル閾値マスターXP state and level thresholds.
publicactivity_exp_rules行動 → EXP のルール (識別子は英語コード)Activity → XP rules.
publicactivity_display_rules (view)activity_exp_rules の公開ビュー。攻撃面となる exp_amount / daily_cap / cooldown 等を含めない (T6 対策)。クライアントには activity_typedisplay_category のみ公開Public-safe view of activity rules; hides exploit-sensitive caps and cooldowns.
publicuser_activity_logs / user_activity_log_targets / user_activity_counts行動ログと集計。連続 N 日ログイン等の派生アクティビティも同一テーブルへ合成Activity log + aggregates; derived activities (login streaks) are synthesized.
publicuser_streaksストリーク状態。kind ごとに current / longest 日数と Freeze 猶予を保持Streak state per kind (current / longest / freeze grace).
publicbadge_definitions / badge_definition_tagsバッジ定義 (activity_type × threshold または conditions jsonb)Badge definitions.
publicuser_badges / user_badge_progress獲得バッジと進捗。count >= thresholduser_badges に自動 INSERTEarned badges and progress.
publicgamification_anomaly_* (views)異常検知ビュー: daily_cap_hits / geo_unverified / top_exp_users_24h / pending_referralsAbuse-detection views: cap hits, geo-failures, top XP users, pending referrals.

中核 RPC: award_user_activity_v2(p_user_id, p_activity_type, p_target_id, p_target_type, ...) が行動ログ挿入・EXP 加算・バッジ進捗更新・cap / cooldown / geo verification を 1 トランザクションで処理する。BFF (POST /v1/me/activities) と内部ロジックの両方から呼び出される。

Core RPC: award_user_activity_v2 inserts a log, grants XP, updates badge progress, and enforces caps / cooldowns / geo verification in a single transaction. Invoked from the BFF (POST /v1/me/activities) and internal logic.

5. カスタマイズ(着せ替え)5. Customization (theming)

SchemaTable役割Purpose
publiccustomization_themesテーマ (上位カテゴリ)Themes.
publiccustomization_theme_parts / customization_theme_part_tagsテーマ構成パーツとタグTheme parts + part tags.
publiccustomization_theme_itemsショップ商品 (テーマ ↔ パーツリンク)Shop items (theme ↔ parts link).
publiccustomization_skins旧世代スキン定義 (段階的に themes へ移行)Legacy skins (migrating to themes).
publicuser_themes / user_active_themes / theme_gifts所有 / 適用中 / ギフト履歴。user_active_themes は 1 ユーザー 1 行Owned / active (one row per user) / gifted themes.

6. 広告・ブースト6. Ads & boosts

SchemaTable役割Purpose
publicadsアプリ内広告枠 (オーナー以外の一般広告)In-app ad inventory (non-owner promo).
publicboostsオーナー露出ブースト。credit_per_impression でクレジット消費、日次/総予算で自動停止Owner visibility boosts; auto-paused on daily / total budget.
publichome_bannersホーム画面横長カードの誘導 / 広告スロット (slot_key で位置指定、starts_at/ends_at で配信期間)Home banner slots; starts_at/ends_at drives delivery window.
analyticsboost_impression_logs / boost_click_logs / boost_conversion_logsブースト効果計測 (append-only)。credits_charged は表示時消費分Boost funnel telemetry (append-only).

7. エリア施設・スポンサー7. Area places & sponsors

2026-04 リネームで area_sponsors から area_places に統合済み。スポンサー (is_sponsored=true) と Google Places 取込の近隣施設を 1 テーブルで管理する。area_sponsors は後方互換 view (is_sponsored=true フィルタ) として残しているが、新規コードは area_places を直接参照すること。

Renamed and merged in 043: sponsors (is_sponsored=true) and nearby Google Places points share a single area_places table. The legacy area_sponsors view (filtered to is_sponsored=true) is kept for backwards compatibility only.

SchemaTable / View役割Purpose
publicarea_placesエリア施設マスター (位置 PostGIS / 課金 / 集計)。is_sponsored でスポンサー判別Area-place master (location, billing, aggregates).
publicarea_sponsors (view)後方互換 view。area_places WHERE is_sponsored=trueBackwards-compat view filtered to sponsors.
publicparking_lot_nearby_spotsハブページ生成用の事前計算リンク (駐車場 → 駅 / ランドマーク距離)Pre-computed lot ↔ nearby station / landmark links.
analyticssponsor_notification_logsスポンサー近接通知の発火ログ。Phase 5 以降はモバイル geofence から API 経由で記録Sponsor proximity-notification logs.

PostGIS 関数:
  • nearby_parking_lots(p_lng, p_lat, p_radius_m, ...) — 近隣駐車場検索
  • nearby_places_rpc(...) — 駐車場周辺の施設検索
コードマスター: sponsor_category (restaurant / cafe / shop / attraction / hotel / service / other)、sponsor_status (draft / active / paused / ended)、sponsor_placement (map / detail / session)
近接通知: モバイル側のネイティブジオフェンスで検知 (サーバー側に近接検知ジョブを置かない)。

PostGIS functions: nearby_parking_lots, nearby_places_rpc. Code masters: sponsor_category, sponsor_status, sponsor_placement. Proximity notifications are handled by on-device geofences; no server-side proximity job runs.

8. 通知8. Notifications

SchemaTable役割Purpose
adminadmin_notifications管理者通知 (Supabase Realtime 購読)。ヘッダーベル表示Admin notifications (consumed via Realtime).
adminadmin_tasks管理者タスク。task_kind + ref_idsupport_tickets / error_reports / owner_applications / parking_lots (new) をポリモーフィック参照Admin task inbox; polymorphic via task_kind + ref_id.
adminadmin_activity_logs管理者操作の監査ログ (append-only)Admin operation audit log (append-only).
publicuser_notificationsユーザー向け通知 (FCM 配信は parky-fcm-dispatch Queue 経由)。created_by の管理者が作成User notifications (FCM via the parky-fcm-dispatch queue).
publicuser_push_tokensFCM デバイストークン。送信時に展開FCM token store.
marketingmarketing_notificationsマーケ担当者向け通知Marketing-portal in-app notifications.
注: Note: 管理者ごとの通知 ON/OFF (admins_notification_prefs) と admin_activity_log_refs は計画段階の名前で実体は未実装。現在の運用は admin_activity_logs 単独でカバー、設定は admin UI 側に保存している。 Per-admin preference rows (admins_notification_prefs) and audit-ref normalization (admin_activity_log_refs) were planned but not implemented; admin prefs live client-side and audit refs are kept inline.

9. コンテンツ・サポート9. Content & support

SchemaTable役割Purpose
publicarticles記事 CMS (TOKYO CAR LIFE 等)。publish_to_web / publish_to_app でチャネル制御、story_number で TOKYO CAR STORY の話数を永続化Articles CMS; channel flags + story_number for series.
publicarticle_tags / article_tag_links記事タグマスターと M:N リンク (tags とは独立した記事専用)Article-only tag master + M:N link (separate from lot tags).
publicassetsバイナリアセットのメタデータ。s3_keyCloudflare R2 オブジェクトを指す (Supabase Storage 不使用)Binary metadata; s3_key points to Cloudflare R2 (not Supabase Storage).
publicsupport_ticketsサポート問い合わせSupport tickets.
analyticserror_reportsクライアントからの不具合報告。アプリ内フォームから送信、admin_tasks に自動転送Client-side bug reports; auto-fanned to admin_tasks.
analyticsclient_eventsクライアント任意イベント / エラー報告 (severity 別、error 以上は Slack 通知)Arbitrary client events; severity ≥ error fans to Slack.
publicapp_review_promptsストアレビュー促進の表示・submit 履歴In-app store-review prompt history.

10. マスターデータ10. Master data

SchemaTable役割Purpose
publiccodesコードマスター (enum 代替)。category_id でカテゴリ、code で値、display_label で UI 表示名、metadata jsonb で補助属性Code master (enum stand-in); JA/EN labels + jsonb metadata.
publici18n_messagesMobile i18n bundle の SSoT。GET /v1/mobile/i18n/bundle で ETag 配信、admin から編集i18n SSoT for mobile; ETag-served via the BFF.
publicjp_holidays日本の祝日マスター。date PK / kind (national / substitute / national_holiday_bridge)。is_jp_holiday(date) helper で参照Japanese public-holiday master; looked up via is_jp_holiday(date).
publicapp_config / app_config_history公開グローバル設定 KV と監査履歴 (append-only)。クライアント露出可能な値のみPublic global config KV with append-only audit history.
adminapp_config / app_config_historyサーバー専用グローバル設定。クライアント露出不可な運用値 (cron 周期 / レート制限 / 保持期間 等)Server-only config (cron cadence, rate limits, retention windows).
adminapp_config_all (view)public.app_config + admin.app_config の統合読み取り (security_invoker=true)Joined read-only view (security_invoker).

コードマスターの主要 category_id (実 DB 検証済): admin_status / user_status (active / withdrawn / suspended / blocked) / vehicle_type (sedan / kei / large / bike / minivan / high_roof) / session_status (parking / completed / cancelled) / review_status (pending / approved / rejected / hidden) / parking_lot_status (pending / active / on_hold / withdrawn) / tag_category (facility / marketing / payment / other) / parking_hours_window_type (business / entry / exit / after_hours_exit) / day_type (weekday / saturday / sunday / holiday / holiday_eve / all) / notif_type / notif_status / notif_target / device_type / sponsor_category / sponsor_status / sponsor_placement / store_type / store_sync_status / operator / oversized_ok ほか。

Verified category_id values (live DB): user_status (active / withdrawn / suspended / blocked), vehicle_type (sedan / kei / large / bike / minivan / high_roof), session_status (parking / completed / cancelled), review_status (pending / approved / rejected / hidden), parking_lot_status (pending / active / on_hold / withdrawn), tag_category (facility / marketing / payment / other), parking_hours_window_type (business / entry / exit / after_hours_exit), day_type (weekday / saturday / sunday / holiday / holiday_eve / all), and more.

時刻判定 RPC (2026-04-24): Window-active RPCs (2026-04-24): is_parking_lot_window_active(lot_id, at, window_type) — 汎用窓口判定 (優先順: 日付オーバーライド → 祝日行 → 曜日行 → day_type → all フォールバック)。is_parking_lot_open_nowwindow_type='business' ラッパ、can_enter_parking_lot_now / can_exit_parking_lot_now は entry / exit / after_hours_exit を OR 合成。helper: is_jp_holiday(date) / get_parking_lot_date_override(lot_id, date)。詳細は 2026-04-24 ADR is_parking_lot_window_active(lot_id, at, window_type) resolves: date override → holiday row → day-of-week row → day_type → all fallback. is_parking_lot_open_now is the business wrapper. can_enter_parking_lot_now / can_exit_parking_lot_now OR-combine entry / exit windows with after-hours-exit. See the 2026-04-24 ADR.

11. 地理階層・ハブ統計11. Geographic hierarchy & hub stats

Web 版のハブページ (都道府県 → 市区町村 → スポット) の事前集計・リンク生成に利用。

Powers the web app's hub pages (prefecture → city → spot) through pre-aggregated data and link tables.

SchemaTable役割Purpose
publicregions地方区分 (8 地方)Regions (8 of them).
publicprefectures都道府県マスター (slug 付き)Prefecture master with slug.
publiccities市区町村マスター。(prefecture_id, slug) でハブ URL を組むCity master; (prefecture_id, slug) keys the hub URL.
publicstations駅マスター。(city_id, slug) でハブページを一意に特定Station master keyed by (city_id, slug).
publicparking_lot_nearby_spots駐車場と周辺スポットのリンク (事前計算結果)Precomputed lot ↔ nearby-spot link.
ランドマーク: Landmarks: 独立 landmarks テーブルは持たず、area_places + parking_lot_nearby_spots で表現する。観光地・施設は area_places 側で place_kind (sponsor / landmark / station 周辺施設等) を分けて管理。 There is no separate landmarks table; landmarks live in area_places distinguished by place_kind, with hub linkage via parking_lot_nearby_spots.

12. AI 検索12. AI search

SchemaTable役割Purpose
publicai_providersLLM プロバイダー設定 (Claude / Gemini / OpenAI)。モデル名・有効/無効・優先順位・vault_secret_id・コスト単価。実 API キーは Supabase Vault 暗号化保管LLM provider config; API keys encrypted in Supabase Vault.
publicai_usage_logsParky ドメイン固有の LLM 呼び出しイベントログ。トークン数・コスト・レイテンシは Cloudflare AI Gateway 側でも記録されるParky-specific LLM call log; tokens / cost / latency dual-recorded by Cloudflare AI Gateway.

13. マーケティングポータル13. Marketing Portal

Marketing Portal (web/portal/marketing/) 専用の marketing schema。X 運用・ニュースレター配信・キャンペーン管理・SNS メトリクス収集を担う。 詳細は マーケティングポータル アーキテクチャ

Owned by the Marketing Portal (web/portal/marketing/) and isolated to the marketing schema. Covers X ops, newsletter delivery, campaigns, and SNS metrics. See Marketing Portal architecture.

SchemaTable役割Purpose
marketingmarketing_integrations外部サービス接続設定 (X / Instagram / GA4 / Resend 等)。OAuth トークンは Supabase VaultExternal-service config; OAuth tokens vaulted.
marketingmarketing_brandブランド設定 (単一行 id=1)。ロゴ / カラー / NG ワード / デフォルトハッシュタグBrand config (single row).
marketingmarketing_assetsマーケ用画像・動画 (R2 + メタ + サムネ URL)Marketing media (R2 + thumbnails).
marketingmarketing_campaigns / marketing_campaign_itemsキャンペーンと配信要素 (item_kind で参照先テーブルを判別する soft FK)Campaigns + delivery items.
marketingmarketing_activity_logマーケ操作の監査ログ (admin 系とは別系統)Marketing operator audit log.
marketingx_accounts接続済 X アカウント。refresh token は VaultConnected X accounts; tokens vaulted.
marketingx_postsX 投稿 (draft / scheduled / sent / failed を status で管理)X posts (draft / scheduled / sent / failed).
marketingx_schedule_rules / x_listen_rules / x_automation_log / x_competitors予約ルール・監視ルール・自動化ログ・競合トラッキングScheduling / listening rules + automation log + competitor tracking.
marketingnewsletter_subscribersTOKYO CAR LIFE メルマガ購読者。marketing schema にあるため anon GRANT は無く、登録は BFF (POST /v1/marketing/newsletter/subscribers) 経由Newsletter subscribers; signup goes through the BFF, not direct anon INSERT.
marketingnewsletter_broadcasts配信履歴 (対象 / 件数 / 送信ステータス)Broadcast history.

認可: requireMarketing ミドルウェアが admin.adminsadmin.role_permissions を JOIN し、marketing:* 権限または super admin フラグを要求する。

Authorization: the requireMarketing middleware joins admin.admins with admin.role_permissions and requires a marketing:* permission or super-admin flag.

14. 店舗連携 (外部データ取り込み)14. Store integrations (external ingest)

外部 POS / App Store Connect / Google Play Console との同期、レビュー取込、日次集計を担う。 同期ジョブは Workers queue parky-store-sync 経由で実行。

External-system syncs (POS / App Store Connect / Google Play Console). Jobs run through the parky-store-sync Workers queue.

SchemaTable役割Purpose
marketingstore_integrations連携先設定 (App Store / Google Play)。API キー / vendor numberStore connection config.
marketingstore_sales_daily日次売上 (product_id × country_code × date)。revenue_transactions へ集約Daily sales rolled up to revenue.
marketingstore_app_metrics_daily日次アプリ指標 (インストール / クラッシュ率 / 評価平均)Daily app metrics (installs / crashes / ratings).
marketingstore_reviews外部ストアレビュー。external_review_id で差分取込、reply_body で運営返信External reviews + replies.
marketingstore_sync_runs同期ジョブ実行履歴 (cron / manual)Sync job runs.
analyticssns_follower_snapshotsSNS フォロワー数の日次スナップショット (JST 09:00 cron)Daily SNS follower snapshots (09:00 JST cron).

VIEW 一覧View catalogue

SchemaView役割Purpose
publicactivity_display_rulesactivity_exp_rules の公開向けセーフ viewPublic-safe view of activity rules.
publicarea_sponsorsarea_places WHERE is_sponsored=true の後方互換 viewBackwards-compat sponsor filter.
publicparking_lot_avg_rating承認済レビューの平均評価 (security_invoker=true)Avg rating from approved reviews.
publicparking_lot_min_hourly_rate時間課金ルールの最安 rate (security_invoker=true)Cheapest hourly rate per lot.
publicparking_spots_effectivespot 状態 + pricing group の有効値を結合した参照ビューEffective view joining spot state with its pricing group.
publicrevenue_monthly_summary月次売上集計 (channel × currency)Monthly revenue rollup.
public (matview)parking_lot_avg_rating_mv / parking_lot_min_hourly_rate_mv同名 view のキャッシュ用 materialized view (定期 REFRESH)Materialized cache of the same-name views (periodic REFRESH).
publicgamification_anomaly_daily_cap_hits直近 48h の cap ヒット集計 (異常検知)Last-48h cap-hit anomaly view.
publicgamification_anomaly_geo_unverified直近 48h の geo 検証失敗集計Last-48h geo-fail anomaly view.
publicgamification_anomaly_top_exp_users_24h直近 24h の TOP100 EXP 獲得者Top-100 24h XP earners.
publicgamification_pending_referrals直近 30 日の紹介適用状況30-day referral application status.
adminapp_config_allpublic.app_config + admin.app_config 統合読取Joined config view.
adminapp_config_history_all同上の履歴統合Joined config-history view.

論理 ER 図 (主要テーブル)Logical ER diagram (core tables)

使い方: Tip: エンティティをクリックすると、関連するリレーションと相手エンティティだけがハイライトされます。図が小さい場合は右上の「拡大表示」で全画面表示できます。 Click any entity to highlight only the relationships and peers related to it. Use "Expand" on the top right to view the diagram full-screen.
エンティティをクリックして関連を強調 Click any entity to focus its relationships
erDiagram
  APP_USERS ||--o{ PARKING_SESSIONS : starts
  PARKING_LOTS ||--o{ PARKING_SESSIONS : hosts
  PARKING_SPOTS ||--o{ PARKING_SESSIONS : pinned_to
  PARKING_LOTS ||--o{ PARKING_LOT_PRICING_GROUPS : has
  PARKING_LOT_PRICING_GROUPS ||--o{ PARKING_SPOTS : groups
  PARKING_LOT_PRICING_GROUPS ||--o{ PARKING_LOT_PRICING_RULES : prices
  APP_USERS ||--o{ PARKING_REVIEWS : writes
  PARKING_LOTS ||--o{ PARKING_REVIEWS : receives
  PARKING_LOTS ||--o{ PARKING_LOT_IMAGES : has
  PARKING_LOTS ||--o{ PARKING_LOT_HOURS : has
  PARKING_LOTS ||--o{ PARKING_LOT_DATE_OVERRIDES : overrides
  PARKING_LOTS ||--o{ PARKING_LOT_TAGS : has
  TAGS ||--o{ PARKING_LOT_TAGS : labels
  OWNERS ||--o{ PARKING_LOT_OWNERS : owns
  PARKING_LOTS ||--o{ PARKING_LOT_OWNERS : owned_by
  OWNERS ||--o{ OWNER_APPLICATIONS : applies
  OWNERS ||--|| OWNER_CREDITS : holds
  OWNERS ||--o{ BOOSTS : purchases
  ADMINS ||--o{ X_ACCOUNTS : connects
  X_ACCOUNTS ||--o{ X_POSTS : schedules
  ADMINS ||--o{ MARKETING_CAMPAIGNS : authors
  MARKETING_CAMPAIGNS ||--o{ MARKETING_CAMPAIGN_ITEMS : contains
  APP_USERS ||--o{ USER_BADGES : earns
  BADGE_DEFINITIONS ||--o{ USER_BADGES : defines
  APP_USERS ||--|| USER_EXP : accrues
  APP_USERS ||--o{ USER_STREAKS : tracks
  APP_USERS ||--o{ USER_NOTIFICATIONS : receives
  APP_USERS ||--o{ USER_PUSH_TOKENS : has
  APP_USERS ||--o{ USER_NOTIFICATION_PREFS : prefers
  APP_USERS ||--o{ USER_REFERRAL_CODES : owns
  USER_REFERRAL_CODES ||--o{ USER_REFERRAL_USAGES : used_by
  APP_USERS ||--o{ USER_SUBSCRIPTIONS : holds
  SUBSCRIPTION_PLANS ||--o{ USER_SUBSCRIPTIONS : priced_as
  APP_USERS ||--o{ USER_CONSENTS : grants
  CONSENT_TYPES ||--o{ USER_CONSENTS : kinds
  ADMINS ||--o{ ADMIN_NOTIFICATIONS : sees
  ROLES ||--o{ ADMINS : assigned
  ROLES ||--o{ ROLE_PERMISSIONS : grants

  %% エンティティをクリックして関連ドキュメントへ
重要: Important: 列挙値 (status, type, category 等) はすべて codes テーブルで管理されます。CHECK 制約に日本語は入れません (Conventions)。 All enum values live in codes. Never put Japanese into CHECK constraints — see the Conventions page.