データモデル 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 | アクセス | Access | BASE | VIEW |
|---|---|---|---|---|---|---|
public | エンドユーザー向け業務ドメイン | End-user business domain | anon / authenticated + RLS | anon / authenticated + RLS | 91 | 10 (+ 2 matview) |
admin | 内部運営者データ (RBAC / 監査) | Internal operator data (RBAC, audit) | service_role only | service_role only | 10 | 2 |
marketing | Marketing Portal 専用 (X / メルマガ / ストア) | Marketing Portal only (X / newsletter / stores) | service_role only | service_role only | 20 | 0 |
analytics | append-only テレメトリ。retention 戦略が public と別 | Append-only telemetry with separate retention | service_role only | service_role only | 7 | 0 |
extensions | postgis / pg_net / pg_stat_statements / pgcrypto / citext / uuid-ossp / pgtap 等 | postgis / pg_net / pg_stat_statements / pgcrypto / citext / uuid-ossp / pgtap | USAGE は全ロール | USAGE granted to all roles | — | — |
bff_only | BFF 経由のみ呼べる RPC (SECURITY DEFINER)。client は直叩き禁止 (ADR-0012) | RPCs that only the BFF may call (SECURITY DEFINER); no client GRANT (ADR-0012) | service_role only | service_role only | — | — |
infra | pg_cron ジョブ管理 (pg_cron_managed_jobs / pg_cron_status_v) | pg_cron job management (pg_cron_managed_jobs / pg_cron_status_v) | service_role only | service_role only | 1 | 1 |
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
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | app_users | エンドユーザー。auth_user_id で auth.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. |
public | user_vehicles | ユーザー登録車両(複数可) | User-registered vehicles (multiple). |
public | user_search_presets | 名前付き検索プリセット(最大 20 / デフォルト 1) | Named search presets (max 20, one default). |
public | user_search_preferences | 検索ソート設定(徒歩 1 分 = N 円のレート等) | Per-user search sort prefs (walking-cost rate, …). |
public | user_subscriptions / subscription_plans | サブスク契約とプランマスター | Subscription rows and plan master. |
public | user_consents / consent_types | 同意取得履歴 (append-only) と種別マスター。current_version で再同意誘導 | Append-only consent history and type master. |
public | user_device_permissions | OS パーミッションの現在値 (location / push) | Current OS-level permission state. |
public | user_notification_prefs | 通知種別ごとの push / in_app / email ON-OFF | Per-notification-type push / in_app / email toggles. |
public | user_referral_codes / user_referral_usages | 招待コードと利用履歴 (referrer / referee ペア) | Referral codes and per-pair usage records. |
public | owners | 駐車場オーナー (法人/個人)。user_id で auth.users と紐付け、status (active / reviewing / suspended) で認可判定 | Parking owners. Status drives authorization. |
public | owner_applications | 既存ユーザーからのオーナー昇格申請 | Owner-upgrade applications from existing users. |
public | owner_inquiries / owner_inquiry_assets / owner_inquiry_upload_tokens | 公開 LP /for-owners/ からの初回問合せ専用テーブル群(未認証ユーザー) | Public-LP first-touch inquiries (no account yet) plus document upload tokens. |
public | owner_credits / credit_transactions | オーナー側のクレジット残高と増減台帳 (purchase / consumption / admin_charge / refund) | Owner credit balance + ledger. |
admin | admins | 管理者マスター。auth_user_id 1:1、RBAC は role_id で。Marketing Portal も同テーブルを共有 | Admin master, shared with the Marketing Portal. |
admin | roles / role_permissions | RBAC。marketing:* 系権限はマーケティングポータル認可に使用 | RBAC. marketing:* permissions gate the Marketing Portal. |
admin | blocked_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_id は NOT 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.
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | parking_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. |
public | parking_lot_pricing_groups | 駐車場内の料金ポリシー集約単位。複数 spot が同一 group を参照することで料金を共通編集できる。(parking_lot_id, code) 一意 | Pricing-policy aggregation unit. Spots reference a group so pricing can be edited in bulk. |
public | parking_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. |
public | parking_lot_hours | 時間窓。1 行 = 1 種別 (window_type: business / entry / exit / after_hours_exit)。day_type / day_of_week で曜日条件、open_time/close_time は text 型 (24:00 表記許容)、effective_from/to で時期別ルール | Time windows. One row per window kind. open_time/close_time are text to allow 24:00. |
public | parking_lot_date_overrides | 特定日付の営業時間・料金オーバーライド (花火大会 / 元旦特別営業 等)。hours jsonb / pricing jsonb 配列 / label で 1 日 1 行管理 | Per-day overrides (fireworks night, New-Year special, …) keyed by date. |
public | parking_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). |
public | parking_lot_images | 駐車場ギャラリー。is_main=true の画像をカード表示に使用 | Gallery; is_main=true drives the card thumbnail. |
public | tags | タグ辞書。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. |
public | parking_lot_tags | 駐車場 ↔ タグのリンク。state は boolean NOT NULL(true=有り / false=無し)。「未確認」は行が存在しないことで表現する | Lot ↔ tag link. state is boolean NOT NULL; "unknown" is encoded by row absence (not a NULL value). |
public | parking_lot_owners | 駐車場 ↔ オーナーのリンク (M:N) | Lot ↔ owner link (M:N). |
public | parking_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. |
public | parking_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. |
public | review_reports | レビュー通報。ユーザーが parking_reviews を不適切として運営に報告 | Review abuse reports. |
public | parking_lot_ratings | 駐車場ごとの評価集計(parking_reviews とは別軸の text-粒度評価) | Per-lot rating aggregates (text-granularity, separate from reviews). |
public | place_discounts | 周辺施設オーナーが提示する駐車場利用割引 | Discounts offered by nearby place owners. |
3. 駐車セッション・売上3. Sessions & revenue
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | parking_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. |
public | parking_session_photos | セッション写真 (R2 保存)。phase (before/after) × slot で用途を区別 | Session photos in R2; phase × slot distinguish purpose. |
public | parking_session_shares | セッション共有リンク。share_token でトークン認証、expires_at で期限管理 | Family-share links via share_token. |
public | session_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. |
public | revenue_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). |
public | credit_transactions | オーナークレジット増減 (append-only) | Owner-credit ledger (append-only). |
public | user_saved_parkings | お気に入り駐車場 | User favorites. |
public | user_destinations | 目的地オートコンプリート履歴。Mapbox place_id 重複判定で use_count をインクリメント | Destination autocomplete history; use_count increments on dupes. |
4. ゲーミフィケーション4. Gamification
| Schema | Table / View | 役割 | Purpose |
|---|---|---|---|
public | user_exp / level_definitions | EXP とレベル閾値マスター | XP state and level thresholds. |
public | activity_exp_rules | 行動 → EXP のルール (識別子は英語コード) | Activity → XP rules. |
public | activity_display_rules (view) | activity_exp_rules の公開ビュー。攻撃面となる exp_amount / daily_cap / cooldown 等を含めない (T6 対策)。クライアントには activity_type と display_category のみ公開 | Public-safe view of activity rules; hides exploit-sensitive caps and cooldowns. |
public | user_activity_logs / user_activity_log_targets / user_activity_counts | 行動ログと集計。連続 N 日ログイン等の派生アクティビティも同一テーブルへ合成 | Activity log + aggregates; derived activities (login streaks) are synthesized. |
public | user_streaks | ストリーク状態。kind ごとに current / longest 日数と Freeze 猶予を保持 | Streak state per kind (current / longest / freeze grace). |
public | badge_definitions / badge_definition_tags | バッジ定義 (activity_type × threshold または conditions jsonb) | Badge definitions. |
public | user_badges / user_badge_progress | 獲得バッジと進捗。count >= threshold で user_badges に自動 INSERT | Earned badges and progress. |
public | gamification_anomaly_* (views) | 異常検知ビュー: daily_cap_hits / geo_unverified / top_exp_users_24h / pending_referrals | Abuse-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)
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | customization_themes | テーマ (上位カテゴリ) | Themes. |
public | customization_theme_parts / customization_theme_part_tags | テーマ構成パーツとタグ | Theme parts + part tags. |
public | customization_theme_items | ショップ商品 (テーマ ↔ パーツリンク) | Shop items (theme ↔ parts link). |
public | customization_skins | 旧世代スキン定義 (段階的に themes へ移行) | Legacy skins (migrating to themes). |
public | user_themes / user_active_themes / theme_gifts | 所有 / 適用中 / ギフト履歴。user_active_themes は 1 ユーザー 1 行 | Owned / active (one row per user) / gifted themes. |
6. 広告・ブースト6. Ads & boosts
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | ads | アプリ内広告枠 (オーナー以外の一般広告) | In-app ad inventory (non-owner promo). |
public | boosts | オーナー露出ブースト。credit_per_impression でクレジット消費、日次/総予算で自動停止 | Owner visibility boosts; auto-paused on daily / total budget. |
public | home_banners | ホーム画面横長カードの誘導 / 広告スロット (slot_key で位置指定、starts_at/ends_at で配信期間) | Home banner slots; starts_at/ends_at drives delivery window. |
analytics | boost_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.
| Schema | Table / View | 役割 | Purpose |
|---|---|---|---|
public | area_places | エリア施設マスター (位置 PostGIS / 課金 / 集計)。is_sponsored でスポンサー判別 | Area-place master (location, billing, aggregates). |
public | area_sponsors (view) | 後方互換 view。area_places WHERE is_sponsored=true | Backwards-compat view filtered to sponsors. |
public | parking_lot_nearby_spots | ハブページ生成用の事前計算リンク (駐車場 → 駅 / ランドマーク距離) | Pre-computed lot ↔ nearby station / landmark links. |
analytics | sponsor_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
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
admin | admin_notifications | 管理者通知 (Supabase Realtime 購読)。ヘッダーベル表示 | Admin notifications (consumed via Realtime). |
admin | admin_tasks | 管理者タスク。task_kind + ref_id で support_tickets / error_reports / owner_applications / parking_lots (new) をポリモーフィック参照 | Admin task inbox; polymorphic via task_kind + ref_id. |
admin | admin_activity_logs | 管理者操作の監査ログ (append-only) | Admin operation audit log (append-only). |
public | user_notifications | ユーザー向け通知 (FCM 配信は parky-fcm-dispatch Queue 経由)。created_by の管理者が作成 | User notifications (FCM via the parky-fcm-dispatch queue). |
public | user_push_tokens | FCM デバイストークン。送信時に展開 | FCM token store. |
marketing | marketing_notifications | マーケ担当者向け通知 | Marketing-portal in-app notifications. |
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
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | articles | 記事 CMS (TOKYO CAR LIFE 等)。publish_to_web / publish_to_app でチャネル制御、story_number で TOKYO CAR STORY の話数を永続化 | Articles CMS; channel flags + story_number for series. |
public | article_tags / article_tag_links | 記事タグマスターと M:N リンク (tags とは独立した記事専用) | Article-only tag master + M:N link (separate from lot tags). |
public | assets | バイナリアセットのメタデータ。s3_key は Cloudflare R2 オブジェクトを指す (Supabase Storage 不使用) | Binary metadata; s3_key points to Cloudflare R2 (not Supabase Storage). |
public | support_tickets | サポート問い合わせ | Support tickets. |
analytics | error_reports | クライアントからの不具合報告。アプリ内フォームから送信、admin_tasks に自動転送 | Client-side bug reports; auto-fanned to admin_tasks. |
analytics | client_events | クライアント任意イベント / エラー報告 (severity 別、error 以上は Slack 通知) | Arbitrary client events; severity ≥ error fans to Slack. |
public | app_review_prompts | ストアレビュー促進の表示・submit 履歴 | In-app store-review prompt history. |
10. マスターデータ10. Master data
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | codes | コードマスター (enum 代替)。category_id でカテゴリ、code で値、display_label で UI 表示名、metadata jsonb で補助属性 | Code master (enum stand-in); JA/EN labels + jsonb metadata. |
public | i18n_messages | Mobile i18n bundle の SSoT。GET /v1/mobile/i18n/bundle で ETag 配信、admin から編集 | i18n SSoT for mobile; ETag-served via the BFF. |
public | jp_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). |
public | app_config / app_config_history | 公開グローバル設定 KV と監査履歴 (append-only)。クライアント露出可能な値のみ | Public global config KV with append-only audit history. |
admin | app_config / app_config_history | サーバー専用グローバル設定。クライアント露出不可な運用値 (cron 周期 / レート制限 / 保持期間 等) | Server-only config (cron cadence, rate limits, retention windows). |
admin | app_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.
is_parking_lot_window_active(lot_id, at, window_type) — 汎用窓口判定 (優先順: 日付オーバーライド → 祝日行 → 曜日行 → day_type → all フォールバック)。is_parking_lot_open_now は window_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.
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | regions | 地方区分 (8 地方) | Regions (8 of them). |
public | prefectures | 都道府県マスター (slug 付き) | Prefecture master with slug. |
public | cities | 市区町村マスター。(prefecture_id, slug) でハブ URL を組む | City master; (prefecture_id, slug) keys the hub URL. |
public | stations | 駅マスター。(city_id, slug) でハブページを一意に特定 | Station master keyed by (city_id, slug). |
public | parking_lot_nearby_spots | 駐車場と周辺スポットのリンク (事前計算結果) | Precomputed lot ↔ nearby-spot link. |
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
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
public | ai_providers | LLM プロバイダー設定 (Claude / Gemini / OpenAI)。モデル名・有効/無効・優先順位・vault_secret_id・コスト単価。実 API キーは Supabase Vault 暗号化保管 | LLM provider config; API keys encrypted in Supabase Vault. |
public | ai_usage_logs | Parky ドメイン固有の 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.
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
marketing | marketing_integrations | 外部サービス接続設定 (X / Instagram / GA4 / Resend 等)。OAuth トークンは Supabase Vault | External-service config; OAuth tokens vaulted. |
marketing | marketing_brand | ブランド設定 (単一行 id=1)。ロゴ / カラー / NG ワード / デフォルトハッシュタグ | Brand config (single row). |
marketing | marketing_assets | マーケ用画像・動画 (R2 + メタ + サムネ URL) | Marketing media (R2 + thumbnails). |
marketing | marketing_campaigns / marketing_campaign_items | キャンペーンと配信要素 (item_kind で参照先テーブルを判別する soft FK) | Campaigns + delivery items. |
marketing | marketing_activity_log | マーケ操作の監査ログ (admin 系とは別系統) | Marketing operator audit log. |
marketing | x_accounts | 接続済 X アカウント。refresh token は Vault | Connected X accounts; tokens vaulted. |
marketing | x_posts | X 投稿 (draft / scheduled / sent / failed を status で管理) | X posts (draft / scheduled / sent / failed). |
marketing | x_schedule_rules / x_listen_rules / x_automation_log / x_competitors | 予約ルール・監視ルール・自動化ログ・競合トラッキング | Scheduling / listening rules + automation log + competitor tracking. |
marketing | newsletter_subscribers | TOKYO CAR LIFE メルマガ購読者。marketing schema にあるため anon GRANT は無く、登録は BFF (POST /v1/marketing/newsletter/subscribers) 経由 | Newsletter subscribers; signup goes through the BFF, not direct anon INSERT. |
marketing | newsletter_broadcasts | 配信履歴 (対象 / 件数 / 送信ステータス) | Broadcast history. |
認可: requireMarketing ミドルウェアが admin.admins と admin.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.
| Schema | Table | 役割 | Purpose |
|---|---|---|---|
marketing | store_integrations | 連携先設定 (App Store / Google Play)。API キー / vendor number | Store connection config. |
marketing | store_sales_daily | 日次売上 (product_id × country_code × date)。revenue_transactions へ集約 | Daily sales rolled up to revenue. |
marketing | store_app_metrics_daily | 日次アプリ指標 (インストール / クラッシュ率 / 評価平均) | Daily app metrics (installs / crashes / ratings). |
marketing | store_reviews | 外部ストアレビュー。external_review_id で差分取込、reply_body で運営返信 | External reviews + replies. |
marketing | store_sync_runs | 同期ジョブ実行履歴 (cron / manual) | Sync job runs. |
analytics | sns_follower_snapshots | SNS フォロワー数の日次スナップショット (JST 09:00 cron) | Daily SNS follower snapshots (09:00 JST cron). |
VIEW 一覧View catalogue
| Schema | View | 役割 | Purpose |
|---|---|---|---|
public | activity_display_rules | activity_exp_rules の公開向けセーフ view | Public-safe view of activity rules. |
public | area_sponsors | area_places WHERE is_sponsored=true の後方互換 view | Backwards-compat sponsor filter. |
public | parking_lot_avg_rating | 承認済レビューの平均評価 (security_invoker=true) | Avg rating from approved reviews. |
public | parking_lot_min_hourly_rate | 時間課金ルールの最安 rate (security_invoker=true) | Cheapest hourly rate per lot. |
public | parking_spots_effective | spot 状態 + pricing group の有効値を結合した参照ビュー | Effective view joining spot state with its pricing group. |
public | revenue_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). |
public | gamification_anomaly_daily_cap_hits | 直近 48h の cap ヒット集計 (異常検知) | Last-48h cap-hit anomaly view. |
public | gamification_anomaly_geo_unverified | 直近 48h の geo 検証失敗集計 | Last-48h geo-fail anomaly view. |
public | gamification_anomaly_top_exp_users_24h | 直近 24h の TOP100 EXP 獲得者 | Top-100 24h XP earners. |
public | gamification_pending_referrals | 直近 30 日の紹介適用状況 | 30-day referral application status. |
admin | app_config_all | public.app_config + admin.app_config 統合読取 | Joined config view. |
admin | app_config_history_all | 同上の履歴統合 | Joined config-history view. |
論理 ER 図 (主要テーブル)Logical ER diagram (core tables)
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
%% エンティティをクリックして関連ドキュメントへ
codes テーブルで管理されます。CHECK 制約に日本語は入れません (Conventions)。
All enum values live in codes. Never put Japanese into CHECK constraints — see the Conventions page.