Ride-Hailing App ER diagram and database schema

The Ride-Hailing App database schema is a DB Planner template with 27 tables, 260 columns and 58 relationships, free to use. Core tables include dispatch_offers, driver_documents, driver_earnings, driver_location_pings. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the Ride-Hailing App database schema, showing 27 tables and their relationships
FIG. 1: entity relationship diagram, 27 tables
Tables
27
Columns
260
Relationships
58
Category
Logistics
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete ride-hailing app database design, modeled on how real ride-hailing platforms dispatch and price rides: 27 tables, 21 enums and 58 relationships covering markets, zones and product tiers, versioned rate cards and surge, riders and payment methods, ride requests, fare estimates and dispatch offers, trips, cancellations and two-way ratings, the itemized receipt, the driver earnings ledger and payouts, driver documents and vehicles, and online sessions with live location. THE FOUR DESIGN RULES 1. A REQUEST is not a TRIP. A ride request is the rider asking; a trip exists only once a driver accepts. Requests that find no driver, or are cancelled while searching, stay as requests, and counted per zone they are exactly the demand signal surge pricing needs. 2. Every dispatch offer is a row. Each driver offered the job gets a row that ends accepted, declined, expired or withdrawn, so acceptance rate is a query, and a partial unique index allows only one accepted offer per request: two drivers can never both win the same ride. 3. Prices are locked, then itemized. The fare estimate points at the exact rate card version and surge window it used and copies the multiplier; the trip keeps that multiplier, and the final fare is itemized lines (base, distance, time, surge, fees, tolls, promo, tip, tax). What the rider paid and what the driver earned are separate ledgers, so the platform take is the difference, never a stored column. 4. Latest position and location history are different tables. driver_locations holds one row per online driver, overwritten every few seconds and indexed with GiST for nearest-driver search; driver_location_pings is the append-only GPS stream, partitioned by day and dropped a partition at a time. Dispatch never reads the stream. DETAILS WORTH STEALING - Trips are a status machine with a timestamp per state (accepted, arrived, started, completed, cancelled), so pickup wait and ride time are plain subtractions. - Surge is stored per zone, tier and time window together with the open requests and available drivers that produced it, so any surged price can be explained in a dispute. - Zones are hexagonal grid cells, a fixed grid that keeps surge history comparable over time, and airport zones are flagged for queue-based dispatch. - Cancellations record who cancelled, why, how many seconds after acceptance (checked against the free cancellation window) and the share of the fee that compensates the driver. - Driver documents are reviewed one at a time with expiry dates, and a renewal is a new row, so the verification audit trail survives. - Payments carry an idempotency key, so a retry after a timeout can never charge a rider twice. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: riders, markets and pricing, dispatch, trips, money, drivers and vehicles, and driver supply and location. Every table carries a note. Postgres-flavoured types, with PostGIS geography columns for locations; the rest ports cleanly to MySQL or SQL Server. Useful for developers building a ride-hailing, taxi or on-demand mobility app, and for students who need a realistic ride-hailing app ER diagram for a DBMS project. This is a schema design reference; fare regulation, driver classification and tax rules vary by market and belong in your own business logic.

Tables (27)

Every table and its columns

service_areas

A market the service operates in. Currency, timezone, fare rules and driver licensing are all per market.

Columns of the service_areas table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(20)unique, not nullShort market code, e.g. "chi", "lon"
namevarchar(120)not null
countrychar(2)not null
timezonevarchar(64)not nullIANA zone. Surge windows, payout weeks and receipts use it.
currencychar(3)not null
boundarygeography(MultiPolygon,4326)not nullRequests with a pickup outside every boundary are refused
is_activebooleannot null, default true
launched_ondate

zones

Small cells inside a market. Supply, demand and surge are measured per zone, never per city.

Columns of the zones table
ColumnTypeConstraintsReferencesDescription
iduuidPK
service_area_iduuidFK, not nullservice_areas.id
cell_idvarchar(20)unique, not nullHexagonal grid cell id (e.g. H3 at resolution 8). A fixed grid keeps surge history comparable over time.
labelvarchar(120)Optional human name, e.g. "Airport", "Stadium"
is_airportbooleannot null, default falseAirport zones usually run a first-in, first-out driver queue instead of nearest-driver dispatch

product_tiers

What a rider picks on the selection screen. A vehicle QUALIFIES for tiers (vehicle_product_tiers); it is not one tier.

Columns of the product_tiers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(30)unique, not nulle.g. economy, comfort, xl, premium, accessible
namevarchar(100)not null
seatssmallintnot null
min_vehicle_yearsmallintOldest model year eligible for the tier
is_sharedbooleannot null, default falsePooled rides that can carry more than one request at once
sort_ordersmallintnot null, default 0

fare_rules

Rate card per market and tier, versioned by validity window and never edited in place. Estimates and trips point at the exact version they used.

Columns of the fare_rules table
ColumnTypeConstraintsReferencesDescription
iduuidPK
service_area_iduuidFK, not nullservice_areas.id
product_tier_iduuidFK, not nullproduct_tiers.id
base_fare_centsintegernot null
per_km_centsintegernot null
per_minute_centsintegernot null
minimum_fare_centsintegernot null
booking_fee_centsintegernot null, default 0Flat platform fee, not subject to surge
cancellation_fee_centsintegernot null
free_cancel_secondsintegernot null, default 120Rider may cancel free of charge for this long after a driver accepts
no_show_wait_secondsintegernot null, default 300How long a driver waits at pickup before a no-show fee applies
valid_fromtimestamptznot null
valid_totimestamptzNull for the rate card in force now

Indexes: (service_area_id, product_tier_id, valid_from) unique

surge_multipliers

Surge per zone, per tier, per short time window (a few minutes), stored with the supply and demand that produced it. Kept as history so any quoted price can be explained in a dispute.

Columns of the surge_multipliers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
zone_iduuidFK, not nullzones.id
product_tier_iduuidFK, not nullproduct_tiers.id
window_starttimestamptznot null
window_endtimestamptznot null
multipliernumeric(4,2)not null1.00 means no surge
open_requestsintegernot nullDemand seen when the multiplier was computed
available_driversintegernot nullSupply seen when the multiplier was computed
computed_attimestamptznot null

Indexes: (zone_id, product_tier_id, window_start) unique

promo_codes

Discount codes. Platform funded: a promo lowers what the rider pays and never what the driver earns.

Columns of the promo_codes table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(30)unique, not null
service_area_iduuidFKservice_areas.idNull for a code valid in every market
discount_kinddiscount_kindnot null
discount_valueintegernot nullCents for a fixed amount, basis points for a percentage
max_discount_centsintegerCap on a percentage discount
max_redemptionsintegerAcross all riders; null for unlimited
per_rider_limitsmallintnot null, default 1
first_ride_onlybooleannot null, default false
valid_fromtimestamptznot null
valid_totimestamptz

riders

People who request rides.

Columns of the riders table
ColumnTypeConstraintsReferencesDescription
iduuidPK
phonevarchar(20)unique, not nullE.164. The login, and the number calls to the driver are masked through.
emailvarchar(254)unique
first_namevarchar(100)not null
last_namevarchar(100)
home_service_area_iduuidFKservice_areas.id
rating_avgnumeric(3,2)Cache of ratings received; recomputed, never edited
statusaccount_statusnot null, default 'active'
created_attimestamptznot null, default `now()`

saved_places

Shortcuts a rider picks from when setting a pickup or destination.

Columns of the saved_places table
ColumnTypeConstraintsReferencesDescription
iduuidPK
rider_iduuidFK, not nullriders.id
labelvarchar(60)not nulle.g. Home, Work, Gym
addressvarchar(300)not null
locationgeography(Point,4326)not null

payment_methods

Saved cards, wallets, business accounts and the cash option, stored as processor tokens.

Columns of the payment_methods table
ColumnTypeConstraintsReferencesDescription
iduuidPK
rider_iduuidFK, not nullriders.id
kindpayment_method_kindnot null
processor_tokenvarchar(200)Card and wallet data stays with the payment processor. Null for cash.
brandvarchar(20)
last4char(4)
expires_ondate
is_defaultbooleannot null, default false
created_attimestamptznot null, default `now()`

promo_redemptions

A rider claiming a code, and the trip it was eventually spent on.

Columns of the promo_redemptions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
promo_code_iduuidFK, not nullpromo_codes.id
rider_iduuidFK, not nullriders.id
trip_iduuidFK, uniquetrips.idSet when the discount is spent on a completed trip
claimed_attimestamptznot null, default `now()`
discount_centsintegerWhat it was actually worth, known once the fare is final

Indexes: (promo_code_id, rider_id)

fare_estimates

Every price shown to a rider, one row per tier on the selection screen. Most are never booked; the one the rider accepts is referenced by the request.

Columns of the fare_estimates table
ColumnTypeConstraintsReferencesDescription
iduuidPK
rider_iduuidFK, not nullriders.id
product_tier_iduuidFK, not nullproduct_tiers.id
fare_rule_iduuidFK, not nullfare_rules.id
surge_multiplier_iduuidFKsurge_multipliers.idNull when no surge was in effect
surge_multipliernumeric(4,2)not null, default 1Copied, so the quote stands even if the surge row is recomputed
pickupgeography(Point,4326)not null
dropoffgeography(Point,4326)not null
est_distance_mintegernot null
est_duration_sintegernot null
low_centsintegernot null
high_centsintegernot nullEqual to low_cents for an upfront fixed price
currencychar(3)not null
created_attimestamptznot null, default `now()`
expires_attimestamptznot nullThe quote is honoured only until here, typically a few minutes

ride_requests

The rider asking for a ride. It exists before any driver is involved and often never becomes a trip (no drivers nearby, cancelled while searching). Those unfulfilled requests are exactly the demand signal surge pricing needs.

Columns of the ride_requests table
ColumnTypeConstraintsReferencesDescription
iduuidPK
rider_iduuidFK, not nullriders.id
product_tier_iduuidFK, not nullproduct_tiers.id
fare_estimate_iduuidFK, unique, not nullfare_estimates.idThe quote the rider accepted
payment_method_iduuidFK, not nullpayment_methods.id
promo_redemption_iduuidFKpromo_redemptions.id
pickup_zone_iduuidFK, not nullzones.id
pickup_locationgeography(Point,4326)not null
pickup_addressvarchar(300)not null
dropoff_locationgeography(Point,4326)
dropoff_addressvarchar(300)
seats_requestedsmallintnot null, default 1
statusrequest_statusnot null, default 'searching'
requested_attimestamptznot null, default `now()`
resolved_attimestamptzWhen it was matched, cancelled or gave up

Indexes: (pickup_zone_id, requested_at), (rider_id, requested_at)

dispatch_offers

Every offer made to a driver and how it ended: accepted, declined, expired or withdrawn. A request that cascades through three drivers leaves three rows.

Columns of the dispatch_offers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
ride_request_iduuidFK, not nullride_requests.id
driver_iduuidFK, not nulldrivers.id
attemptsmallintnot null1 for the first driver offered the job, 2 for the next, and so on
pickup_eta_sintegernot nullDriving time to pickup at the moment of the offer
pickup_distance_mintegernot null
statusoffer_statusnot null, default 'offered'
offered_attimestamptznot null
expires_attimestamptznot nullUsually about 15 seconds after offered_at
responded_attimestamptz
decline_reasonvarchar(100)

Indexes: (ride_request_id, attempt) unique, (driver_id, offered_at), (ride_request_id)

trips

A matched ride. status runs driver_en_route, arrived, in_progress, then completed or cancelled, and every state has its own timestamp column, so pickup wait, ETA accuracy and ride time are plain subtractions.

Columns of the trips table
ColumnTypeConstraintsReferencesDescription
iduuidPK
ride_request_iduuidFK, unique, not nullride_requests.id
dispatch_offer_iduuidFK, unique, not nulldispatch_offers.idThe accepted offer that created this trip
rider_iduuidFK, not nullriders.idCopied from the request for the trip history query
driver_iduuidFK, not nulldrivers.id
vehicle_iduuidFK, not nullvehicles.id
product_tier_iduuidFK, not nullproduct_tiers.id
fare_rule_iduuidFK, not nullfare_rules.idRate card version the final fare is computed under
surge_multipliernumeric(4,2)not null, default 1Locked from the estimate, never re-read at drop-off
statustrip_statusnot null, default 'driver_en_route'
accepted_attimestamptznot null
arrived_attimestamptzDriver at pickup; the no-show wait starts here
started_attimestamptzRider on board, meter running
completed_attimestamptz
cancelled_attimestamptz
actual_pickupgeography(Point,4326)
actual_dropoffgeography(Point,4326)
distance_mintegerMeasured from the location stream, not taken from the estimate
duration_sinteger
fare_total_centsintegerSum of fare_line_items, cached once the fare is final
currencychar(3)not null

Indexes: (driver_id, accepted_at), (rider_id, accepted_at)

trip_cancellations

Who cancelled, why, and what it cost. A late rider cancel or a no-show carries a fee, and part of it compensates the driver.

Columns of the trip_cancellations table
ColumnTypeConstraintsReferencesDescription
iduuidPK
ride_request_iduuidFK, unique, not nullride_requests.id
trip_iduuidFK, uniquetrips.idNull when the rider cancelled before any driver accepted
cancelled_bycancel_partynot null
reasoncancel_reasonnot null
cancelled_attimestamptznot null
seconds_after_acceptintegerCompared against the free cancellation window of the fare rule
fee_centsintegernot null, default 0
driver_compensation_centsintegernot null, default 0Share of the fee paid to the driver for the wasted drive
fee_waived_byvarchar(120)Support agent who waived the fee, if anyone did

ratings

Two-way ratings: the rider rates the driver and the driver rates the rider. The averages cached on riders and drivers are recomputed from these rows.

Columns of the ratings table
ColumnTypeConstraintsReferencesDescription
iduuidPK
trip_iduuidFK, not nulltrips.id
directionrating_directionnot null
starssmallintnot null1 to 5
commentvarchar(1000)
created_attimestamptznot null, default `now()`

Indexes: (trip_id, direction) unique

fare_line_items

The itemized receipt: base, distance, time, surge, booking fee, wait time, tolls, airport fee, promo, tip, tax. The rider total is their sum.

Columns of the fare_line_items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
trip_iduuidFK, not nulltrips.id
componentfare_componentnot null
descriptionvarchar(200)not nullAs printed on the receipt, e.g. "12.4 km x 1.10", "Surge 1.6x"
amount_centsintegernot nullNegative for a promo discount

payments

Rider card activity as rows: an authorization when the request is placed, the capture at drop-off, a separate charge for a tip added later, refunds after a support review.

Columns of the payments table
ColumnTypeConstraintsReferencesDescription
iduuidPK
ride_request_iduuidFK, not nullride_requests.idEvery charge traces back to a request, including a cancellation fee with no trip
trip_iduuidFKtrips.id
payment_method_iduuidFK, not nullpayment_methods.id
kindpayment_kindnot null
statuspayment_statusnot null, default 'pending'
amount_centsintegernot null
currencychar(3)not null
parent_payment_iduuidFKpayments.idA capture points at its authorization, a refund at its capture
idempotency_keyvarchar(100)unique, not nullA retry after a timeout can never charge twice
processor_referencevarchar(100)unique
created_attimestamptznot null, default `now()`

driver_earnings

The driver side ledger: fare share, surge share, tips passed through in full, cancellation compensation, bonuses and adjustments. The platform take is what the rider paid minus these rows, never a stored column.

Columns of the driver_earnings table
ColumnTypeConstraintsReferencesDescription
iduuidPK
driver_iduuidFK, not nulldrivers.id
trip_iduuidFKtrips.idNull for earnings not tied to one trip, e.g. a weekly bonus
trip_cancellation_iduuidFKtrip_cancellations.id
driver_payout_iduuidFKdriver_payouts.idNull until swept into a payout
kindearning_kindnot null
amount_centsintegernot nullNegative for an adjustment or clawback
currencychar(3)not null
earned_attimestamptznot null

Indexes: (driver_id, earned_at), (driver_payout_id)

driver_payouts

Transfers to the driver bank account: weekly by default, or an instant cash-out for a fee.

Columns of the driver_payouts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
driver_iduuidFK, not nulldrivers.id
kindpayout_kindnot null
period_startdatenot null
period_enddatenot null
amount_centsbigintnot nullSum of the earnings rows it sweeps
fee_centsintegernot null, default 0Charged for an instant cash-out
currencychar(3)not null
statuspayout_statusnot null, default 'pending'
processor_referencevarchar(100)unique
initiated_attimestamptznot null
paid_attimestamptz

drivers

People who drive. status moves from applicant to active only once every required document is approved.

Columns of the drivers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
phonevarchar(20)unique, not null
emailvarchar(254)unique, not null
first_namevarchar(100)not null
last_namevarchar(100)not null
service_area_iduuidFK, not nullservice_areas.idThe market the driver is licensed to work in
statusdriver_statusnot null, default 'applicant'
rating_avgnumeric(3,2)Cache of ratings received
acceptance_ratenumeric(5,4)Cache computed from dispatch_offers over a trailing window
payout_account_tokenvarchar(200)Bank account held by the payment processor
approved_attimestamptz
created_attimestamptznot null, default `now()`

driver_documents

License, background check, registration, insurance and inspection, each reviewed on its own. A renewal is a new row; the old one stays as the audit trail.

Columns of the driver_documents table
ColumnTypeConstraintsReferencesDescription
iduuidPK
driver_iduuidFK, not nulldrivers.id
vehicle_iduuidFKvehicles.idSet for vehicle documents: registration, insurance, inspection
kinddocument_kindnot null
storage_keyvarchar(300)not nullObject storage key. The scan never lives in the database.
document_numbervarchar(60)
expires_ondateA nightly job suspends drivers whose required documents lapse
statusdocument_statusnot null, default 'pending'
reviewed_byvarchar(120)Ops reviewer, or the background check vendor
reviewed_attimestamptz
rejection_reasonvarchar(300)
submitted_attimestamptznot null, default `now()`

Indexes: (driver_id, kind, status)

vehicles

Cars registered to a driver. A driver may have several, but drives one per session.

Columns of the vehicles table
ColumnTypeConstraintsReferencesDescription
iduuidPK
driver_iduuidFK, not nulldrivers.id
vinchar(17)unique, not null
platevarchar(15)not null
plate_regionvarchar(60)not null
makevarchar(60)not null
modelvarchar(60)not null
model_yearsmallintnot null
colorvarchar(30)not nullShown to the rider beside the plate so they find the right car
seatssmallintnot null
wheelchair_accessiblebooleannot null, default false
statusvehicle_statusnot null, default 'pending'

vehicle_product_tiers

Which tiers a vehicle qualifies for. A large new car can serve economy, comfort and xl at once.

Columns of the vehicle_product_tiers table
ColumnTypeConstraintsReferences
vehicle_iduuidFK, not nullvehicles.id
product_tier_iduuidFK, not nullproduct_tiers.id
approved_attimestamptznot null

driver_sessions

Each stretch a driver is online. Hours-online limits, utilization and fatigue rules are computed from these rows.

Columns of the driver_sessions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
driver_iduuidFK, not nulldrivers.id
vehicle_iduuidFK, not nullvehicles.id
service_area_iduuidFK, not nullservice_areas.id
started_attimestamptznot null
ended_attimestamptzNull while online
end_reasonsession_end_reason

Indexes: (driver_id, started_at), (driver_id)

driver_locations

The LATEST position of each online driver: one row per driver, overwritten every few seconds and deleted when the session ends. Dispatch reads only this small table, never the stream.

Columns of the driver_locations table
ColumnTypeConstraintsReferencesDescription
driver_iduuidPK, FKdrivers.id
driver_session_iduuidFK, not nulldriver_sessions.id
locationgeography(Point,4326)not null
heading_degsmallint
speed_kphsmallint
availabilitydriver_availabilitynot null
zone_iduuidFK, not nullzones.idDerived from location, so supply per zone is a simple count
updated_attimestamptznot null

Indexes: (location), (zone_id, availability)

driver_location_pings

Append-only GPS stream from every online driver, every few seconds: by far the highest-volume table in the system. Partition it by recorded_at (daily), keep raw pings for a fixed retention period, and drop whole partitions instead of deleting rows. Plain lat and lng columns keep inserts cheap; nothing on the dispatch path ever reads it.

Columns of the driver_location_pings table
ColumnTypeConstraintsReferencesDescription
driver_iduuidFK, not nulldrivers.id
recorded_attimestamptznot nullDevice time of the GPS fix
trip_iduuidFKtrips.idSet while on a trip, so the route can be rebuilt for a fare dispute
latnumeric(9,6)not null
lngnumeric(9,6)not null
accuracy_msmallint
speed_kphsmallint

Enums (21)

discount_kind
fixed_amount, percentage
account_status
active, suspended, banned, closed
payment_method_kind
card, wallet, business_account, cash
request_status
searching, matched, no_drivers_found, cancelled
offer_status
offered, accepted, declined, expired, withdrawn
trip_status
driver_en_route, arrived, in_progress, completed, cancelled
cancel_party
rider, driver, support, system
cancel_reason
changed_plans, driver_too_far, rider_no_show, wrong_pickup, vehicle_issue, safety_concern, other
rating_direction
rider_to_driver, driver_to_rider
fare_component
base, distance, time, surge, booking_fee, minimum_fare_top_up, wait_time, toll, airport_fee, promo, tip, tax
payment_kind
authorization, capture, release, charge, refund
payment_status
pending, succeeded, failed
earning_kind
fare_share, surge_share, tip, cancellation_compensation, bonus, adjustment
payout_kind
weekly, instant
payout_status
pending, paid, failed
driver_status
applicant, active, suspended, deactivated
document_kind
drivers_license, background_check, vehicle_registration, vehicle_insurance, vehicle_inspection, profile_photo
document_status
pending, approved, rejected, expired
vehicle_status
pending, active, inactive, rejected
session_end_reason
went_offline, app_timeout, hours_limit_reached, suspended
driver_availability
available, en_route_to_pickup, on_trip

Relationships (58)

  • dispatch_offers.driver_id references drivers.id many to one
  • dispatch_offers.id references trips.dispatch_offer_id one to one
  • dispatch_offers.ride_request_id references ride_requests.id many to one
  • driver_documents.driver_id references drivers.id many to one
  • driver_documents.vehicle_id references vehicles.id many to one
  • driver_earnings.driver_id references drivers.id many to one
  • driver_earnings.driver_payout_id references driver_payouts.id many to one
  • driver_earnings.trip_cancellation_id references trip_cancellations.id many to one
  • driver_earnings.trip_id references trips.id many to one
  • driver_location_pings.driver_id references drivers.id many to one
  • driver_location_pings.trip_id references trips.id many to one
  • driver_locations.driver_session_id references driver_sessions.id many to one
  • driver_locations.zone_id references zones.id many to one
  • driver_payouts.driver_id references drivers.id many to one
  • driver_sessions.driver_id references drivers.id many to one
  • driver_sessions.service_area_id references service_areas.id many to one
  • driver_sessions.vehicle_id references vehicles.id many to one
  • drivers.id references driver_locations.driver_id one to one
  • drivers.service_area_id references service_areas.id many to one
  • fare_estimates.fare_rule_id references fare_rules.id many to one
  • fare_estimates.id references ride_requests.fare_estimate_id one to one
  • fare_estimates.product_tier_id references product_tiers.id many to one
  • fare_estimates.rider_id references riders.id many to one
  • fare_estimates.surge_multiplier_id references surge_multipliers.id many to one
  • fare_line_items.trip_id references trips.id many to one
  • fare_rules.product_tier_id references product_tiers.id many to one
  • fare_rules.service_area_id references service_areas.id many to one
  • payment_methods.rider_id references riders.id many to one
  • payments.parent_payment_id references payments.id many to one
  • payments.payment_method_id references payment_methods.id many to one
  • payments.ride_request_id references ride_requests.id many to one
  • payments.trip_id references trips.id many to one
  • promo_codes.service_area_id references service_areas.id many to one
  • promo_redemptions.promo_code_id references promo_codes.id many to one
  • promo_redemptions.rider_id references riders.id many to one
  • promo_redemptions.trip_id references trips.id many to one
  • ratings.trip_id references trips.id many to one
  • ride_requests.id references trips.ride_request_id one to one
  • ride_requests.id references trip_cancellations.ride_request_id one to one
  • ride_requests.payment_method_id references payment_methods.id many to one
  • ride_requests.pickup_zone_id references zones.id many to one
  • ride_requests.product_tier_id references product_tiers.id many to one
  • ride_requests.promo_redemption_id references promo_redemptions.id many to one
  • ride_requests.rider_id references riders.id many to one
  • riders.home_service_area_id references service_areas.id many to one
  • saved_places.rider_id references riders.id many to one
  • surge_multipliers.product_tier_id references product_tiers.id many to one
  • surge_multipliers.zone_id references zones.id many to one
  • trips.driver_id references drivers.id many to one
  • trips.fare_rule_id references fare_rules.id many to one
  • trips.id references trip_cancellations.trip_id one to one
  • trips.product_tier_id references product_tiers.id many to one
  • trips.rider_id references riders.id many to one
  • trips.vehicle_id references vehicles.id many to one
  • vehicle_product_tiers.product_tier_id references product_tiers.id many to one
  • vehicle_product_tiers.vehicle_id references vehicles.id many to one
  • vehicles.driver_id references drivers.id many to one
  • zones.service_area_id references service_areas.id many to one

Ride-Hailing App database schema in DBML

The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.

ride-hailing-app.dbml dbml
// Ride-Hailing App
// Zones (header colors): markets and pricing (blue), riders (green),
// dispatch (amber), trips (coral), money (purple), drivers and vehicles (teal),
// driver supply and location (gray).

// ---------------------------------------------------------------------------
// MARKETS AND PRICING: where the service runs and what a ride costs there
// ---------------------------------------------------------------------------

Table service_areas [headercolor: #4c8bf5] {
  id uuid [pk]
  code varchar(20) [not null, unique, note: 'Short market code, e.g. "chi", "lon"']
  name varchar(120) [not null]
  country char(2) [not null]
  timezone varchar(64) [not null, note: 'IANA zone. Surge windows, payout weeks and receipts use it.']
  currency char(3) [not null]
  boundary geography(MultiPolygon,4326) [not null, note: 'Requests with a pickup outside every boundary are refused']
  is_active boolean [not null, default: true]
  launched_on date
  Note: 'A market the service operates in. Currency, timezone, fare rules and driver licensing are all per market.'
}

Table zones [headercolor: #4c8bf5] {
  id uuid [pk]
  service_area_id uuid [not null, ref: > service_areas.id]
  cell_id varchar(20) [not null, unique, note: 'Hexagonal grid cell id (e.g. H3 at resolution 8). A fixed grid keeps surge history comparable over time.']
  label varchar(120) [note: 'Optional human name, e.g. "Airport", "Stadium"']
  is_airport boolean [not null, default: false, note: 'Airport zones usually run a first-in, first-out driver queue instead of nearest-driver dispatch']
  Note: 'Small cells inside a market. Supply, demand and surge are measured per zone, never per city.'
}

Table product_tiers [headercolor: #4c8bf5] {
  id uuid [pk]
  code varchar(30) [not null, unique, note: 'e.g. economy, comfort, xl, premium, accessible']
  name varchar(100) [not null]
  seats smallint [not null]
  min_vehicle_year smallint [note: 'Oldest model year eligible for the tier']
  is_shared boolean [not null, default: false, note: 'Pooled rides that can carry more than one request at once']
  sort_order smallint [not null, default: 0]
  Note: 'What a rider picks on the selection screen. A vehicle QUALIFIES for tiers (vehicle_product_tiers); it is not one tier.'
}

Table fare_rules [headercolor: #4c8bf5] {
  id uuid [pk]
  service_area_id uuid [not null, ref: > service_areas.id]
  product_tier_id uuid [not null, ref: > product_tiers.id]
  base_fare_cents integer [not null]
  per_km_cents integer [not null]
  per_minute_cents integer [not null]
  minimum_fare_cents integer [not null]
  booking_fee_cents integer [not null, default: 0, note: 'Flat platform fee, not subject to surge']
  cancellation_fee_cents integer [not null]
  free_cancel_seconds integer [not null, default: 120, note: 'Rider may cancel free of charge for this long after a driver accepts']
  no_show_wait_seconds integer [not null, default: 300, note: 'How long a driver waits at pickup before a no-show fee applies']
  valid_from timestamptz [not null]
  valid_to timestamptz [note: 'Null for the rate card in force now']

  indexes {
    (service_area_id, product_tier_id, valid_from) [unique]
  }

  Note: 'Rate card per market and tier, versioned by validity window and never edited in place. Estimates and trips point at the exact version they used.'
}

Table surge_multipliers [headercolor: #4c8bf5] {
  id uuid [pk]
  zone_id uuid [not null, ref: > zones.id]
  product_tier_id uuid [not null, ref: > product_tiers.id]
  window_start timestamptz [not null]
  window_end timestamptz [not null]
  multiplier numeric(4,2) [not null, note: '1.00 means no surge']
  open_requests integer [not null, note: 'Demand seen when the multiplier was computed']
  available_drivers integer [not null, note: 'Supply seen when the multiplier was computed']
  computed_at timestamptz [not null]

  indexes {
    (zone_id, product_tier_id, window_start) [unique]
  }

  Note: 'Surge per zone, per tier, per short time window (a few minutes), stored with the supply and demand that produced it. Kept as history so any quoted price can be explained in a dispute.'
}

Table promo_codes [headercolor: #4c8bf5] {
  id uuid [pk]
  code varchar(30) [not null, unique]
  service_area_id uuid [ref: > service_areas.id, note: 'Null for a code valid in every market']
  discount_kind discount_kind [not null]
  discount_value integer [not null, note: 'Cents for a fixed amount, basis points for a percentage']
  max_discount_cents integer [note: 'Cap on a percentage discount']
  max_redemptions integer [note: 'Across all riders; null for unlimited']
  per_rider_limit smallint [not null, default: 1]
  first_ride_only boolean [not null, default: false]
  valid_from timestamptz [not null]
  valid_to timestamptz
  Note: 'Discount codes. Platform funded: a promo lowers what the rider pays and never what the driver earns.'
}

// ---------------------------------------------------------------------------
// RIDERS
// ---------------------------------------------------------------------------

Table riders [headercolor: #8bc34a] {
  id uuid [pk]
  phone varchar(20) [not null, unique, note: 'E.164. The login, and the number calls to the driver are masked through.']
  email varchar(254) [unique]
  first_name varchar(100) [not null]
  last_name varchar(100)
  home_service_area_id uuid [ref: > service_areas.id]
  rating_avg numeric(3,2) [note: 'Cache of ratings received; recomputed, never edited']
  status account_status [not null, default: 'active']
  created_at timestamptz [not null, default: `now()`]
  Note: 'People who request rides.'
}

Table saved_places [headercolor: #8bc34a] {
  id uuid [pk]
  rider_id uuid [not null, ref: > riders.id]
  label varchar(60) [not null, note: 'e.g. Home, Work, Gym']
  address varchar(300) [not null]
  location geography(Point,4326) [not null]
  Note: 'Shortcuts a rider picks from when setting a pickup or destination.'
}

Table payment_methods [headercolor: #8bc34a] {
  id uuid [pk]
  rider_id uuid [not null, ref: > riders.id]
  kind payment_method_kind [not null]
  processor_token varchar(200) [note: 'Card and wallet data stays with the payment processor. Null for cash.']
  brand varchar(20)
  last4 char(4)
  expires_on date
  is_default boolean [not null, default: false]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Saved cards, wallets, business accounts and the cash option, stored as processor tokens.'
}

Table promo_redemptions [headercolor: #8bc34a] {
  id uuid [pk]
  promo_code_id uuid [not null, ref: > promo_codes.id]
  rider_id uuid [not null, ref: > riders.id]
  trip_id uuid [unique, ref: > trips.id, note: 'Set when the discount is spent on a completed trip']
  claimed_at timestamptz [not null, default: `now()`]
  discount_cents integer [note: 'What it was actually worth, known once the fare is final']

  indexes {
    (promo_code_id, rider_id) [note: 'Per-rider limits are counted here']
  }

  Note: 'A rider claiming a code, and the trip it was eventually spent on.'
}

// ---------------------------------------------------------------------------
// DISPATCH: the ask, the price shown, and every driver offered the job
// ---------------------------------------------------------------------------

Table fare_estimates [headercolor: #f5b74c] {
  id uuid [pk]
  rider_id uuid [not null, ref: > riders.id]
  product_tier_id uuid [not null, ref: > product_tiers.id]
  fare_rule_id uuid [not null, ref: > fare_rules.id]
  surge_multiplier_id uuid [ref: > surge_multipliers.id, note: 'Null when no surge was in effect']
  surge_multiplier numeric(4,2) [not null, default: 1.00, note: 'Copied, so the quote stands even if the surge row is recomputed']
  pickup geography(Point,4326) [not null]
  dropoff geography(Point,4326) [not null]
  est_distance_m integer [not null]
  est_duration_s integer [not null]
  low_cents integer [not null]
  high_cents integer [not null, note: 'Equal to low_cents for an upfront fixed price']
  currency char(3) [not null]
  created_at timestamptz [not null, default: `now()`]
  expires_at timestamptz [not null, note: 'The quote is honoured only until here, typically a few minutes']
  Note: 'Every price shown to a rider, one row per tier on the selection screen. Most are never booked; the one the rider accepts is referenced by the request.'
}

Table ride_requests [headercolor: #f5b74c] {
  id uuid [pk]
  rider_id uuid [not null, ref: > riders.id]
  product_tier_id uuid [not null, ref: > product_tiers.id]
  fare_estimate_id uuid [not null, unique, ref: - fare_estimates.id, note: 'The quote the rider accepted']
  payment_method_id uuid [not null, ref: > payment_methods.id]
  promo_redemption_id uuid [ref: > promo_redemptions.id]
  pickup_zone_id uuid [not null, ref: > zones.id]
  pickup_location geography(Point,4326) [not null]
  pickup_address varchar(300) [not null]
  dropoff_location geography(Point,4326)
  dropoff_address varchar(300)
  seats_requested smallint [not null, default: 1]
  status request_status [not null, default: 'searching']
  requested_at timestamptz [not null, default: `now()`]
  resolved_at timestamptz [note: 'When it was matched, cancelled or gave up']

  indexes {
    (pickup_zone_id, requested_at) [note: 'Demand per zone per window, the input to surge']
    (rider_id, requested_at)
  }

  Note: 'The rider asking for a ride. It exists before any driver is involved and often never becomes a trip (no drivers nearby, cancelled while searching). Those unfulfilled requests are exactly the demand signal surge pricing needs.'
}

Table dispatch_offers [headercolor: #f5b74c] {
  id uuid [pk]
  ride_request_id uuid [not null, ref: > ride_requests.id]
  driver_id uuid [not null, ref: > drivers.id]
  attempt smallint [not null, note: '1 for the first driver offered the job, 2 for the next, and so on']
  pickup_eta_s integer [not null, note: 'Driving time to pickup at the moment of the offer']
  pickup_distance_m integer [not null]
  status offer_status [not null, default: 'offered']
  offered_at timestamptz [not null]
  expires_at timestamptz [not null, note: 'Usually about 15 seconds after offered_at']
  responded_at timestamptz
  decline_reason varchar(100)

  indexes {
    (ride_request_id, attempt) [unique]
    (driver_id, offered_at) [note: 'Acceptance rate per driver over a trailing window']
    ride_request_id [name: 'one_accepted_offer', note: 'Partial unique index WHERE status = accepted: two drivers can never both win a request']
  }

  Note: 'Every offer made to a driver and how it ended: accepted, declined, expired or withdrawn. A request that cascades through three drivers leaves three rows.'
}

// ---------------------------------------------------------------------------
// TRIPS: a matched ride, as a status machine
// ---------------------------------------------------------------------------

Table trips [headercolor: #f07178] {
  id uuid [pk]
  ride_request_id uuid [not null, unique, ref: - ride_requests.id]
  dispatch_offer_id uuid [not null, unique, ref: - dispatch_offers.id, note: 'The accepted offer that created this trip']
  rider_id uuid [not null, ref: > riders.id, note: 'Copied from the request for the trip history query']
  driver_id uuid [not null, ref: > drivers.id]
  vehicle_id uuid [not null, ref: > vehicles.id]
  product_tier_id uuid [not null, ref: > product_tiers.id]
  fare_rule_id uuid [not null, ref: > fare_rules.id, note: 'Rate card version the final fare is computed under']
  surge_multiplier numeric(4,2) [not null, default: 1.00, note: 'Locked from the estimate, never re-read at drop-off']
  status trip_status [not null, default: 'driver_en_route']
  accepted_at timestamptz [not null]
  arrived_at timestamptz [note: 'Driver at pickup; the no-show wait starts here']
  started_at timestamptz [note: 'Rider on board, meter running']
  completed_at timestamptz
  cancelled_at timestamptz
  actual_pickup geography(Point,4326)
  actual_dropoff geography(Point,4326)
  distance_m integer [note: 'Measured from the location stream, not taken from the estimate']
  duration_s integer
  fare_total_cents integer [note: 'Sum of fare_line_items, cached once the fare is final']
  currency char(3) [not null]

  indexes {
    (driver_id, accepted_at)
    (rider_id, accepted_at)
  }

  Note: 'A matched ride. status runs driver_en_route, arrived, in_progress, then completed or cancelled, and every state has its own timestamp column, so pickup wait, ETA accuracy and ride time are plain subtractions.'
}

Table trip_cancellations [headercolor: #f07178] {
  id uuid [pk]
  ride_request_id uuid [not null, unique, ref: - ride_requests.id]
  trip_id uuid [unique, ref: - trips.id, note: 'Null when the rider cancelled before any driver accepted']
  cancelled_by cancel_party [not null]
  reason cancel_reason [not null]
  cancelled_at timestamptz [not null]
  seconds_after_accept integer [note: 'Compared against the free cancellation window of the fare rule']
  fee_cents integer [not null, default: 0]
  driver_compensation_cents integer [not null, default: 0, note: 'Share of the fee paid to the driver for the wasted drive']
  fee_waived_by varchar(120) [note: 'Support agent who waived the fee, if anyone did']
  Note: 'Who cancelled, why, and what it cost. A late rider cancel or a no-show carries a fee, and part of it compensates the driver.'
}

Table ratings [headercolor: #f07178] {
  id uuid [pk]
  trip_id uuid [not null, ref: > trips.id]
  direction rating_direction [not null]
  stars smallint [not null, note: '1 to 5']
  comment varchar(1000)
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (trip_id, direction) [unique, note: 'Each side rates the other at most once per trip']
  }

  Note: 'Two-way ratings: the rider rates the driver and the driver rates the rider. The averages cached on riders and drivers are recomputed from these rows.'
}

// ---------------------------------------------------------------------------
// MONEY: what the rider paid and what the driver earned, kept apart
// ---------------------------------------------------------------------------

Table fare_line_items [headercolor: #b98cf0] {
  id uuid [pk]
  trip_id uuid [not null, ref: > trips.id]
  component fare_component [not null]
  description varchar(200) [not null, note: 'As printed on the receipt, e.g. "12.4 km x 1.10", "Surge 1.6x"']
  amount_cents integer [not null, note: 'Negative for a promo discount']
  Note: 'The itemized receipt: base, distance, time, surge, booking fee, wait time, tolls, airport fee, promo, tip, tax. The rider total is their sum.'
}

Table payments [headercolor: #b98cf0] {
  id uuid [pk]
  ride_request_id uuid [not null, ref: > ride_requests.id, note: 'Every charge traces back to a request, including a cancellation fee with no trip']
  trip_id uuid [ref: > trips.id]
  payment_method_id uuid [not null, ref: > payment_methods.id]
  kind payment_kind [not null]
  status payment_status [not null, default: 'pending']
  amount_cents integer [not null]
  currency char(3) [not null]
  parent_payment_id uuid [ref: > payments.id, note: 'A capture points at its authorization, a refund at its capture']
  idempotency_key varchar(100) [not null, unique, note: 'A retry after a timeout can never charge twice']
  processor_reference varchar(100) [unique]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Rider card activity as rows: an authorization when the request is placed, the capture at drop-off, a separate charge for a tip added later, refunds after a support review.'
}

Table driver_earnings [headercolor: #b98cf0] {
  id uuid [pk]
  driver_id uuid [not null, ref: > drivers.id]
  trip_id uuid [ref: > trips.id, note: 'Null for earnings not tied to one trip, e.g. a weekly bonus']
  trip_cancellation_id uuid [ref: > trip_cancellations.id]
  driver_payout_id uuid [ref: > driver_payouts.id, note: 'Null until swept into a payout']
  kind earning_kind [not null]
  amount_cents integer [not null, note: 'Negative for an adjustment or clawback']
  currency char(3) [not null]
  earned_at timestamptz [not null]

  indexes {
    (driver_id, earned_at)
    driver_payout_id
  }

  Note: 'The driver side ledger: fare share, surge share, tips passed through in full, cancellation compensation, bonuses and adjustments. The platform take is what the rider paid minus these rows, never a stored column.'
}

Table driver_payouts [headercolor: #b98cf0] {
  id uuid [pk]
  driver_id uuid [not null, ref: > drivers.id]
  kind payout_kind [not null]
  period_start date [not null]
  period_end date [not null]
  amount_cents bigint [not null, note: 'Sum of the earnings rows it sweeps']
  fee_cents integer [not null, default: 0, note: 'Charged for an instant cash-out']
  currency char(3) [not null]
  status payout_status [not null, default: 'pending']
  processor_reference varchar(100) [unique]
  initiated_at timestamptz [not null]
  paid_at timestamptz
  Note: 'Transfers to the driver bank account: weekly by default, or an instant cash-out for a fee.'
}

// ---------------------------------------------------------------------------
// DRIVERS AND VEHICLES: who may drive, in what
// ---------------------------------------------------------------------------

Table drivers [headercolor: #4cd0b0] {
  id uuid [pk]
  phone varchar(20) [not null, unique]
  email varchar(254) [not null, unique]
  first_name varchar(100) [not null]
  last_name varchar(100) [not null]
  service_area_id uuid [not null, ref: > service_areas.id, note: 'The market the driver is licensed to work in']
  status driver_status [not null, default: 'applicant']
  rating_avg numeric(3,2) [note: 'Cache of ratings received']
  acceptance_rate numeric(5,4) [note: 'Cache computed from dispatch_offers over a trailing window']
  payout_account_token varchar(200) [note: 'Bank account held by the payment processor']
  approved_at timestamptz
  created_at timestamptz [not null, default: `now()`]
  Note: 'People who drive. status moves from applicant to active only once every required document is approved.'
}

Table driver_documents [headercolor: #4cd0b0] {
  id uuid [pk]
  driver_id uuid [not null, ref: > drivers.id]
  vehicle_id uuid [ref: > vehicles.id, note: 'Set for vehicle documents: registration, insurance, inspection']
  kind document_kind [not null]
  storage_key varchar(300) [not null, note: 'Object storage key. The scan never lives in the database.']
  document_number varchar(60)
  expires_on date [note: 'A nightly job suspends drivers whose required documents lapse']
  status document_status [not null, default: 'pending']
  reviewed_by varchar(120) [note: 'Ops reviewer, or the background check vendor']
  reviewed_at timestamptz
  rejection_reason varchar(300)
  submitted_at timestamptz [not null, default: `now()`]

  indexes {
    (driver_id, kind, status)
  }

  Note: 'License, background check, registration, insurance and inspection, each reviewed on its own. A renewal is a new row; the old one stays as the audit trail.'
}

Table vehicles [headercolor: #4cd0b0] {
  id uuid [pk]
  driver_id uuid [not null, ref: > drivers.id]
  vin char(17) [not null, unique]
  plate varchar(15) [not null]
  plate_region varchar(60) [not null]
  make varchar(60) [not null]
  model varchar(60) [not null]
  model_year smallint [not null]
  color varchar(30) [not null, note: 'Shown to the rider beside the plate so they find the right car']
  seats smallint [not null]
  wheelchair_accessible boolean [not null, default: false]
  status vehicle_status [not null, default: 'pending']
  Note: 'Cars registered to a driver. A driver may have several, but drives one per session.'
}

Table vehicle_product_tiers [headercolor: #4cd0b0] {
  vehicle_id uuid [not null, ref: > vehicles.id]
  product_tier_id uuid [not null, ref: > product_tiers.id]
  approved_at timestamptz [not null]

  indexes {
    (vehicle_id, product_tier_id) [pk]
  }

  Note: 'Which tiers a vehicle qualifies for. A large new car can serve economy, comfort and xl at once.'
}

// ---------------------------------------------------------------------------
// DRIVER SUPPLY AND LOCATION: who is online, and where
// ---------------------------------------------------------------------------

Table driver_sessions [headercolor: #90a4ae] {
  id uuid [pk]
  driver_id uuid [not null, ref: > drivers.id]
  vehicle_id uuid [not null, ref: > vehicles.id]
  service_area_id uuid [not null, ref: > service_areas.id]
  started_at timestamptz [not null]
  ended_at timestamptz [note: 'Null while online']
  end_reason session_end_reason

  indexes {
    (driver_id, started_at)
    driver_id [name: 'one_open_session', note: 'Partial unique index WHERE ended_at IS NULL: one open session per driver']
  }

  Note: 'Each stretch a driver is online. Hours-online limits, utilization and fatigue rules are computed from these rows.'
}

Table driver_locations [headercolor: #90a4ae] {
  driver_id uuid [pk, ref: - drivers.id]
  driver_session_id uuid [not null, ref: > driver_sessions.id]
  location geography(Point,4326) [not null]
  heading_deg smallint
  speed_kph smallint
  availability driver_availability [not null]
  zone_id uuid [not null, ref: > zones.id, note: 'Derived from location, so supply per zone is a simple count']
  updated_at timestamptz [not null]

  indexes {
    location [type: gist, note: 'Nearest available drivers to a pickup']
    (zone_id, availability)
  }

  Note: 'The LATEST position of each online driver: one row per driver, overwritten every few seconds and deleted when the session ends. Dispatch reads only this small table, never the stream.'
}

Table driver_location_pings [headercolor: #90a4ae] {
  driver_id uuid [not null, ref: > drivers.id]
  recorded_at timestamptz [not null, note: 'Device time of the GPS fix']
  trip_id uuid [ref: > trips.id, note: 'Set while on a trip, so the route can be rebuilt for a fare dispute']
  lat numeric(9,6) [not null]
  lng numeric(9,6) [not null]
  accuracy_m smallint
  speed_kph smallint

  indexes {
    (driver_id, recorded_at) [pk, note: 'Includes recorded_at because a partitioned table needs the partition key in its primary key']
  }

  Note: '''Append-only GPS stream from every online driver, every few seconds: by far the highest-volume table in the system.
Partition it by recorded_at (daily), keep raw pings for a fixed retention period, and drop whole partitions instead of deleting rows.
Plain lat and lng columns keep inserts cheap; nothing on the dispatch path ever reads it.'''
}

// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------

Enum discount_kind {
  fixed_amount
  percentage
}

Enum account_status {
  active
  suspended
  banned
  closed
}

Enum payment_method_kind {
  card
  wallet
  business_account
  cash
}

Enum request_status {
  searching
  matched
  no_drivers_found
  cancelled
}

Enum offer_status {
  offered
  accepted
  declined
  expired
  withdrawn
}

Enum trip_status {
  driver_en_route
  arrived
  in_progress
  completed
  cancelled
}

Enum cancel_party {
  rider
  driver
  support
  system
}

Enum cancel_reason {
  changed_plans
  driver_too_far
  rider_no_show
  wrong_pickup
  vehicle_issue
  safety_concern
  other
}

Enum rating_direction {
  rider_to_driver
  driver_to_rider
}

Enum fare_component {
  base
  distance
  time
  surge
  booking_fee
  minimum_fare_top_up
  wait_time
  toll
  airport_fee
  promo
  tip
  tax
}

Enum payment_kind {
  authorization
  capture
  release
  charge
  refund
}

Enum payment_status {
  pending
  succeeded
  failed
}

Enum earning_kind {
  fare_share
  surge_share
  tip
  cancellation_compensation
  bonus
  adjustment
}

Enum payout_kind {
  weekly
  instant
}

Enum payout_status {
  pending
  paid
  failed
}

Enum driver_status {
  applicant
  active
  suspended
  deactivated
}

Enum document_kind {
  drivers_license
  background_check
  vehicle_registration
  vehicle_insurance
  vehicle_inspection
  profile_photo
}

Enum document_status {
  pending
  approved
  rejected
  expired
}

Enum vehicle_status {
  pending
  active
  inactive
  rejected
}

Enum session_end_reason {
  went_offline
  app_timeout
  hours_limit_reached
  suspended
}

Enum driver_availability {
  available
  en_route_to_pickup
  on_trip
}

Ride-Hailing App database schema as SQL

The same schema as CREATE TABLE statements, exported by DB Planner. PostgreSQL is shown first; MySQL and SQL Server are below it.

PostgreSQL
postgresql.sql PostgreSQL
CREATE TYPE "discount_kind" AS ENUM (
  'fixed_amount',
  'percentage'
);

CREATE TYPE "account_status" AS ENUM (
  'active',
  'suspended',
  'banned',
  'closed'
);

CREATE TYPE "payment_method_kind" AS ENUM (
  'card',
  'wallet',
  'business_account',
  'cash'
);

CREATE TYPE "request_status" AS ENUM (
  'searching',
  'matched',
  'no_drivers_found',
  'cancelled'
);

CREATE TYPE "offer_status" AS ENUM (
  'offered',
  'accepted',
  'declined',
  'expired',
  'withdrawn'
);

CREATE TYPE "trip_status" AS ENUM (
  'driver_en_route',
  'arrived',
  'in_progress',
  'completed',
  'cancelled'
);

CREATE TYPE "cancel_party" AS ENUM (
  'rider',
  'driver',
  'support',
  'system'
);

CREATE TYPE "cancel_reason" AS ENUM (
  'changed_plans',
  'driver_too_far',
  'rider_no_show',
  'wrong_pickup',
  'vehicle_issue',
  'safety_concern',
  'other'
);

CREATE TYPE "rating_direction" AS ENUM (
  'rider_to_driver',
  'driver_to_rider'
);

CREATE TYPE "fare_component" AS ENUM (
  'base',
  'distance',
  'time',
  'surge',
  'booking_fee',
  'minimum_fare_top_up',
  'wait_time',
  'toll',
  'airport_fee',
  'promo',
  'tip',
  'tax'
);

CREATE TYPE "payment_kind" AS ENUM (
  'authorization',
  'capture',
  'release',
  'charge',
  'refund'
);

CREATE TYPE "payment_status" AS ENUM (
  'pending',
  'succeeded',
  'failed'
);

CREATE TYPE "earning_kind" AS ENUM (
  'fare_share',
  'surge_share',
  'tip',
  'cancellation_compensation',
  'bonus',
  'adjustment'
);

CREATE TYPE "payout_kind" AS ENUM (
  'weekly',
  'instant'
);

CREATE TYPE "payout_status" AS ENUM (
  'pending',
  'paid',
  'failed'
);

CREATE TYPE "driver_status" AS ENUM (
  'applicant',
  'active',
  'suspended',
  'deactivated'
);

CREATE TYPE "document_kind" AS ENUM (
  'drivers_license',
  'background_check',
  'vehicle_registration',
  'vehicle_insurance',
  'vehicle_inspection',
  'profile_photo'
);

CREATE TYPE "document_status" AS ENUM (
  'pending',
  'approved',
  'rejected',
  'expired'
);

CREATE TYPE "vehicle_status" AS ENUM (
  'pending',
  'active',
  'inactive',
  'rejected'
);

CREATE TYPE "session_end_reason" AS ENUM (
  'went_offline',
  'app_timeout',
  'hours_limit_reached',
  'suspended'
);

CREATE TYPE "driver_availability" AS ENUM (
  'available',
  'en_route_to_pickup',
  'on_trip'
);

CREATE TABLE "service_areas" (
  "id" uuid PRIMARY KEY,
  "code" varchar(20) UNIQUE NOT NULL,
  "name" varchar(120) NOT NULL,
  "country" char(2) NOT NULL,
  "timezone" varchar(64) NOT NULL,
  "currency" char(3) NOT NULL,
  "boundary" "geography(MultiPolygon,4326)" NOT NULL,
  "is_active" boolean NOT NULL DEFAULT true,
  "launched_on" date
);

CREATE TABLE "zones" (
  "id" uuid PRIMARY KEY,
  "service_area_id" uuid NOT NULL,
  "cell_id" varchar(20) UNIQUE NOT NULL,
  "label" varchar(120),
  "is_airport" boolean NOT NULL DEFAULT false
);

CREATE TABLE "product_tiers" (
  "id" uuid PRIMARY KEY,
  "code" varchar(30) UNIQUE NOT NULL,
  "name" varchar(100) NOT NULL,
  "seats" smallint NOT NULL,
  "min_vehicle_year" smallint,
  "is_shared" boolean NOT NULL DEFAULT false,
  "sort_order" smallint NOT NULL DEFAULT 0
);

CREATE TABLE "fare_rules" (
  "id" uuid PRIMARY KEY,
  "service_area_id" uuid NOT NULL,
  "product_tier_id" uuid NOT NULL,
  "base_fare_cents" integer NOT NULL,
  "per_km_cents" integer NOT NULL,
  "per_minute_cents" integer NOT NULL,
  "minimum_fare_cents" integer NOT NULL,
  "booking_fee_cents" integer NOT NULL DEFAULT 0,
  "cancellation_fee_cents" integer NOT NULL,
  "free_cancel_seconds" integer NOT NULL DEFAULT 120,
  "no_show_wait_seconds" integer NOT NULL DEFAULT 300,
  "valid_from" timestamptz NOT NULL,
  "valid_to" timestamptz
);

CREATE TABLE "surge_multipliers" (
  "id" uuid PRIMARY KEY,
  "zone_id" uuid NOT NULL,
  "product_tier_id" uuid NOT NULL,
  "window_start" timestamptz NOT NULL,
  "window_end" timestamptz NOT NULL,
  "multiplier" numeric(4,2) NOT NULL,
  "open_requests" integer NOT NULL,
  "available_drivers" integer NOT NULL,
  "computed_at" timestamptz NOT NULL
);

CREATE TABLE "promo_codes" (
  "id" uuid PRIMARY KEY,
  "code" varchar(30) UNIQUE NOT NULL,
  "service_area_id" uuid,
  "discount_kind" discount_kind NOT NULL,
  "discount_value" integer NOT NULL,
  "max_discount_cents" integer,
  "max_redemptions" integer,
  "per_rider_limit" smallint NOT NULL DEFAULT 1,
  "first_ride_only" boolean NOT NULL DEFAULT false,
  "valid_from" timestamptz NOT NULL,
  "valid_to" timestamptz
);

CREATE TABLE "riders" (
  "id" uuid PRIMARY KEY,
  "phone" varchar(20) UNIQUE NOT NULL,
  "email" varchar(254) UNIQUE,
  "first_name" varchar(100) NOT NULL,
  "last_name" varchar(100),
  "home_service_area_id" uuid,
  "rating_avg" numeric(3,2),
  "status" account_status NOT NULL DEFAULT 'active',
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "saved_places" (
  "id" uuid PRIMARY KEY,
  "rider_id" uuid NOT NULL,
  "label" varchar(60) NOT NULL,
  "address" varchar(300) NOT NULL,
  "location" "geography(Point,4326)" NOT NULL
);

CREATE TABLE "payment_methods" (
  "id" uuid PRIMARY KEY,
  "rider_id" uuid NOT NULL,
  "kind" payment_method_kind NOT NULL,
  "processor_token" varchar(200),
  "brand" varchar(20),
  "last4" char(4),
  "expires_on" date,
  "is_default" boolean NOT NULL DEFAULT false,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "promo_redemptions" (
  "id" uuid PRIMARY KEY,
  "promo_code_id" uuid NOT NULL,
  "rider_id" uuid NOT NULL,
  "trip_id" uuid UNIQUE,
  "claimed_at" timestamptz NOT NULL DEFAULT (now()),
  "discount_cents" integer
);

CREATE TABLE "fare_estimates" (
  "id" uuid PRIMARY KEY,
  "rider_id" uuid NOT NULL,
  "product_tier_id" uuid NOT NULL,
  "fare_rule_id" uuid NOT NULL,
  "surge_multiplier_id" uuid,
  "surge_multiplier" numeric(4,2) NOT NULL DEFAULT 1,
  "pickup" "geography(Point,4326)" NOT NULL,
  "dropoff" "geography(Point,4326)" NOT NULL,
  "est_distance_m" integer NOT NULL,
  "est_duration_s" integer NOT NULL,
  "low_cents" integer NOT NULL,
  "high_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "expires_at" timestamptz NOT NULL
);

CREATE TABLE "ride_requests" (
  "id" uuid PRIMARY KEY,
  "rider_id" uuid NOT NULL,
  "product_tier_id" uuid NOT NULL,
  "fare_estimate_id" uuid UNIQUE NOT NULL,
  "payment_method_id" uuid NOT NULL,
  "promo_redemption_id" uuid,
  "pickup_zone_id" uuid NOT NULL,
  "pickup_location" "geography(Point,4326)" NOT NULL,
  "pickup_address" varchar(300) NOT NULL,
  "dropoff_location" "geography(Point,4326)",
  "dropoff_address" varchar(300),
  "seats_requested" smallint NOT NULL DEFAULT 1,
  "status" request_status NOT NULL DEFAULT 'searching',
  "requested_at" timestamptz NOT NULL DEFAULT (now()),
  "resolved_at" timestamptz
);

CREATE TABLE "dispatch_offers" (
  "id" uuid PRIMARY KEY,
  "ride_request_id" uuid NOT NULL,
  "driver_id" uuid NOT NULL,
  "attempt" smallint NOT NULL,
  "pickup_eta_s" integer NOT NULL,
  "pickup_distance_m" integer NOT NULL,
  "status" offer_status NOT NULL DEFAULT 'offered',
  "offered_at" timestamptz NOT NULL,
  "expires_at" timestamptz NOT NULL,
  "responded_at" timestamptz,
  "decline_reason" varchar(100)
);

CREATE TABLE "trips" (
  "id" uuid PRIMARY KEY,
  "ride_request_id" uuid UNIQUE NOT NULL,
  "dispatch_offer_id" uuid UNIQUE NOT NULL,
  "rider_id" uuid NOT NULL,
  "driver_id" uuid NOT NULL,
  "vehicle_id" uuid NOT NULL,
  "product_tier_id" uuid NOT NULL,
  "fare_rule_id" uuid NOT NULL,
  "surge_multiplier" numeric(4,2) NOT NULL DEFAULT 1,
  "status" trip_status NOT NULL DEFAULT 'driver_en_route',
  "accepted_at" timestamptz NOT NULL,
  "arrived_at" timestamptz,
  "started_at" timestamptz,
  "completed_at" timestamptz,
  "cancelled_at" timestamptz,
  "actual_pickup" "geography(Point,4326)",
  "actual_dropoff" "geography(Point,4326)",
  "distance_m" integer,
  "duration_s" integer,
  "fare_total_cents" integer,
  "currency" char(3) NOT NULL
);

CREATE TABLE "trip_cancellations" (
  "id" uuid PRIMARY KEY,
  "ride_request_id" uuid UNIQUE NOT NULL,
  "trip_id" uuid UNIQUE,
  "cancelled_by" cancel_party NOT NULL,
  "reason" cancel_reason NOT NULL,
  "cancelled_at" timestamptz NOT NULL,
  "seconds_after_accept" integer,
  "fee_cents" integer NOT NULL DEFAULT 0,
  "driver_compensation_cents" integer NOT NULL DEFAULT 0,
  "fee_waived_by" varchar(120)
);

CREATE TABLE "ratings" (
  "id" uuid PRIMARY KEY,
  "trip_id" uuid NOT NULL,
  "direction" rating_direction NOT NULL,
  "stars" smallint NOT NULL,
  "comment" varchar(1000),
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "fare_line_items" (
  "id" uuid PRIMARY KEY,
  "trip_id" uuid NOT NULL,
  "component" fare_component NOT NULL,
  "description" varchar(200) NOT NULL,
  "amount_cents" integer NOT NULL
);

CREATE TABLE "payments" (
  "id" uuid PRIMARY KEY,
  "ride_request_id" uuid NOT NULL,
  "trip_id" uuid,
  "payment_method_id" uuid NOT NULL,
  "kind" payment_kind NOT NULL,
  "status" payment_status NOT NULL DEFAULT 'pending',
  "amount_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "parent_payment_id" uuid,
  "idempotency_key" varchar(100) UNIQUE NOT NULL,
  "processor_reference" varchar(100) UNIQUE,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "driver_earnings" (
  "id" uuid PRIMARY KEY,
  "driver_id" uuid NOT NULL,
  "trip_id" uuid,
  "trip_cancellation_id" uuid,
  "driver_payout_id" uuid,
  "kind" earning_kind NOT NULL,
  "amount_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "earned_at" timestamptz NOT NULL
);

CREATE TABLE "driver_payouts" (
  "id" uuid PRIMARY KEY,
  "driver_id" uuid NOT NULL,
  "kind" payout_kind NOT NULL,
  "period_start" date NOT NULL,
  "period_end" date NOT NULL,
  "amount_cents" bigint NOT NULL,
  "fee_cents" integer NOT NULL DEFAULT 0,
  "currency" char(3) NOT NULL,
  "status" payout_status NOT NULL DEFAULT 'pending',
  "processor_reference" varchar(100) UNIQUE,
  "initiated_at" timestamptz NOT NULL,
  "paid_at" timestamptz
);

CREATE TABLE "drivers" (
  "id" uuid PRIMARY KEY,
  "phone" varchar(20) UNIQUE NOT NULL,
  "email" varchar(254) UNIQUE NOT NULL,
  "first_name" varchar(100) NOT NULL,
  "last_name" varchar(100) NOT NULL,
  "service_area_id" uuid NOT NULL,
  "status" driver_status NOT NULL DEFAULT 'applicant',
  "rating_avg" numeric(3,2),
  "acceptance_rate" numeric(5,4),
  "payout_account_token" varchar(200),
  "approved_at" timestamptz,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "driver_documents" (
  "id" uuid PRIMARY KEY,
  "driver_id" uuid NOT NULL,
  "vehicle_id" uuid,
  "kind" document_kind NOT NULL,
  "storage_key" varchar(300) NOT NULL,
  "document_number" varchar(60),
  "expires_on" date,
  "status" document_status NOT NULL DEFAULT 'pending',
  "reviewed_by" varchar(120),
  "reviewed_at" timestamptz,
  "rejection_reason" varchar(300),
  "submitted_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "vehicles" (
  "id" uuid PRIMARY KEY,
  "driver_id" uuid NOT NULL,
  "vin" char(17) UNIQUE NOT NULL,
  "plate" varchar(15) NOT NULL,
  "plate_region" varchar(60) NOT NULL,
  "make" varchar(60) NOT NULL,
  "model" varchar(60) NOT NULL,
  "model_year" smallint NOT NULL,
  "color" varchar(30) NOT NULL,
  "seats" smallint NOT NULL,
  "wheelchair_accessible" boolean NOT NULL DEFAULT false,
  "status" vehicle_status NOT NULL DEFAULT 'pending'
);

CREATE TABLE "vehicle_product_tiers" (
  "vehicle_id" uuid NOT NULL,
  "product_tier_id" uuid NOT NULL,
  "approved_at" timestamptz NOT NULL,
  PRIMARY KEY ("vehicle_id", "product_tier_id")
);

CREATE TABLE "driver_sessions" (
  "id" uuid PRIMARY KEY,
  "driver_id" uuid NOT NULL,
  "vehicle_id" uuid NOT NULL,
  "service_area_id" uuid NOT NULL,
  "started_at" timestamptz NOT NULL,
  "ended_at" timestamptz,
  "end_reason" session_end_reason
);

CREATE TABLE "driver_locations" (
  "driver_id" uuid PRIMARY KEY,
  "driver_session_id" uuid NOT NULL,
  "location" "geography(Point,4326)" NOT NULL,
  "heading_deg" smallint,
  "speed_kph" smallint,
  "availability" driver_availability NOT NULL,
  "zone_id" uuid NOT NULL,
  "updated_at" timestamptz NOT NULL
);

CREATE TABLE "driver_location_pings" (
  "driver_id" uuid NOT NULL,
  "recorded_at" timestamptz NOT NULL,
  "trip_id" uuid,
  "lat" numeric(9,6) NOT NULL,
  "lng" numeric(9,6) NOT NULL,
  "accuracy_m" smallint,
  "speed_kph" smallint,
  PRIMARY KEY ("driver_id", "recorded_at")
);

CREATE UNIQUE INDEX ON "fare_rules" ("service_area_id", "product_tier_id", "valid_from");

CREATE UNIQUE INDEX ON "surge_multipliers" ("zone_id", "product_tier_id", "window_start");

CREATE INDEX ON "promo_redemptions" ("promo_code_id", "rider_id");

CREATE INDEX ON "ride_requests" ("pickup_zone_id", "requested_at");

CREATE INDEX ON "ride_requests" ("rider_id", "requested_at");

CREATE UNIQUE INDEX ON "dispatch_offers" ("ride_request_id", "attempt");

CREATE INDEX ON "dispatch_offers" ("driver_id", "offered_at");

CREATE INDEX "one_accepted_offer" ON "dispatch_offers" ("ride_request_id");

CREATE INDEX ON "trips" ("driver_id", "accepted_at");

CREATE INDEX ON "trips" ("rider_id", "accepted_at");

CREATE UNIQUE INDEX ON "ratings" ("trip_id", "direction");

CREATE INDEX ON "driver_earnings" ("driver_id", "earned_at");

CREATE INDEX ON "driver_earnings" ("driver_payout_id");

CREATE INDEX ON "driver_documents" ("driver_id", "kind", "status");

CREATE INDEX ON "driver_sessions" ("driver_id", "started_at");

CREATE INDEX "one_open_session" ON "driver_sessions" ("driver_id");

CREATE INDEX ON "driver_locations" USING GIST ("location");

CREATE INDEX ON "driver_locations" ("zone_id", "availability");

COMMENT ON TABLE "service_areas" IS 'A market the service operates in. Currency, timezone, fare rules and driver licensing are all per market.';

COMMENT ON COLUMN "service_areas"."code" IS 'Short market code, e.g. "chi", "lon"';

COMMENT ON COLUMN "service_areas"."timezone" IS 'IANA zone. Surge windows, payout weeks and receipts use it.';

COMMENT ON COLUMN "service_areas"."boundary" IS 'Requests with a pickup outside every boundary are refused';

COMMENT ON TABLE "zones" IS 'Small cells inside a market. Supply, demand and surge are measured per zone, never per city.';

COMMENT ON COLUMN "zones"."cell_id" IS 'Hexagonal grid cell id (e.g. H3 at resolution 8). A fixed grid keeps surge history comparable over time.';

COMMENT ON COLUMN "zones"."label" IS 'Optional human name, e.g. "Airport", "Stadium"';

COMMENT ON COLUMN "zones"."is_airport" IS 'Airport zones usually run a first-in, first-out driver queue instead of nearest-driver dispatch';

COMMENT ON TABLE "product_tiers" IS 'What a rider picks on the selection screen. A vehicle QUALIFIES for tiers (vehicle_product_tiers); it is not one tier.';

COMMENT ON COLUMN "product_tiers"."code" IS 'e.g. economy, comfort, xl, premium, accessible';

COMMENT ON COLUMN "product_tiers"."min_vehicle_year" IS 'Oldest model year eligible for the tier';

COMMENT ON COLUMN "product_tiers"."is_shared" IS 'Pooled rides that can carry more than one request at once';

COMMENT ON TABLE "fare_rules" IS 'Rate card per market and tier, versioned by validity window and never edited in place. Estimates and trips point at the exact version they used.';

COMMENT ON COLUMN "fare_rules"."booking_fee_cents" IS 'Flat platform fee, not subject to surge';

COMMENT ON COLUMN "fare_rules"."free_cancel_seconds" IS 'Rider may cancel free of charge for this long after a driver accepts';

COMMENT ON COLUMN "fare_rules"."no_show_wait_seconds" IS 'How long a driver waits at pickup before a no-show fee applies';

COMMENT ON COLUMN "fare_rules"."valid_to" IS 'Null for the rate card in force now';

COMMENT ON TABLE "surge_multipliers" IS 'Surge per zone, per tier, per short time window (a few minutes), stored with the supply and demand that produced it. Kept as history so any quoted price can be explained in a dispute.';

COMMENT ON COLUMN "surge_multipliers"."multiplier" IS '1.00 means no surge';

COMMENT ON COLUMN "surge_multipliers"."open_requests" IS 'Demand seen when the multiplier was computed';

COMMENT ON COLUMN "surge_multipliers"."available_drivers" IS 'Supply seen when the multiplier was computed';

COMMENT ON TABLE "promo_codes" IS 'Discount codes. Platform funded: a promo lowers what the rider pays and never what the driver earns.';

COMMENT ON COLUMN "promo_codes"."service_area_id" IS 'Null for a code valid in every market';

COMMENT ON COLUMN "promo_codes"."discount_value" IS 'Cents for a fixed amount, basis points for a percentage';

COMMENT ON COLUMN "promo_codes"."max_discount_cents" IS 'Cap on a percentage discount';

COMMENT ON COLUMN "promo_codes"."max_redemptions" IS 'Across all riders; null for unlimited';

COMMENT ON TABLE "riders" IS 'People who request rides.';

COMMENT ON COLUMN "riders"."phone" IS 'E.164. The login, and the number calls to the driver are masked through.';

COMMENT ON COLUMN "riders"."rating_avg" IS 'Cache of ratings received; recomputed, never edited';

COMMENT ON TABLE "saved_places" IS 'Shortcuts a rider picks from when setting a pickup or destination.';

COMMENT ON COLUMN "saved_places"."label" IS 'e.g. Home, Work, Gym';

COMMENT ON TABLE "payment_methods" IS 'Saved cards, wallets, business accounts and the cash option, stored as processor tokens.';

COMMENT ON COLUMN "payment_methods"."processor_token" IS 'Card and wallet data stays with the payment processor. Null for cash.';

COMMENT ON TABLE "promo_redemptions" IS 'A rider claiming a code, and the trip it was eventually spent on.';

COMMENT ON COLUMN "promo_redemptions"."trip_id" IS 'Set when the discount is spent on a completed trip';

COMMENT ON COLUMN "promo_redemptions"."discount_cents" IS 'What it was actually worth, known once the fare is final';

COMMENT ON TABLE "fare_estimates" IS 'Every price shown to a rider, one row per tier on the selection screen. Most are never booked; the one the rider accepts is referenced by the request.';

COMMENT ON COLUMN "fare_estimates"."surge_multiplier_id" IS 'Null when no surge was in effect';

COMMENT ON COLUMN "fare_estimates"."surge_multiplier" IS 'Copied, so the quote stands even if the surge row is recomputed';

COMMENT ON COLUMN "fare_estimates"."high_cents" IS 'Equal to low_cents for an upfront fixed price';

COMMENT ON COLUMN "fare_estimates"."expires_at" IS 'The quote is honoured only until here, typically a few minutes';

COMMENT ON TABLE "ride_requests" IS 'The rider asking for a ride. It exists before any driver is involved and often never becomes a trip (no drivers nearby, cancelled while searching). Those unfulfilled requests are exactly the demand signal surge pricing needs.';

COMMENT ON COLUMN "ride_requests"."fare_estimate_id" IS 'The quote the rider accepted';

COMMENT ON COLUMN "ride_requests"."resolved_at" IS 'When it was matched, cancelled or gave up';

COMMENT ON TABLE "dispatch_offers" IS 'Every offer made to a driver and how it ended: accepted, declined, expired or withdrawn. A request that cascades through three drivers leaves three rows.';

COMMENT ON COLUMN "dispatch_offers"."attempt" IS '1 for the first driver offered the job, 2 for the next, and so on';

COMMENT ON COLUMN "dispatch_offers"."pickup_eta_s" IS 'Driving time to pickup at the moment of the offer';

COMMENT ON COLUMN "dispatch_offers"."expires_at" IS 'Usually about 15 seconds after offered_at';

COMMENT ON TABLE "trips" IS 'A matched ride. status runs driver_en_route, arrived, in_progress, then completed or cancelled, and every state has its own timestamp column, so pickup wait, ETA accuracy and ride time are plain subtractions.';

COMMENT ON COLUMN "trips"."dispatch_offer_id" IS 'The accepted offer that created this trip';

COMMENT ON COLUMN "trips"."rider_id" IS 'Copied from the request for the trip history query';

COMMENT ON COLUMN "trips"."fare_rule_id" IS 'Rate card version the final fare is computed under';

COMMENT ON COLUMN "trips"."surge_multiplier" IS 'Locked from the estimate, never re-read at drop-off';

COMMENT ON COLUMN "trips"."arrived_at" IS 'Driver at pickup; the no-show wait starts here';

COMMENT ON COLUMN "trips"."started_at" IS 'Rider on board, meter running';

COMMENT ON COLUMN "trips"."distance_m" IS 'Measured from the location stream, not taken from the estimate';

COMMENT ON COLUMN "trips"."fare_total_cents" IS 'Sum of fare_line_items, cached once the fare is final';

COMMENT ON TABLE "trip_cancellations" IS 'Who cancelled, why, and what it cost. A late rider cancel or a no-show carries a fee, and part of it compensates the driver.';

COMMENT ON COLUMN "trip_cancellations"."trip_id" IS 'Null when the rider cancelled before any driver accepted';

COMMENT ON COLUMN "trip_cancellations"."seconds_after_accept" IS 'Compared against the free cancellation window of the fare rule';

COMMENT ON COLUMN "trip_cancellations"."driver_compensation_cents" IS 'Share of the fee paid to the driver for the wasted drive';

COMMENT ON COLUMN "trip_cancellations"."fee_waived_by" IS 'Support agent who waived the fee, if anyone did';

COMMENT ON TABLE "ratings" IS 'Two-way ratings: the rider rates the driver and the driver rates the rider. The averages cached on riders and drivers are recomputed from these rows.';

COMMENT ON COLUMN "ratings"."stars" IS '1 to 5';

COMMENT ON TABLE "fare_line_items" IS 'The itemized receipt: base, distance, time, surge, booking fee, wait time, tolls, airport fee, promo, tip, tax. The rider total is their sum.';

COMMENT ON COLUMN "fare_line_items"."description" IS 'As printed on the receipt, e.g. "12.4 km x 1.10", "Surge 1.6x"';

COMMENT ON COLUMN "fare_line_items"."amount_cents" IS 'Negative for a promo discount';

COMMENT ON TABLE "payments" IS 'Rider card activity as rows: an authorization when the request is placed, the capture at drop-off, a separate charge for a tip added later, refunds after a support review.';

COMMENT ON COLUMN "payments"."ride_request_id" IS 'Every charge traces back to a request, including a cancellation fee with no trip';

COMMENT ON COLUMN "payments"."parent_payment_id" IS 'A capture points at its authorization, a refund at its capture';

COMMENT ON COLUMN "payments"."idempotency_key" IS 'A retry after a timeout can never charge twice';

COMMENT ON TABLE "driver_earnings" IS 'The driver side ledger: fare share, surge share, tips passed through in full, cancellation compensation, bonuses and adjustments. The platform take is what the rider paid minus these rows, never a stored column.';

COMMENT ON COLUMN "driver_earnings"."trip_id" IS 'Null for earnings not tied to one trip, e.g. a weekly bonus';

COMMENT ON COLUMN "driver_earnings"."driver_payout_id" IS 'Null until swept into a payout';

COMMENT ON COLUMN "driver_earnings"."amount_cents" IS 'Negative for an adjustment or clawback';

COMMENT ON TABLE "driver_payouts" IS 'Transfers to the driver bank account: weekly by default, or an instant cash-out for a fee.';

COMMENT ON COLUMN "driver_payouts"."amount_cents" IS 'Sum of the earnings rows it sweeps';

COMMENT ON COLUMN "driver_payouts"."fee_cents" IS 'Charged for an instant cash-out';

COMMENT ON TABLE "drivers" IS 'People who drive. status moves from applicant to active only once every required document is approved.';

COMMENT ON COLUMN "drivers"."service_area_id" IS 'The market the driver is licensed to work in';

COMMENT ON COLUMN "drivers"."rating_avg" IS 'Cache of ratings received';

COMMENT ON COLUMN "drivers"."acceptance_rate" IS 'Cache computed from dispatch_offers over a trailing window';

COMMENT ON COLUMN "drivers"."payout_account_token" IS 'Bank account held by the payment processor';

COMMENT ON TABLE "driver_documents" IS 'License, background check, registration, insurance and inspection, each reviewed on its own. A renewal is a new row; the old one stays as the audit trail.';

COMMENT ON COLUMN "driver_documents"."vehicle_id" IS 'Set for vehicle documents: registration, insurance, inspection';

COMMENT ON COLUMN "driver_documents"."storage_key" IS 'Object storage key. The scan never lives in the database.';

COMMENT ON COLUMN "driver_documents"."expires_on" IS 'A nightly job suspends drivers whose required documents lapse';

COMMENT ON COLUMN "driver_documents"."reviewed_by" IS 'Ops reviewer, or the background check vendor';

COMMENT ON TABLE "vehicles" IS 'Cars registered to a driver. A driver may have several, but drives one per session.';

COMMENT ON COLUMN "vehicles"."color" IS 'Shown to the rider beside the plate so they find the right car';

COMMENT ON TABLE "vehicle_product_tiers" IS 'Which tiers a vehicle qualifies for. A large new car can serve economy, comfort and xl at once.';

COMMENT ON TABLE "driver_sessions" IS 'Each stretch a driver is online. Hours-online limits, utilization and fatigue rules are computed from these rows.';

COMMENT ON COLUMN "driver_sessions"."ended_at" IS 'Null while online';

COMMENT ON TABLE "driver_locations" IS 'The LATEST position of each online driver: one row per driver, overwritten every few seconds and deleted when the session ends. Dispatch reads only this small table, never the stream.';

COMMENT ON COLUMN "driver_locations"."zone_id" IS 'Derived from location, so supply per zone is a simple count';

COMMENT ON TABLE "driver_location_pings" IS 'Append-only GPS stream from every online driver, every few seconds: by far the highest-volume table in the system.
Partition it by recorded_at (daily), keep raw pings for a fixed retention period, and drop whole partitions instead of deleting rows.
Plain lat and lng columns keep inserts cheap; nothing on the dispatch path ever reads it.';

COMMENT ON COLUMN "driver_location_pings"."recorded_at" IS 'Device time of the GPS fix';

COMMENT ON COLUMN "driver_location_pings"."trip_id" IS 'Set while on a trip, so the route can be rebuilt for a fare dispute';

ALTER TABLE "zones" ADD FOREIGN KEY ("service_area_id") REFERENCES "service_areas" ("id");

ALTER TABLE "fare_rules" ADD FOREIGN KEY ("service_area_id") REFERENCES "service_areas" ("id");

ALTER TABLE "fare_rules" ADD FOREIGN KEY ("product_tier_id") REFERENCES "product_tiers" ("id");

ALTER TABLE "surge_multipliers" ADD FOREIGN KEY ("zone_id") REFERENCES "zones" ("id");

ALTER TABLE "surge_multipliers" ADD FOREIGN KEY ("product_tier_id") REFERENCES "product_tiers" ("id");

ALTER TABLE "promo_codes" ADD FOREIGN KEY ("service_area_id") REFERENCES "service_areas" ("id");

ALTER TABLE "riders" ADD FOREIGN KEY ("home_service_area_id") REFERENCES "service_areas" ("id");

ALTER TABLE "saved_places" ADD FOREIGN KEY ("rider_id") REFERENCES "riders" ("id");

ALTER TABLE "payment_methods" ADD FOREIGN KEY ("rider_id") REFERENCES "riders" ("id");

ALTER TABLE "promo_redemptions" ADD FOREIGN KEY ("promo_code_id") REFERENCES "promo_codes" ("id");

ALTER TABLE "promo_redemptions" ADD FOREIGN KEY ("rider_id") REFERENCES "riders" ("id");

ALTER TABLE "promo_redemptions" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");

ALTER TABLE "fare_estimates" ADD FOREIGN KEY ("rider_id") REFERENCES "riders" ("id");

ALTER TABLE "fare_estimates" ADD FOREIGN KEY ("product_tier_id") REFERENCES "product_tiers" ("id");

ALTER TABLE "fare_estimates" ADD FOREIGN KEY ("fare_rule_id") REFERENCES "fare_rules" ("id");

ALTER TABLE "fare_estimates" ADD FOREIGN KEY ("surge_multiplier_id") REFERENCES "surge_multipliers" ("id");

ALTER TABLE "ride_requests" ADD FOREIGN KEY ("rider_id") REFERENCES "riders" ("id");

ALTER TABLE "ride_requests" ADD FOREIGN KEY ("product_tier_id") REFERENCES "product_tiers" ("id");

ALTER TABLE "ride_requests" ADD FOREIGN KEY ("fare_estimate_id") REFERENCES "fare_estimates" ("id");

ALTER TABLE "ride_requests" ADD FOREIGN KEY ("payment_method_id") REFERENCES "payment_methods" ("id");

ALTER TABLE "ride_requests" ADD FOREIGN KEY ("promo_redemption_id") REFERENCES "promo_redemptions" ("id");

ALTER TABLE "ride_requests" ADD FOREIGN KEY ("pickup_zone_id") REFERENCES "zones" ("id");

ALTER TABLE "dispatch_offers" ADD FOREIGN KEY ("ride_request_id") REFERENCES "ride_requests" ("id");

ALTER TABLE "dispatch_offers" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("ride_request_id") REFERENCES "ride_requests" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("dispatch_offer_id") REFERENCES "dispatch_offers" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("rider_id") REFERENCES "riders" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("vehicle_id") REFERENCES "vehicles" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("product_tier_id") REFERENCES "product_tiers" ("id");

ALTER TABLE "trips" ADD FOREIGN KEY ("fare_rule_id") REFERENCES "fare_rules" ("id");

ALTER TABLE "trip_cancellations" ADD FOREIGN KEY ("ride_request_id") REFERENCES "ride_requests" ("id");

ALTER TABLE "trip_cancellations" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");

ALTER TABLE "ratings" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");

ALTER TABLE "fare_line_items" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("ride_request_id") REFERENCES "ride_requests" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("payment_method_id") REFERENCES "payment_methods" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("parent_payment_id") REFERENCES "payments" ("id");

ALTER TABLE "driver_earnings" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "driver_earnings" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");

ALTER TABLE "driver_earnings" ADD FOREIGN KEY ("trip_cancellation_id") REFERENCES "trip_cancellations" ("id");

ALTER TABLE "driver_earnings" ADD FOREIGN KEY ("driver_payout_id") REFERENCES "driver_payouts" ("id");

ALTER TABLE "driver_payouts" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "drivers" ADD FOREIGN KEY ("service_area_id") REFERENCES "service_areas" ("id");

ALTER TABLE "driver_documents" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "driver_documents" ADD FOREIGN KEY ("vehicle_id") REFERENCES "vehicles" ("id");

ALTER TABLE "vehicles" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "vehicle_product_tiers" ADD FOREIGN KEY ("vehicle_id") REFERENCES "vehicles" ("id");

ALTER TABLE "vehicle_product_tiers" ADD FOREIGN KEY ("product_tier_id") REFERENCES "product_tiers" ("id");

ALTER TABLE "driver_sessions" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "driver_sessions" ADD FOREIGN KEY ("vehicle_id") REFERENCES "vehicles" ("id");

ALTER TABLE "driver_sessions" ADD FOREIGN KEY ("service_area_id") REFERENCES "service_areas" ("id");

ALTER TABLE "driver_locations" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "driver_locations" ADD FOREIGN KEY ("driver_session_id") REFERENCES "driver_sessions" ("id");

ALTER TABLE "driver_locations" ADD FOREIGN KEY ("zone_id") REFERENCES "zones" ("id");

ALTER TABLE "driver_location_pings" ADD FOREIGN KEY ("driver_id") REFERENCES "drivers" ("id");

ALTER TABLE "driver_location_pings" ADD FOREIGN KEY ("trip_id") REFERENCES "trips" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `service_areas` (
  `id` uuid PRIMARY KEY,
  `code` varchar(20) UNIQUE NOT NULL COMMENT 'Short market code, e.g. "chi", "lon"',
  `name` varchar(120) NOT NULL,
  `country` char(2) NOT NULL,
  `timezone` varchar(64) NOT NULL COMMENT 'IANA zone. Surge windows, payout weeks and receipts use it.',
  `currency` char(3) NOT NULL,
  `boundary` geography(MultiPolygon,4326) NOT NULL COMMENT 'Requests with a pickup outside every boundary are refused',
  `is_active` boolean NOT NULL DEFAULT true,
  `launched_on` date
);

CREATE TABLE `zones` (
  `id` uuid PRIMARY KEY,
  `service_area_id` uuid NOT NULL,
  `cell_id` varchar(20) UNIQUE NOT NULL COMMENT 'Hexagonal grid cell id (e.g. H3 at resolution 8). A fixed grid keeps surge history comparable over time.',
  `label` varchar(120) COMMENT 'Optional human name, e.g. "Airport", "Stadium"',
  `is_airport` boolean NOT NULL DEFAULT false COMMENT 'Airport zones usually run a first-in, first-out driver queue instead of nearest-driver dispatch'
);

CREATE TABLE `product_tiers` (
  `id` uuid PRIMARY KEY,
  `code` varchar(30) UNIQUE NOT NULL COMMENT 'e.g. economy, comfort, xl, premium, accessible',
  `name` varchar(100) NOT NULL,
  `seats` smallint NOT NULL,
  `min_vehicle_year` smallint COMMENT 'Oldest model year eligible for the tier',
  `is_shared` boolean NOT NULL DEFAULT false COMMENT 'Pooled rides that can carry more than one request at once',
  `sort_order` smallint NOT NULL DEFAULT 0
);

CREATE TABLE `fare_rules` (
  `id` uuid PRIMARY KEY,
  `service_area_id` uuid NOT NULL,
  `product_tier_id` uuid NOT NULL,
  `base_fare_cents` integer NOT NULL,
  `per_km_cents` integer NOT NULL,
  `per_minute_cents` integer NOT NULL,
  `minimum_fare_cents` integer NOT NULL,
  `booking_fee_cents` integer NOT NULL DEFAULT 0 COMMENT 'Flat platform fee, not subject to surge',
  `cancellation_fee_cents` integer NOT NULL,
  `free_cancel_seconds` integer NOT NULL DEFAULT 120 COMMENT 'Rider may cancel free of charge for this long after a driver accepts',
  `no_show_wait_seconds` integer NOT NULL DEFAULT 300 COMMENT 'How long a driver waits at pickup before a no-show fee applies',
  `valid_from` timestamptz NOT NULL,
  `valid_to` timestamptz COMMENT 'Null for the rate card in force now'
);

CREATE TABLE `surge_multipliers` (
  `id` uuid PRIMARY KEY,
  `zone_id` uuid NOT NULL,
  `product_tier_id` uuid NOT NULL,
  `window_start` timestamptz NOT NULL,
  `window_end` timestamptz NOT NULL,
  `multiplier` numeric(4,2) NOT NULL COMMENT '1.00 means no surge',
  `open_requests` integer NOT NULL COMMENT 'Demand seen when the multiplier was computed',
  `available_drivers` integer NOT NULL COMMENT 'Supply seen when the multiplier was computed',
  `computed_at` timestamptz NOT NULL
);

CREATE TABLE `promo_codes` (
  `id` uuid PRIMARY KEY,
  `code` varchar(30) UNIQUE NOT NULL,
  `service_area_id` uuid COMMENT 'Null for a code valid in every market',
  `discount_kind` ENUM ('fixed_amount', 'percentage') NOT NULL,
  `discount_value` integer NOT NULL COMMENT 'Cents for a fixed amount, basis points for a percentage',
  `max_discount_cents` integer COMMENT 'Cap on a percentage discount',
  `max_redemptions` integer COMMENT 'Across all riders; null for unlimited',
  `per_rider_limit` smallint NOT NULL DEFAULT 1,
  `first_ride_only` boolean NOT NULL DEFAULT false,
  `valid_from` timestamptz NOT NULL,
  `valid_to` timestamptz
);

CREATE TABLE `riders` (
  `id` uuid PRIMARY KEY,
  `phone` varchar(20) UNIQUE NOT NULL COMMENT 'E.164. The login, and the number calls to the driver are masked through.',
  `email` varchar(254) UNIQUE,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100),
  `home_service_area_id` uuid,
  `rating_avg` numeric(3,2) COMMENT 'Cache of ratings received; recomputed, never edited',
  `status` ENUM ('active', 'suspended', 'banned', 'closed') NOT NULL DEFAULT 'active',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `saved_places` (
  `id` uuid PRIMARY KEY,
  `rider_id` uuid NOT NULL,
  `label` varchar(60) NOT NULL COMMENT 'e.g. Home, Work, Gym',
  `address` varchar(300) NOT NULL,
  `location` geography(Point,4326) NOT NULL
);

CREATE TABLE `payment_methods` (
  `id` uuid PRIMARY KEY,
  `rider_id` uuid NOT NULL,
  `kind` ENUM ('card', 'wallet', 'business_account', 'cash') NOT NULL,
  `processor_token` varchar(200) COMMENT 'Card and wallet data stays with the payment processor. Null for cash.',
  `brand` varchar(20),
  `last4` char(4),
  `expires_on` date,
  `is_default` boolean NOT NULL DEFAULT false,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `promo_redemptions` (
  `id` uuid PRIMARY KEY,
  `promo_code_id` uuid NOT NULL,
  `rider_id` uuid NOT NULL,
  `trip_id` uuid UNIQUE COMMENT 'Set when the discount is spent on a completed trip',
  `claimed_at` timestamptz NOT NULL DEFAULT (now()),
  `discount_cents` integer COMMENT 'What it was actually worth, known once the fare is final'
);

CREATE TABLE `fare_estimates` (
  `id` uuid PRIMARY KEY,
  `rider_id` uuid NOT NULL,
  `product_tier_id` uuid NOT NULL,
  `fare_rule_id` uuid NOT NULL,
  `surge_multiplier_id` uuid COMMENT 'Null when no surge was in effect',
  `surge_multiplier` numeric(4,2) NOT NULL DEFAULT 1 COMMENT 'Copied, so the quote stands even if the surge row is recomputed',
  `pickup` geography(Point,4326) NOT NULL,
  `dropoff` geography(Point,4326) NOT NULL,
  `est_distance_m` integer NOT NULL,
  `est_duration_s` integer NOT NULL,
  `low_cents` integer NOT NULL,
  `high_cents` integer NOT NULL COMMENT 'Equal to low_cents for an upfront fixed price',
  `currency` char(3) NOT NULL,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `expires_at` timestamptz NOT NULL COMMENT 'The quote is honoured only until here, typically a few minutes'
);

CREATE TABLE `ride_requests` (
  `id` uuid PRIMARY KEY,
  `rider_id` uuid NOT NULL,
  `product_tier_id` uuid NOT NULL,
  `fare_estimate_id` uuid UNIQUE NOT NULL COMMENT 'The quote the rider accepted',
  `payment_method_id` uuid NOT NULL,
  `promo_redemption_id` uuid,
  `pickup_zone_id` uuid NOT NULL,
  `pickup_location` geography(Point,4326) NOT NULL,
  `pickup_address` varchar(300) NOT NULL,
  `dropoff_location` geography(Point,4326),
  `dropoff_address` varchar(300),
  `seats_requested` smallint NOT NULL DEFAULT 1,
  `status` ENUM ('searching', 'matched', 'no_drivers_found', 'cancelled') NOT NULL DEFAULT 'searching',
  `requested_at` timestamptz NOT NULL DEFAULT (now()),
  `resolved_at` timestamptz COMMENT 'When it was matched, cancelled or gave up'
);

CREATE TABLE `dispatch_offers` (
  `id` uuid PRIMARY KEY,
  `ride_request_id` uuid NOT NULL,
  `driver_id` uuid NOT NULL,
  `attempt` smallint NOT NULL COMMENT '1 for the first driver offered the job, 2 for the next, and so on',
  `pickup_eta_s` integer NOT NULL COMMENT 'Driving time to pickup at the moment of the offer',
  `pickup_distance_m` integer NOT NULL,
  `status` ENUM ('offered', 'accepted', 'declined', 'expired', 'withdrawn') NOT NULL DEFAULT 'offered',
  `offered_at` timestamptz NOT NULL,
  `expires_at` timestamptz NOT NULL COMMENT 'Usually about 15 seconds after offered_at',
  `responded_at` timestamptz,
  `decline_reason` varchar(100)
);

CREATE TABLE `trips` (
  `id` uuid PRIMARY KEY,
  `ride_request_id` uuid UNIQUE NOT NULL,
  `dispatch_offer_id` uuid UNIQUE NOT NULL COMMENT 'The accepted offer that created this trip',
  `rider_id` uuid NOT NULL COMMENT 'Copied from the request for the trip history query',
  `driver_id` uuid NOT NULL,
  `vehicle_id` uuid NOT NULL,
  `product_tier_id` uuid NOT NULL,
  `fare_rule_id` uuid NOT NULL COMMENT 'Rate card version the final fare is computed under',
  `surge_multiplier` numeric(4,2) NOT NULL DEFAULT 1 COMMENT 'Locked from the estimate, never re-read at drop-off',
  `status` ENUM ('driver_en_route', 'arrived', 'in_progress', 'completed', 'cancelled') NOT NULL DEFAULT 'driver_en_route',
  `accepted_at` timestamptz NOT NULL,
  `arrived_at` timestamptz COMMENT 'Driver at pickup; the no-show wait starts here',
  `started_at` timestamptz COMMENT 'Rider on board, meter running',
  `completed_at` timestamptz,
  `cancelled_at` timestamptz,
  `actual_pickup` geography(Point,4326),
  `actual_dropoff` geography(Point,4326),
  `distance_m` integer COMMENT 'Measured from the location stream, not taken from the estimate',
  `duration_s` integer,
  `fare_total_cents` integer COMMENT 'Sum of fare_line_items, cached once the fare is final',
  `currency` char(3) NOT NULL
);

CREATE TABLE `trip_cancellations` (
  `id` uuid PRIMARY KEY,
  `ride_request_id` uuid UNIQUE NOT NULL,
  `trip_id` uuid UNIQUE COMMENT 'Null when the rider cancelled before any driver accepted',
  `cancelled_by` ENUM ('rider', 'driver', 'support', 'system') NOT NULL,
  `reason` ENUM ('changed_plans', 'driver_too_far', 'rider_no_show', 'wrong_pickup', 'vehicle_issue', 'safety_concern', 'other') NOT NULL,
  `cancelled_at` timestamptz NOT NULL,
  `seconds_after_accept` integer COMMENT 'Compared against the free cancellation window of the fare rule',
  `fee_cents` integer NOT NULL DEFAULT 0,
  `driver_compensation_cents` integer NOT NULL DEFAULT 0 COMMENT 'Share of the fee paid to the driver for the wasted drive',
  `fee_waived_by` varchar(120) COMMENT 'Support agent who waived the fee, if anyone did'
);

CREATE TABLE `ratings` (
  `id` uuid PRIMARY KEY,
  `trip_id` uuid NOT NULL,
  `direction` ENUM ('rider_to_driver', 'driver_to_rider') NOT NULL,
  `stars` smallint NOT NULL COMMENT '1 to 5',
  `comment` varchar(1000),
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `fare_line_items` (
  `id` uuid PRIMARY KEY,
  `trip_id` uuid NOT NULL,
  `component` ENUM ('base', 'distance', 'time', 'surge', 'booking_fee', 'minimum_fare_top_up', 'wait_time', 'toll', 'airport_fee', 'promo', 'tip', 'tax') NOT NULL,
  `description` varchar(200) NOT NULL COMMENT 'As printed on the receipt, e.g. "12.4 km x 1.10", "Surge 1.6x"',
  `amount_cents` integer NOT NULL COMMENT 'Negative for a promo discount'
);

CREATE TABLE `payments` (
  `id` uuid PRIMARY KEY,
  `ride_request_id` uuid NOT NULL COMMENT 'Every charge traces back to a request, including a cancellation fee with no trip',
  `trip_id` uuid,
  `payment_method_id` uuid NOT NULL,
  `kind` ENUM ('authorization', 'capture', 'release', 'charge', 'refund') NOT NULL,
  `status` ENUM ('pending', 'succeeded', 'failed') NOT NULL DEFAULT 'pending',
  `amount_cents` integer NOT NULL,
  `currency` char(3) NOT NULL,
  `parent_payment_id` uuid COMMENT 'A capture points at its authorization, a refund at its capture',
  `idempotency_key` varchar(100) UNIQUE NOT NULL COMMENT 'A retry after a timeout can never charge twice',
  `processor_reference` varchar(100) UNIQUE,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `driver_earnings` (
  `id` uuid PRIMARY KEY,
  `driver_id` uuid NOT NULL,
  `trip_id` uuid COMMENT 'Null for earnings not tied to one trip, e.g. a weekly bonus',
  `trip_cancellation_id` uuid,
  `driver_payout_id` uuid COMMENT 'Null until swept into a payout',
  `kind` ENUM ('fare_share', 'surge_share', 'tip', 'cancellation_compensation', 'bonus', 'adjustment') NOT NULL,
  `amount_cents` integer NOT NULL COMMENT 'Negative for an adjustment or clawback',
  `currency` char(3) NOT NULL,
  `earned_at` timestamptz NOT NULL
);

CREATE TABLE `driver_payouts` (
  `id` uuid PRIMARY KEY,
  `driver_id` uuid NOT NULL,
  `kind` ENUM ('weekly', 'instant') NOT NULL,
  `period_start` date NOT NULL,
  `period_end` date NOT NULL,
  `amount_cents` bigint NOT NULL COMMENT 'Sum of the earnings rows it sweeps',
  `fee_cents` integer NOT NULL DEFAULT 0 COMMENT 'Charged for an instant cash-out',
  `currency` char(3) NOT NULL,
  `status` ENUM ('pending', 'paid', 'failed') NOT NULL DEFAULT 'pending',
  `processor_reference` varchar(100) UNIQUE,
  `initiated_at` timestamptz NOT NULL,
  `paid_at` timestamptz
);

CREATE TABLE `drivers` (
  `id` uuid PRIMARY KEY,
  `phone` varchar(20) UNIQUE NOT NULL,
  `email` varchar(254) UNIQUE NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `service_area_id` uuid NOT NULL COMMENT 'The market the driver is licensed to work in',
  `status` ENUM ('applicant', 'active', 'suspended', 'deactivated') NOT NULL DEFAULT 'applicant',
  `rating_avg` numeric(3,2) COMMENT 'Cache of ratings received',
  `acceptance_rate` numeric(5,4) COMMENT 'Cache computed from dispatch_offers over a trailing window',
  `payout_account_token` varchar(200) COMMENT 'Bank account held by the payment processor',
  `approved_at` timestamptz,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `driver_documents` (
  `id` uuid PRIMARY KEY,
  `driver_id` uuid NOT NULL,
  `vehicle_id` uuid COMMENT 'Set for vehicle documents: registration, insurance, inspection',
  `kind` ENUM ('drivers_license', 'background_check', 'vehicle_registration', 'vehicle_insurance', 'vehicle_inspection', 'profile_photo') NOT NULL,
  `storage_key` varchar(300) NOT NULL COMMENT 'Object storage key. The scan never lives in the database.',
  `document_number` varchar(60),
  `expires_on` date COMMENT 'A nightly job suspends drivers whose required documents lapse',
  `status` ENUM ('pending', 'approved', 'rejected', 'expired') NOT NULL DEFAULT 'pending',
  `reviewed_by` varchar(120) COMMENT 'Ops reviewer, or the background check vendor',
  `reviewed_at` timestamptz,
  `rejection_reason` varchar(300),
  `submitted_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `vehicles` (
  `id` uuid PRIMARY KEY,
  `driver_id` uuid NOT NULL,
  `vin` char(17) UNIQUE NOT NULL,
  `plate` varchar(15) NOT NULL,
  `plate_region` varchar(60) NOT NULL,
  `make` varchar(60) NOT NULL,
  `model` varchar(60) NOT NULL,
  `model_year` smallint NOT NULL,
  `color` varchar(30) NOT NULL COMMENT 'Shown to the rider beside the plate so they find the right car',
  `seats` smallint NOT NULL,
  `wheelchair_accessible` boolean NOT NULL DEFAULT false,
  `status` ENUM ('pending', 'active', 'inactive', 'rejected') NOT NULL DEFAULT 'pending'
);

CREATE TABLE `vehicle_product_tiers` (
  `vehicle_id` uuid NOT NULL,
  `product_tier_id` uuid NOT NULL,
  `approved_at` timestamptz NOT NULL,
  PRIMARY KEY (`vehicle_id`, `product_tier_id`)
);

CREATE TABLE `driver_sessions` (
  `id` uuid PRIMARY KEY,
  `driver_id` uuid NOT NULL,
  `vehicle_id` uuid NOT NULL,
  `service_area_id` uuid NOT NULL,
  `started_at` timestamptz NOT NULL,
  `ended_at` timestamptz COMMENT 'Null while online',
  `end_reason` ENUM ('went_offline', 'app_timeout', 'hours_limit_reached', 'suspended')
);

CREATE TABLE `driver_locations` (
  `driver_id` uuid PRIMARY KEY,
  `driver_session_id` uuid NOT NULL,
  `location` geography(Point,4326) NOT NULL,
  `heading_deg` smallint,
  `speed_kph` smallint,
  `availability` ENUM ('available', 'en_route_to_pickup', 'on_trip') NOT NULL,
  `zone_id` uuid NOT NULL COMMENT 'Derived from location, so supply per zone is a simple count',
  `updated_at` timestamptz NOT NULL
);

CREATE TABLE `driver_location_pings` (
  `driver_id` uuid NOT NULL,
  `recorded_at` timestamptz NOT NULL COMMENT 'Device time of the GPS fix',
  `trip_id` uuid COMMENT 'Set while on a trip, so the route can be rebuilt for a fare dispute',
  `lat` numeric(9,6) NOT NULL,
  `lng` numeric(9,6) NOT NULL,
  `accuracy_m` smallint,
  `speed_kph` smallint,
  PRIMARY KEY (`driver_id`, `recorded_at`)
);

CREATE UNIQUE INDEX `fare_rules_index_0` ON `fare_rules` (`service_area_id`, `product_tier_id`, `valid_from`);

CREATE UNIQUE INDEX `surge_multipliers_index_1` ON `surge_multipliers` (`zone_id`, `product_tier_id`, `window_start`);

CREATE INDEX `promo_redemptions_index_2` ON `promo_redemptions` (`promo_code_id`, `rider_id`);

CREATE INDEX `ride_requests_index_3` ON `ride_requests` (`pickup_zone_id`, `requested_at`);

CREATE INDEX `ride_requests_index_4` ON `ride_requests` (`rider_id`, `requested_at`);

CREATE UNIQUE INDEX `dispatch_offers_index_5` ON `dispatch_offers` (`ride_request_id`, `attempt`);

CREATE INDEX `dispatch_offers_index_6` ON `dispatch_offers` (`driver_id`, `offered_at`);

CREATE INDEX `one_accepted_offer` ON `dispatch_offers` (`ride_request_id`);

CREATE INDEX `trips_index_8` ON `trips` (`driver_id`, `accepted_at`);

CREATE INDEX `trips_index_9` ON `trips` (`rider_id`, `accepted_at`);

CREATE UNIQUE INDEX `ratings_index_10` ON `ratings` (`trip_id`, `direction`);

CREATE INDEX `driver_earnings_index_11` ON `driver_earnings` (`driver_id`, `earned_at`);

CREATE INDEX `driver_earnings_index_12` ON `driver_earnings` (`driver_payout_id`);

CREATE INDEX `driver_documents_index_13` ON `driver_documents` (`driver_id`, `kind`, `status`);

CREATE INDEX `driver_sessions_index_14` ON `driver_sessions` (`driver_id`, `started_at`);

CREATE INDEX `one_open_session` ON `driver_sessions` (`driver_id`);

CREATE INDEX `driver_locations_index_16` ON `driver_locations` (`location`) USING GIST;

CREATE INDEX `driver_locations_index_17` ON `driver_locations` (`zone_id`, `availability`);

ALTER TABLE `service_areas` COMMENT = 'A market the service operates in. Currency, timezone, fare rules and driver licensing are all per market.';

ALTER TABLE `zones` COMMENT = 'Small cells inside a market. Supply, demand and surge are measured per zone, never per city.';

ALTER TABLE `product_tiers` COMMENT = 'What a rider picks on the selection screen. A vehicle QUALIFIES for tiers (vehicle_product_tiers); it is not one tier.';

ALTER TABLE `fare_rules` COMMENT = 'Rate card per market and tier, versioned by validity window and never edited in place. Estimates and trips point at the exact version they used.';

ALTER TABLE `surge_multipliers` COMMENT = 'Surge per zone, per tier, per short time window (a few minutes), stored with the supply and demand that produced it. Kept as history so any quoted price can be explained in a dispute.';

ALTER TABLE `promo_codes` COMMENT = 'Discount codes. Platform funded: a promo lowers what the rider pays and never what the driver earns.';

ALTER TABLE `riders` COMMENT = 'People who request rides.';

ALTER TABLE `saved_places` COMMENT = 'Shortcuts a rider picks from when setting a pickup or destination.';

ALTER TABLE `payment_methods` COMMENT = 'Saved cards, wallets, business accounts and the cash option, stored as processor tokens.';

ALTER TABLE `promo_redemptions` COMMENT = 'A rider claiming a code, and the trip it was eventually spent on.';

ALTER TABLE `fare_estimates` COMMENT = 'Every price shown to a rider, one row per tier on the selection screen. Most are never booked; the one the rider accepts is referenced by the request.';

ALTER TABLE `ride_requests` COMMENT = 'The rider asking for a ride. It exists before any driver is involved and often never becomes a trip (no drivers nearby, cancelled while searching). Those unfulfilled requests are exactly the demand signal surge pricing needs.';

ALTER TABLE `dispatch_offers` COMMENT = 'Every offer made to a driver and how it ended: accepted, declined, expired or withdrawn. A request that cascades through three drivers leaves three rows.';

ALTER TABLE `trips` COMMENT = 'A matched ride. status runs driver_en_route, arrived, in_progress, then completed or cancelled, and every state has its own timestamp column, so pickup wait, ETA accuracy and ride time are plain subtractions.';

ALTER TABLE `trip_cancellations` COMMENT = 'Who cancelled, why, and what it cost. A late rider cancel or a no-show carries a fee, and part of it compensates the driver.';

ALTER TABLE `ratings` COMMENT = 'Two-way ratings: the rider rates the driver and the driver rates the rider. The averages cached on riders and drivers are recomputed from these rows.';

ALTER TABLE `fare_line_items` COMMENT = 'The itemized receipt: base, distance, time, surge, booking fee, wait time, tolls, airport fee, promo, tip, tax. The rider total is their sum.';

ALTER TABLE `payments` COMMENT = 'Rider card activity as rows: an authorization when the request is placed, the capture at drop-off, a separate charge for a tip added later, refunds after a support review.';

ALTER TABLE `driver_earnings` COMMENT = 'The driver side ledger: fare share, surge share, tips passed through in full, cancellation compensation, bonuses and adjustments. The platform take is what the rider paid minus these rows, never a stored column.';

ALTER TABLE `driver_payouts` COMMENT = 'Transfers to the driver bank account: weekly by default, or an instant cash-out for a fee.';

ALTER TABLE `drivers` COMMENT = 'People who drive. status moves from applicant to active only once every required document is approved.';

ALTER TABLE `driver_documents` COMMENT = 'License, background check, registration, insurance and inspection, each reviewed on its own. A renewal is a new row; the old one stays as the audit trail.';

ALTER TABLE `vehicles` COMMENT = 'Cars registered to a driver. A driver may have several, but drives one per session.';

ALTER TABLE `vehicle_product_tiers` COMMENT = 'Which tiers a vehicle qualifies for. A large new car can serve economy, comfort and xl at once.';

ALTER TABLE `driver_sessions` COMMENT = 'Each stretch a driver is online. Hours-online limits, utilization and fatigue rules are computed from these rows.';

ALTER TABLE `driver_locations` COMMENT = 'The LATEST position of each online driver: one row per driver, overwritten every few seconds and deleted when the session ends. Dispatch reads only this small table, never the stream.';

ALTER TABLE `driver_location_pings` COMMENT = 'Append-only GPS stream from every online driver, every few seconds: by far the highest-volume table in the system.
Partition it by recorded_at (daily), keep raw pings for a fixed retention period, and drop whole partitions instead of deleting rows.
Plain lat and lng columns keep inserts cheap; nothing on the dispatch path ever reads it.';

ALTER TABLE `zones` ADD FOREIGN KEY (`service_area_id`) REFERENCES `service_areas` (`id`);

ALTER TABLE `fare_rules` ADD FOREIGN KEY (`service_area_id`) REFERENCES `service_areas` (`id`);

ALTER TABLE `fare_rules` ADD FOREIGN KEY (`product_tier_id`) REFERENCES `product_tiers` (`id`);

ALTER TABLE `surge_multipliers` ADD FOREIGN KEY (`zone_id`) REFERENCES `zones` (`id`);

ALTER TABLE `surge_multipliers` ADD FOREIGN KEY (`product_tier_id`) REFERENCES `product_tiers` (`id`);

ALTER TABLE `promo_codes` ADD FOREIGN KEY (`service_area_id`) REFERENCES `service_areas` (`id`);

ALTER TABLE `riders` ADD FOREIGN KEY (`home_service_area_id`) REFERENCES `service_areas` (`id`);

ALTER TABLE `saved_places` ADD FOREIGN KEY (`rider_id`) REFERENCES `riders` (`id`);

ALTER TABLE `payment_methods` ADD FOREIGN KEY (`rider_id`) REFERENCES `riders` (`id`);

ALTER TABLE `promo_redemptions` ADD FOREIGN KEY (`promo_code_id`) REFERENCES `promo_codes` (`id`);

ALTER TABLE `promo_redemptions` ADD FOREIGN KEY (`rider_id`) REFERENCES `riders` (`id`);

ALTER TABLE `promo_redemptions` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);

ALTER TABLE `fare_estimates` ADD FOREIGN KEY (`rider_id`) REFERENCES `riders` (`id`);

ALTER TABLE `fare_estimates` ADD FOREIGN KEY (`product_tier_id`) REFERENCES `product_tiers` (`id`);

ALTER TABLE `fare_estimates` ADD FOREIGN KEY (`fare_rule_id`) REFERENCES `fare_rules` (`id`);

ALTER TABLE `fare_estimates` ADD FOREIGN KEY (`surge_multiplier_id`) REFERENCES `surge_multipliers` (`id`);

ALTER TABLE `ride_requests` ADD FOREIGN KEY (`rider_id`) REFERENCES `riders` (`id`);

ALTER TABLE `ride_requests` ADD FOREIGN KEY (`product_tier_id`) REFERENCES `product_tiers` (`id`);

ALTER TABLE `ride_requests` ADD FOREIGN KEY (`fare_estimate_id`) REFERENCES `fare_estimates` (`id`);

ALTER TABLE `ride_requests` ADD FOREIGN KEY (`payment_method_id`) REFERENCES `payment_methods` (`id`);

ALTER TABLE `ride_requests` ADD FOREIGN KEY (`promo_redemption_id`) REFERENCES `promo_redemptions` (`id`);

ALTER TABLE `ride_requests` ADD FOREIGN KEY (`pickup_zone_id`) REFERENCES `zones` (`id`);

ALTER TABLE `dispatch_offers` ADD FOREIGN KEY (`ride_request_id`) REFERENCES `ride_requests` (`id`);

ALTER TABLE `dispatch_offers` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`ride_request_id`) REFERENCES `ride_requests` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`dispatch_offer_id`) REFERENCES `dispatch_offers` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`rider_id`) REFERENCES `riders` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`vehicle_id`) REFERENCES `vehicles` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`product_tier_id`) REFERENCES `product_tiers` (`id`);

ALTER TABLE `trips` ADD FOREIGN KEY (`fare_rule_id`) REFERENCES `fare_rules` (`id`);

ALTER TABLE `trip_cancellations` ADD FOREIGN KEY (`ride_request_id`) REFERENCES `ride_requests` (`id`);

ALTER TABLE `trip_cancellations` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);

ALTER TABLE `ratings` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);

ALTER TABLE `fare_line_items` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`ride_request_id`) REFERENCES `ride_requests` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`payment_method_id`) REFERENCES `payment_methods` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`parent_payment_id`) REFERENCES `payments` (`id`);

ALTER TABLE `driver_earnings` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `driver_earnings` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);

ALTER TABLE `driver_earnings` ADD FOREIGN KEY (`trip_cancellation_id`) REFERENCES `trip_cancellations` (`id`);

ALTER TABLE `driver_earnings` ADD FOREIGN KEY (`driver_payout_id`) REFERENCES `driver_payouts` (`id`);

ALTER TABLE `driver_payouts` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `drivers` ADD FOREIGN KEY (`service_area_id`) REFERENCES `service_areas` (`id`);

ALTER TABLE `driver_documents` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `driver_documents` ADD FOREIGN KEY (`vehicle_id`) REFERENCES `vehicles` (`id`);

ALTER TABLE `vehicles` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `vehicle_product_tiers` ADD FOREIGN KEY (`vehicle_id`) REFERENCES `vehicles` (`id`);

ALTER TABLE `vehicle_product_tiers` ADD FOREIGN KEY (`product_tier_id`) REFERENCES `product_tiers` (`id`);

ALTER TABLE `driver_sessions` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `driver_sessions` ADD FOREIGN KEY (`vehicle_id`) REFERENCES `vehicles` (`id`);

ALTER TABLE `driver_sessions` ADD FOREIGN KEY (`service_area_id`) REFERENCES `service_areas` (`id`);

ALTER TABLE `driver_locations` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `driver_locations` ADD FOREIGN KEY (`driver_session_id`) REFERENCES `driver_sessions` (`id`);

ALTER TABLE `driver_locations` ADD FOREIGN KEY (`zone_id`) REFERENCES `zones` (`id`);

ALTER TABLE `driver_location_pings` ADD FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`);

ALTER TABLE `driver_location_pings` ADD FOREIGN KEY (`trip_id`) REFERENCES `trips` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [service_areas] (
  [id] uuid PRIMARY KEY,
  [code] varchar(20) UNIQUE NOT NULL,
  [name] varchar(120) NOT NULL,
  [country] char(2) NOT NULL,
  [timezone] varchar(64) NOT NULL,
  [currency] char(3) NOT NULL,
  [boundary] geography(MultiPolygon,4326) NOT NULL,
  [is_active] boolean NOT NULL DEFAULT (true),
  [launched_on] date
)
GO

CREATE TABLE [zones] (
  [id] uuid PRIMARY KEY,
  [service_area_id] uuid NOT NULL,
  [cell_id] varchar(20) UNIQUE NOT NULL,
  [label] varchar(120),
  [is_airport] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [product_tiers] (
  [id] uuid PRIMARY KEY,
  [code] varchar(30) UNIQUE NOT NULL,
  [name] varchar(100) NOT NULL,
  [seats] smallint NOT NULL,
  [min_vehicle_year] smallint,
  [is_shared] boolean NOT NULL DEFAULT (false),
  [sort_order] smallint NOT NULL DEFAULT (0)
)
GO

CREATE TABLE [fare_rules] (
  [id] uuid PRIMARY KEY,
  [service_area_id] uuid NOT NULL,
  [product_tier_id] uuid NOT NULL,
  [base_fare_cents] integer NOT NULL,
  [per_km_cents] integer NOT NULL,
  [per_minute_cents] integer NOT NULL,
  [minimum_fare_cents] integer NOT NULL,
  [booking_fee_cents] integer NOT NULL DEFAULT (0),
  [cancellation_fee_cents] integer NOT NULL,
  [free_cancel_seconds] integer NOT NULL DEFAULT (120),
  [no_show_wait_seconds] integer NOT NULL DEFAULT (300),
  [valid_from] timestamptz NOT NULL,
  [valid_to] timestamptz
)
GO

CREATE TABLE [surge_multipliers] (
  [id] uuid PRIMARY KEY,
  [zone_id] uuid NOT NULL,
  [product_tier_id] uuid NOT NULL,
  [window_start] timestamptz NOT NULL,
  [window_end] timestamptz NOT NULL,
  [multiplier] numeric(4,2) NOT NULL,
  [open_requests] integer NOT NULL,
  [available_drivers] integer NOT NULL,
  [computed_at] timestamptz NOT NULL
)
GO

CREATE TABLE [promo_codes] (
  [id] uuid PRIMARY KEY,
  [code] varchar(30) UNIQUE NOT NULL,
  [service_area_id] uuid,
  [discount_kind] nvarchar(255) NOT NULL CHECK ([discount_kind] IN ('fixed_amount', 'percentage')),
  [discount_value] integer NOT NULL,
  [max_discount_cents] integer,
  [max_redemptions] integer,
  [per_rider_limit] smallint NOT NULL DEFAULT (1),
  [first_ride_only] boolean NOT NULL DEFAULT (false),
  [valid_from] timestamptz NOT NULL,
  [valid_to] timestamptz
)
GO

CREATE TABLE [riders] (
  [id] uuid PRIMARY KEY,
  [phone] varchar(20) UNIQUE NOT NULL,
  [email] varchar(254) UNIQUE,
  [first_name] varchar(100) NOT NULL,
  [last_name] varchar(100),
  [home_service_area_id] uuid,
  [rating_avg] numeric(3,2),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('active', 'suspended', 'banned', 'closed')) DEFAULT 'active',
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [saved_places] (
  [id] uuid PRIMARY KEY,
  [rider_id] uuid NOT NULL,
  [label] varchar(60) NOT NULL,
  [address] varchar(300) NOT NULL,
  [location] geography(Point,4326) NOT NULL
)
GO

CREATE TABLE [payment_methods] (
  [id] uuid PRIMARY KEY,
  [rider_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('card', 'wallet', 'business_account', 'cash')),
  [processor_token] varchar(200),
  [brand] varchar(20),
  [last4] char(4),
  [expires_on] date,
  [is_default] boolean NOT NULL DEFAULT (false),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [promo_redemptions] (
  [id] uuid PRIMARY KEY,
  [promo_code_id] uuid NOT NULL,
  [rider_id] uuid NOT NULL,
  [trip_id] uuid UNIQUE,
  [claimed_at] timestamptz NOT NULL DEFAULT (now()),
  [discount_cents] integer
)
GO

CREATE TABLE [fare_estimates] (
  [id] uuid PRIMARY KEY,
  [rider_id] uuid NOT NULL,
  [product_tier_id] uuid NOT NULL,
  [fare_rule_id] uuid NOT NULL,
  [surge_multiplier_id] uuid,
  [surge_multiplier] numeric(4,2) NOT NULL DEFAULT (1),
  [pickup] geography(Point,4326) NOT NULL,
  [dropoff] geography(Point,4326) NOT NULL,
  [est_distance_m] integer NOT NULL,
  [est_duration_s] integer NOT NULL,
  [low_cents] integer NOT NULL,
  [high_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [expires_at] timestamptz NOT NULL
)
GO

CREATE TABLE [ride_requests] (
  [id] uuid PRIMARY KEY,
  [rider_id] uuid NOT NULL,
  [product_tier_id] uuid NOT NULL,
  [fare_estimate_id] uuid UNIQUE NOT NULL,
  [payment_method_id] uuid NOT NULL,
  [promo_redemption_id] uuid,
  [pickup_zone_id] uuid NOT NULL,
  [pickup_location] geography(Point,4326) NOT NULL,
  [pickup_address] varchar(300) NOT NULL,
  [dropoff_location] geography(Point,4326),
  [dropoff_address] varchar(300),
  [seats_requested] smallint NOT NULL DEFAULT (1),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('searching', 'matched', 'no_drivers_found', 'cancelled')) DEFAULT 'searching',
  [requested_at] timestamptz NOT NULL DEFAULT (now()),
  [resolved_at] timestamptz
)
GO

CREATE TABLE [dispatch_offers] (
  [id] uuid PRIMARY KEY,
  [ride_request_id] uuid NOT NULL,
  [driver_id] uuid NOT NULL,
  [attempt] smallint NOT NULL,
  [pickup_eta_s] integer NOT NULL,
  [pickup_distance_m] integer NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('offered', 'accepted', 'declined', 'expired', 'withdrawn')) DEFAULT 'offered',
  [offered_at] timestamptz NOT NULL,
  [expires_at] timestamptz NOT NULL,
  [responded_at] timestamptz,
  [decline_reason] varchar(100)
)
GO

CREATE TABLE [trips] (
  [id] uuid PRIMARY KEY,
  [ride_request_id] uuid UNIQUE NOT NULL,
  [dispatch_offer_id] uuid UNIQUE NOT NULL,
  [rider_id] uuid NOT NULL,
  [driver_id] uuid NOT NULL,
  [vehicle_id] uuid NOT NULL,
  [product_tier_id] uuid NOT NULL,
  [fare_rule_id] uuid NOT NULL,
  [surge_multiplier] numeric(4,2) NOT NULL DEFAULT (1),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('driver_en_route', 'arrived', 'in_progress', 'completed', 'cancelled')) DEFAULT 'driver_en_route',
  [accepted_at] timestamptz NOT NULL,
  [arrived_at] timestamptz,
  [started_at] timestamptz,
  [completed_at] timestamptz,
  [cancelled_at] timestamptz,
  [actual_pickup] geography(Point,4326),
  [actual_dropoff] geography(Point,4326),
  [distance_m] integer,
  [duration_s] integer,
  [fare_total_cents] integer,
  [currency] char(3) NOT NULL
)
GO

CREATE TABLE [trip_cancellations] (
  [id] uuid PRIMARY KEY,
  [ride_request_id] uuid UNIQUE NOT NULL,
  [trip_id] uuid UNIQUE,
  [cancelled_by] nvarchar(255) NOT NULL CHECK ([cancelled_by] IN ('rider', 'driver', 'support', 'system')),
  [reason] nvarchar(255) NOT NULL CHECK ([reason] IN ('changed_plans', 'driver_too_far', 'rider_no_show', 'wrong_pickup', 'vehicle_issue', 'safety_concern', 'other')),
  [cancelled_at] timestamptz NOT NULL,
  [seconds_after_accept] integer,
  [fee_cents] integer NOT NULL DEFAULT (0),
  [driver_compensation_cents] integer NOT NULL DEFAULT (0),
  [fee_waived_by] varchar(120)
)
GO

CREATE TABLE [ratings] (
  [id] uuid PRIMARY KEY,
  [trip_id] uuid NOT NULL,
  [direction] nvarchar(255) NOT NULL CHECK ([direction] IN ('rider_to_driver', 'driver_to_rider')),
  [stars] smallint NOT NULL,
  [comment] varchar(1000),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [fare_line_items] (
  [id] uuid PRIMARY KEY,
  [trip_id] uuid NOT NULL,
  [component] nvarchar(255) NOT NULL CHECK ([component] IN ('base', 'distance', 'time', 'surge', 'booking_fee', 'minimum_fare_top_up', 'wait_time', 'toll', 'airport_fee', 'promo', 'tip', 'tax')),
  [description] varchar(200) NOT NULL,
  [amount_cents] integer NOT NULL
)
GO

CREATE TABLE [payments] (
  [id] uuid PRIMARY KEY,
  [ride_request_id] uuid NOT NULL,
  [trip_id] uuid,
  [payment_method_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('authorization', 'capture', 'release', 'charge', 'refund')),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'succeeded', 'failed')) DEFAULT 'pending',
  [amount_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [parent_payment_id] uuid,
  [idempotency_key] varchar(100) UNIQUE NOT NULL,
  [processor_reference] varchar(100) UNIQUE,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [driver_earnings] (
  [id] uuid PRIMARY KEY,
  [driver_id] uuid NOT NULL,
  [trip_id] uuid,
  [trip_cancellation_id] uuid,
  [driver_payout_id] uuid,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('fare_share', 'surge_share', 'tip', 'cancellation_compensation', 'bonus', 'adjustment')),
  [amount_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [earned_at] timestamptz NOT NULL
)
GO

CREATE TABLE [driver_payouts] (
  [id] uuid PRIMARY KEY,
  [driver_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('weekly', 'instant')),
  [period_start] date NOT NULL,
  [period_end] date NOT NULL,
  [amount_cents] bigint NOT NULL,
  [fee_cents] integer NOT NULL DEFAULT (0),
  [currency] char(3) NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'paid', 'failed')) DEFAULT 'pending',
  [processor_reference] varchar(100) UNIQUE,
  [initiated_at] timestamptz NOT NULL,
  [paid_at] timestamptz
)
GO

CREATE TABLE [drivers] (
  [id] uuid PRIMARY KEY,
  [phone] varchar(20) UNIQUE NOT NULL,
  [email] varchar(254) UNIQUE NOT NULL,
  [first_name] varchar(100) NOT NULL,
  [last_name] varchar(100) NOT NULL,
  [service_area_id] uuid NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('applicant', 'active', 'suspended', 'deactivated')) DEFAULT 'applicant',
  [rating_avg] numeric(3,2),
  [acceptance_rate] numeric(5,4),
  [payout_account_token] varchar(200),
  [approved_at] timestamptz,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [driver_documents] (
  [id] uuid PRIMARY KEY,
  [driver_id] uuid NOT NULL,
  [vehicle_id] uuid,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('drivers_license', 'background_check', 'vehicle_registration', 'vehicle_insurance', 'vehicle_inspection', 'profile_photo')),
  [storage_key] varchar(300) NOT NULL,
  [document_number] varchar(60),
  [expires_on] date,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'approved', 'rejected', 'expired')) DEFAULT 'pending',
  [reviewed_by] varchar(120),
  [reviewed_at] timestamptz,
  [rejection_reason] varchar(300),
  [submitted_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [vehicles] (
  [id] uuid PRIMARY KEY,
  [driver_id] uuid NOT NULL,
  [vin] char(17) UNIQUE NOT NULL,
  [plate] varchar(15) NOT NULL,
  [plate_region] varchar(60) NOT NULL,
  [make] varchar(60) NOT NULL,
  [model] varchar(60) NOT NULL,
  [model_year] smallint NOT NULL,
  [color] varchar(30) NOT NULL,
  [seats] smallint NOT NULL,
  [wheelchair_accessible] boolean NOT NULL DEFAULT (false),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'active', 'inactive', 'rejected')) DEFAULT 'pending'
)
GO

CREATE TABLE [vehicle_product_tiers] (
  [vehicle_id] uuid NOT NULL,
  [product_tier_id] uuid NOT NULL,
  [approved_at] timestamptz NOT NULL,
  PRIMARY KEY ([vehicle_id], [product_tier_id])
)
GO

CREATE TABLE [driver_sessions] (
  [id] uuid PRIMARY KEY,
  [driver_id] uuid NOT NULL,
  [vehicle_id] uuid NOT NULL,
  [service_area_id] uuid NOT NULL,
  [started_at] timestamptz NOT NULL,
  [ended_at] timestamptz,
  [end_reason] nvarchar(255) CHECK ([end_reason] IN ('went_offline', 'app_timeout', 'hours_limit_reached', 'suspended'))
)
GO

CREATE TABLE [driver_locations] (
  [driver_id] uuid PRIMARY KEY,
  [driver_session_id] uuid NOT NULL,
  [location] geography(Point,4326) NOT NULL,
  [heading_deg] smallint,
  [speed_kph] smallint,
  [availability] nvarchar(255) NOT NULL CHECK ([availability] IN ('available', 'en_route_to_pickup', 'on_trip')),
  [zone_id] uuid NOT NULL,
  [updated_at] timestamptz NOT NULL
)
GO

CREATE TABLE [driver_location_pings] (
  [driver_id] uuid NOT NULL,
  [recorded_at] timestamptz NOT NULL,
  [trip_id] uuid,
  [lat] numeric(9,6) NOT NULL,
  [lng] numeric(9,6) NOT NULL,
  [accuracy_m] smallint,
  [speed_kph] smallint,
  PRIMARY KEY ([driver_id], [recorded_at])
)
GO

CREATE UNIQUE INDEX [fare_rules_index_0] ON [fare_rules] ("service_area_id", "product_tier_id", "valid_from")
GO

CREATE UNIQUE INDEX [surge_multipliers_index_1] ON [surge_multipliers] ("zone_id", "product_tier_id", "window_start")
GO

CREATE INDEX [promo_redemptions_index_2] ON [promo_redemptions] ("promo_code_id", "rider_id")
GO

CREATE INDEX [ride_requests_index_3] ON [ride_requests] ("pickup_zone_id", "requested_at")
GO

CREATE INDEX [ride_requests_index_4] ON [ride_requests] ("rider_id", "requested_at")
GO

CREATE UNIQUE INDEX [dispatch_offers_index_5] ON [dispatch_offers] ("ride_request_id", "attempt")
GO

CREATE INDEX [dispatch_offers_index_6] ON [dispatch_offers] ("driver_id", "offered_at")
GO

CREATE INDEX [one_accepted_offer] ON [dispatch_offers] ("ride_request_id")
GO

CREATE INDEX [trips_index_8] ON [trips] ("driver_id", "accepted_at")
GO

CREATE INDEX [trips_index_9] ON [trips] ("rider_id", "accepted_at")
GO

CREATE UNIQUE INDEX [ratings_index_10] ON [ratings] ("trip_id", "direction")
GO

CREATE INDEX [driver_earnings_index_11] ON [driver_earnings] ("driver_id", "earned_at")
GO

CREATE INDEX [driver_earnings_index_12] ON [driver_earnings] ("driver_payout_id")
GO

CREATE INDEX [driver_documents_index_13] ON [driver_documents] ("driver_id", "kind", "status")
GO

CREATE INDEX [driver_sessions_index_14] ON [driver_sessions] ("driver_id", "started_at")
GO

CREATE INDEX [one_open_session] ON [driver_sessions] ("driver_id")
GO

CREATE INDEX [driver_locations_index_16] ON [driver_locations] ("location")
GO

CREATE INDEX [driver_locations_index_17] ON [driver_locations] ("zone_id", "availability")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A market the service operates in. Currency, timezone, fare rules and driver licensing are all per market.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'service_areas';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Short market code, e.g. "chi", "lon"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'service_areas',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'IANA zone. Surge windows, payout weeks and receipts use it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'service_areas',
@level2type = N'Column', @level2name = 'timezone';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Requests with a pickup outside every boundary are refused',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'service_areas',
@level2type = N'Column', @level2name = 'boundary';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Small cells inside a market. Supply, demand and surge are measured per zone, never per city.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'zones';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Hexagonal grid cell id (e.g. H3 at resolution 8). A fixed grid keeps surge history comparable over time.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'zones',
@level2type = N'Column', @level2name = 'cell_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Optional human name, e.g. "Airport", "Stadium"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'zones',
@level2type = N'Column', @level2name = 'label';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Airport zones usually run a first-in, first-out driver queue instead of nearest-driver dispatch',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'zones',
@level2type = N'Column', @level2name = 'is_airport';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What a rider picks on the selection screen. A vehicle QUALIFIES for tiers (vehicle_product_tiers); it is not one tier.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'product_tiers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. economy, comfort, xl, premium, accessible',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'product_tiers',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Oldest model year eligible for the tier',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'product_tiers',
@level2type = N'Column', @level2name = 'min_vehicle_year';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Pooled rides that can carry more than one request at once',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'product_tiers',
@level2type = N'Column', @level2name = 'is_shared';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Rate card per market and tier, versioned by validity window and never edited in place. Estimates and trips point at the exact version they used.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_rules';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Flat platform fee, not subject to surge',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_rules',
@level2type = N'Column', @level2name = 'booking_fee_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Rider may cancel free of charge for this long after a driver accepts',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_rules',
@level2type = N'Column', @level2name = 'free_cancel_seconds';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'How long a driver waits at pickup before a no-show fee applies',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_rules',
@level2type = N'Column', @level2name = 'no_show_wait_seconds';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for the rate card in force now',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_rules',
@level2type = N'Column', @level2name = 'valid_to';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Surge per zone, per tier, per short time window (a few minutes), stored with the supply and demand that produced it. Kept as history so any quoted price can be explained in a dispute.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'surge_multipliers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '1.00 means no surge',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'surge_multipliers',
@level2type = N'Column', @level2name = 'multiplier';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Demand seen when the multiplier was computed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'surge_multipliers',
@level2type = N'Column', @level2name = 'open_requests';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Supply seen when the multiplier was computed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'surge_multipliers',
@level2type = N'Column', @level2name = 'available_drivers';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Discount codes. Platform funded: a promo lowers what the rider pays and never what the driver earns.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_codes';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for a code valid in every market',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_codes',
@level2type = N'Column', @level2name = 'service_area_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cents for a fixed amount, basis points for a percentage',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_codes',
@level2type = N'Column', @level2name = 'discount_value';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cap on a percentage discount',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_codes',
@level2type = N'Column', @level2name = 'max_discount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Across all riders; null for unlimited',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_codes',
@level2type = N'Column', @level2name = 'max_redemptions';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People who request rides.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'riders';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'E.164. The login, and the number calls to the driver are masked through.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'riders',
@level2type = N'Column', @level2name = 'phone';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cache of ratings received; recomputed, never edited',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'riders',
@level2type = N'Column', @level2name = 'rating_avg';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Shortcuts a rider picks from when setting a pickup or destination.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_places';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Home, Work, Gym',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_places',
@level2type = N'Column', @level2name = 'label';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Saved cards, wallets, business accounts and the cash option, stored as processor tokens.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payment_methods';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Card and wallet data stays with the payment processor. Null for cash.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payment_methods',
@level2type = N'Column', @level2name = 'processor_token';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A rider claiming a code, and the trip it was eventually spent on.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_redemptions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when the discount is spent on a completed trip',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_redemptions',
@level2type = N'Column', @level2name = 'trip_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'What it was actually worth, known once the fare is final',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promo_redemptions',
@level2type = N'Column', @level2name = 'discount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Every price shown to a rider, one row per tier on the selection screen. Most are never booked; the one the rider accepts is referenced by the request.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_estimates';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null when no surge was in effect',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_estimates',
@level2type = N'Column', @level2name = 'surge_multiplier_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied, so the quote stands even if the surge row is recomputed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_estimates',
@level2type = N'Column', @level2name = 'surge_multiplier';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Equal to low_cents for an upfront fixed price',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_estimates',
@level2type = N'Column', @level2name = 'high_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The quote is honoured only until here, typically a few minutes',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_estimates',
@level2type = N'Column', @level2name = 'expires_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The rider asking for a ride. It exists before any driver is involved and often never becomes a trip (no drivers nearby, cancelled while searching). Those unfulfilled requests are exactly the demand signal surge pricing needs.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ride_requests';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The quote the rider accepted',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ride_requests',
@level2type = N'Column', @level2name = 'fare_estimate_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'When it was matched, cancelled or gave up',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ride_requests',
@level2type = N'Column', @level2name = 'resolved_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Every offer made to a driver and how it ended: accepted, declined, expired or withdrawn. A request that cascades through three drivers leaves three rows.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dispatch_offers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '1 for the first driver offered the job, 2 for the next, and so on',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dispatch_offers',
@level2type = N'Column', @level2name = 'attempt';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Driving time to pickup at the moment of the offer',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dispatch_offers',
@level2type = N'Column', @level2name = 'pickup_eta_s';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Usually about 15 seconds after offered_at',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dispatch_offers',
@level2type = N'Column', @level2name = 'expires_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A matched ride. status runs driver_en_route, arrived, in_progress, then completed or cancelled, and every state has its own timestamp column, so pickup wait, ETA accuracy and ride time are plain subtractions.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The accepted offer that created this trip',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'dispatch_offer_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied from the request for the trip history query',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'rider_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Rate card version the final fare is computed under',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'fare_rule_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Locked from the estimate, never re-read at drop-off',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'surge_multiplier';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Driver at pickup; the no-show wait starts here',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'arrived_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Rider on board, meter running',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'started_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Measured from the location stream, not taken from the estimate',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'distance_m';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sum of fare_line_items, cached once the fare is final',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trips',
@level2type = N'Column', @level2name = 'fare_total_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who cancelled, why, and what it cost. A late rider cancel or a no-show carries a fee, and part of it compensates the driver.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trip_cancellations';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null when the rider cancelled before any driver accepted',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trip_cancellations',
@level2type = N'Column', @level2name = 'trip_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Compared against the free cancellation window of the fare rule',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trip_cancellations',
@level2type = N'Column', @level2name = 'seconds_after_accept';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Share of the fee paid to the driver for the wasted drive',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trip_cancellations',
@level2type = N'Column', @level2name = 'driver_compensation_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Support agent who waived the fee, if anyone did',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'trip_cancellations',
@level2type = N'Column', @level2name = 'fee_waived_by';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Two-way ratings: the rider rates the driver and the driver rates the rider. The averages cached on riders and drivers are recomputed from these rows.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ratings';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '1 to 5',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ratings',
@level2type = N'Column', @level2name = 'stars';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The itemized receipt: base, distance, time, surge, booking fee, wait time, tolls, airport fee, promo, tip, tax. The rider total is their sum.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_line_items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'As printed on the receipt, e.g. "12.4 km x 1.10", "Surge 1.6x"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_line_items',
@level2type = N'Column', @level2name = 'description';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Negative for a promo discount',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fare_line_items',
@level2type = N'Column', @level2name = 'amount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Rider card activity as rows: an authorization when the request is placed, the capture at drop-off, a separate charge for a tip added later, refunds after a support review.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Every charge traces back to a request, including a cancellation fee with no trip',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'ride_request_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A capture points at its authorization, a refund at its capture',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'parent_payment_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A retry after a timeout can never charge twice',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'idempotency_key';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The driver side ledger: fare share, surge share, tips passed through in full, cancellation compensation, bonuses and adjustments. The platform take is what the rider paid minus these rows, never a stored column.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_earnings';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for earnings not tied to one trip, e.g. a weekly bonus',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_earnings',
@level2type = N'Column', @level2name = 'trip_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null until swept into a payout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_earnings',
@level2type = N'Column', @level2name = 'driver_payout_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Negative for an adjustment or clawback',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_earnings',
@level2type = N'Column', @level2name = 'amount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Transfers to the driver bank account: weekly by default, or an instant cash-out for a fee.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_payouts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sum of the earnings rows it sweeps',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_payouts',
@level2type = N'Column', @level2name = 'amount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Charged for an instant cash-out',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_payouts',
@level2type = N'Column', @level2name = 'fee_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People who drive. status moves from applicant to active only once every required document is approved.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'drivers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The market the driver is licensed to work in',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'drivers',
@level2type = N'Column', @level2name = 'service_area_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cache of ratings received',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'drivers',
@level2type = N'Column', @level2name = 'rating_avg';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cache computed from dispatch_offers over a trailing window',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'drivers',
@level2type = N'Column', @level2name = 'acceptance_rate';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Bank account held by the payment processor',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'drivers',
@level2type = N'Column', @level2name = 'payout_account_token';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'License, background check, registration, insurance and inspection, each reviewed on its own. A renewal is a new row; the old one stays as the audit trail.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_documents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set for vehicle documents: registration, insurance, inspection',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_documents',
@level2type = N'Column', @level2name = 'vehicle_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Object storage key. The scan never lives in the database.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_documents',
@level2type = N'Column', @level2name = 'storage_key';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A nightly job suspends drivers whose required documents lapse',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_documents',
@level2type = N'Column', @level2name = 'expires_on';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Ops reviewer, or the background check vendor',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_documents',
@level2type = N'Column', @level2name = 'reviewed_by';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Cars registered to a driver. A driver may have several, but drives one per session.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'vehicles';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Shown to the rider beside the plate so they find the right car',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'vehicles',
@level2type = N'Column', @level2name = 'color';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Which tiers a vehicle qualifies for. A large new car can serve economy, comfort and xl at once.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'vehicle_product_tiers';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Each stretch a driver is online. Hours-online limits, utilization and fatigue rules are computed from these rows.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_sessions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null while online',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_sessions',
@level2type = N'Column', @level2name = 'ended_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The LATEST position of each online driver: one row per driver, overwritten every few seconds and deleted when the session ends. Dispatch reads only this small table, never the stream.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_locations';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Derived from location, so supply per zone is a simple count',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_locations',
@level2type = N'Column', @level2name = 'zone_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Append-only GPS stream from every online driver, every few seconds: by far the highest-volume table in the system.
Partition it by recorded_at (daily), keep raw pings for a fixed retention period, and drop whole partitions instead of deleting rows.
Plain lat and lng columns keep inserts cheap; nothing on the dispatch path ever reads it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_location_pings';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Device time of the GPS fix',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_location_pings',
@level2type = N'Column', @level2name = 'recorded_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set while on a trip, so the route can be rebuilt for a fare dispute',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'driver_location_pings',
@level2type = N'Column', @level2name = 'trip_id';
GO

ALTER TABLE [zones] ADD FOREIGN KEY ([service_area_id]) REFERENCES [service_areas] ([id])
GO

ALTER TABLE [fare_rules] ADD FOREIGN KEY ([service_area_id]) REFERENCES [service_areas] ([id])
GO

ALTER TABLE [fare_rules] ADD FOREIGN KEY ([product_tier_id]) REFERENCES [product_tiers] ([id])
GO

ALTER TABLE [surge_multipliers] ADD FOREIGN KEY ([zone_id]) REFERENCES [zones] ([id])
GO

ALTER TABLE [surge_multipliers] ADD FOREIGN KEY ([product_tier_id]) REFERENCES [product_tiers] ([id])
GO

ALTER TABLE [promo_codes] ADD FOREIGN KEY ([service_area_id]) REFERENCES [service_areas] ([id])
GO

ALTER TABLE [riders] ADD FOREIGN KEY ([home_service_area_id]) REFERENCES [service_areas] ([id])
GO

ALTER TABLE [saved_places] ADD FOREIGN KEY ([rider_id]) REFERENCES [riders] ([id])
GO

ALTER TABLE [payment_methods] ADD FOREIGN KEY ([rider_id]) REFERENCES [riders] ([id])
GO

ALTER TABLE [promo_redemptions] ADD FOREIGN KEY ([promo_code_id]) REFERENCES [promo_codes] ([id])
GO

ALTER TABLE [promo_redemptions] ADD FOREIGN KEY ([rider_id]) REFERENCES [riders] ([id])
GO

ALTER TABLE [promo_redemptions] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

ALTER TABLE [fare_estimates] ADD FOREIGN KEY ([rider_id]) REFERENCES [riders] ([id])
GO

ALTER TABLE [fare_estimates] ADD FOREIGN KEY ([product_tier_id]) REFERENCES [product_tiers] ([id])
GO

ALTER TABLE [fare_estimates] ADD FOREIGN KEY ([fare_rule_id]) REFERENCES [fare_rules] ([id])
GO

ALTER TABLE [fare_estimates] ADD FOREIGN KEY ([surge_multiplier_id]) REFERENCES [surge_multipliers] ([id])
GO

ALTER TABLE [ride_requests] ADD FOREIGN KEY ([rider_id]) REFERENCES [riders] ([id])
GO

ALTER TABLE [ride_requests] ADD FOREIGN KEY ([product_tier_id]) REFERENCES [product_tiers] ([id])
GO

ALTER TABLE [ride_requests] ADD FOREIGN KEY ([fare_estimate_id]) REFERENCES [fare_estimates] ([id])
GO

ALTER TABLE [ride_requests] ADD FOREIGN KEY ([payment_method_id]) REFERENCES [payment_methods] ([id])
GO

ALTER TABLE [ride_requests] ADD FOREIGN KEY ([promo_redemption_id]) REFERENCES [promo_redemptions] ([id])
GO

ALTER TABLE [ride_requests] ADD FOREIGN KEY ([pickup_zone_id]) REFERENCES [zones] ([id])
GO

ALTER TABLE [dispatch_offers] ADD FOREIGN KEY ([ride_request_id]) REFERENCES [ride_requests] ([id])
GO

ALTER TABLE [dispatch_offers] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([ride_request_id]) REFERENCES [ride_requests] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([dispatch_offer_id]) REFERENCES [dispatch_offers] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([rider_id]) REFERENCES [riders] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([vehicle_id]) REFERENCES [vehicles] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([product_tier_id]) REFERENCES [product_tiers] ([id])
GO

ALTER TABLE [trips] ADD FOREIGN KEY ([fare_rule_id]) REFERENCES [fare_rules] ([id])
GO

ALTER TABLE [trip_cancellations] ADD FOREIGN KEY ([ride_request_id]) REFERENCES [ride_requests] ([id])
GO

ALTER TABLE [trip_cancellations] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

ALTER TABLE [ratings] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

ALTER TABLE [fare_line_items] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([ride_request_id]) REFERENCES [ride_requests] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([payment_method_id]) REFERENCES [payment_methods] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([parent_payment_id]) REFERENCES [payments] ([id])
GO

ALTER TABLE [driver_earnings] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [driver_earnings] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

ALTER TABLE [driver_earnings] ADD FOREIGN KEY ([trip_cancellation_id]) REFERENCES [trip_cancellations] ([id])
GO

ALTER TABLE [driver_earnings] ADD FOREIGN KEY ([driver_payout_id]) REFERENCES [driver_payouts] ([id])
GO

ALTER TABLE [driver_payouts] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [drivers] ADD FOREIGN KEY ([service_area_id]) REFERENCES [service_areas] ([id])
GO

ALTER TABLE [driver_documents] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [driver_documents] ADD FOREIGN KEY ([vehicle_id]) REFERENCES [vehicles] ([id])
GO

ALTER TABLE [vehicles] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [vehicle_product_tiers] ADD FOREIGN KEY ([vehicle_id]) REFERENCES [vehicles] ([id])
GO

ALTER TABLE [vehicle_product_tiers] ADD FOREIGN KEY ([product_tier_id]) REFERENCES [product_tiers] ([id])
GO

ALTER TABLE [driver_sessions] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [driver_sessions] ADD FOREIGN KEY ([vehicle_id]) REFERENCES [vehicles] ([id])
GO

ALTER TABLE [driver_sessions] ADD FOREIGN KEY ([service_area_id]) REFERENCES [service_areas] ([id])
GO

ALTER TABLE [driver_locations] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [driver_locations] ADD FOREIGN KEY ([driver_session_id]) REFERENCES [driver_sessions] ([id])
GO

ALTER TABLE [driver_locations] ADD FOREIGN KEY ([zone_id]) REFERENCES [zones] ([id])
GO

ALTER TABLE [driver_location_pings] ADD FOREIGN KEY ([driver_id]) REFERENCES [drivers] ([id])
GO

ALTER TABLE [driver_location_pings] ADD FOREIGN KEY ([trip_id]) REFERENCES [trips] ([id])
GO

How to use this template

  1. Open the ER diagram to see the tables and how they relate.
  2. Copy it into your workspace. You get your own editable copy, in DBML.
  3. Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.

The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.

Frequently asked questions

Which table is at the centre of the Ride-Hailing App database schema?
drivers. It is referenced by 8 other tables: dispatch_offers, driver_documents, driver_earnings, driver_location_pings, driver_payouts and 3 more.
How is dispatch_offers related to drivers?
dispatch_offers.driver_id references drivers.id, a many to one relationship. All 58 relationships in the schema are listed on this page.
Which table in the Ride-Hailing App database schema has the most columns?
trips, with 21 columns, followed by fare_estimates (15) and ride_requests (15). The schema has 260 columns across 27 tables.
Can I export it to PostgreSQL or MySQL?
Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
Is this template free?
Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
Can I change it after copying it?
Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.