Skip to content

Schema & Migrations ​

PostgreSQL + PostGIS. The schema below is the canonical baseline.

Source of truth and how conflicts were resolved ​

Two earlier design records describe this schema and they disagree. The resolution rules applied here are:

  1. GEOGRAPHY, not GEOMETRY. The matching engine needs true metre-based distance (ST_DWithin, ST_Distance in metres) at Dubai scale, which is exactly what geography gives. geometry works in degrees and silently breaks distance thresholds. All spatial columns are therefore GEOGRAPHY(..., 4326).
  2. Newer artefact wins, older artefact fills gaps. Where the later record dropped a field the earlier one had, the field is restored.
  3. Anything a documented endpoint or engine invariant requires must exist. Tables implied by the API contract or the compliance engine are added explicitly and marked as such.

Tables added to close contract gaps ​

These are not inventions; each is required by an already-documented contract that the earlier DDL left dangling.

TableRequired byGap it closes
recurring_journeysPOST /journeys/recurringjourneys.recurring_journey_id was a UUID with no target table
emergency_contactsPOST /users/me/emergency-contactsendpoint had no storage
user_sessionsAccess + refresh + device session, POST /auth/refresh, POST /auth/logoutrefresh and revocation had no storage
policy_versionsPolicy versioning — "activate a new ruleset without rewriting the application"policy_version was a loose string, not a ruleset
compliance_decisionsImmutable decision history and explainabilitycompliance_events alone cannot hold superseded decisions

bookings.match_id is also added. POST /bookings takes a matchId, so a booking cannot be created without referencing the match that produced it.

Extensions ​

sql
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS pgcrypto;

Identifier strategy ​

All primary entities use gen_random_uuid().

A separate human-readable public_id is exposed to clients so internal UUIDs are never the public identifier.

Enum types ​

sql
CREATE TYPE account_status AS ENUM (
    'PENDING',
    'ACTIVE',
    'RESTRICTED',
    'SUSPENDED',
    'BLOCKED',
    'DELETED'
);

CREATE TYPE account_type AS ENUM (
    'PASSENGER',
    'DRIVER',
    'BOTH',
    'ADMIN',
    'REGULATORY'
);

CREATE TYPE verification_status AS ENUM (
    'UNVERIFIED',
    'PENDING',
    'VERIFIED',
    'EXPIRED',
    'REJECTED',
    'REVIEW'
);

CREATE TYPE relationship_verification AS ENUM (
    'UNVERIFIED',
    'SELF_DECLARED',
    'INVITED',
    'VERIFIED',
    'REJECTED',
    'REVIEW'
);

CREATE TYPE journey_status AS ENUM (
    'DRAFT',
    'PUBLISHED',
    'MATCHING',
    'FULL',
    'IN_PROGRESS',
    'COMPLETED',
    'CANCELLED',
    'EXPIRED',
    'FLAGGED',
    'SUSPENDED'
);

CREATE TYPE journey_type AS ENUM (
    'ONE_TIME',
    'RECURRING'
);

CREATE TYPE request_status AS ENUM (
    'REQUESTED',
    'MATCHING',
    'MATCHED',
    'ACCEPTED',
    'REJECTED',
    'BOOKED',
    'CANCELLED',
    'EXPIRED',
    'COMPLETED',
    'FLAGGED'
);

CREATE TYPE match_status AS ENUM (
    'CANDIDATE',
    'OFFERED',
    'ACCEPTED',
    'DECLINED',
    'EXPIRED',
    'BLOCKED'
);

CREATE TYPE compliance_status AS ENUM (
    'PENDING',
    'ALLOW',
    'REVIEW',
    'BLOCK'
);

CREATE TYPE booking_status AS ENUM (
    'PENDING_CONFIRMATION',
    'CONFIRMED',
    'IN_PROGRESS',
    'COMPLETED',
    'CANCELLED',
    'NO_SHOW',
    'SUSPENDED'
);

CREATE TYPE contribution_type AS ENUM (
    'JOURNEY_COST_SHARE',
    'PETROL_CONTRIBUTION',
    'FIXED_APPROVED_AMOUNT',
    'OTHER_APPROVED'
);

PETROL_CONTRIBUTION is retained on purpose

It is kept in the enum so the policy gate has a value to reject. Labelling a payment "petrol contribution" does not change its legal treatment — see Contribution Policy.

Identity and relationships ​

users ​

sql
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    public_id TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    mobile TEXT UNIQUE,
    email TEXT UNIQUE,
    date_of_birth DATE,
    locale TEXT NOT NULL DEFAULT 'en-AE',
    status account_status NOT NULL DEFAULT 'PENDING',
    account_type account_type NOT NULL DEFAULT 'PASSENGER',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_active_at TIMESTAMPTZ
);

Emirates ID numbers are never stored in users. Identity documents belong in user_identities, encrypted and referenced by hash.

user_identities ​

sql
CREATE TABLE user_identities (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    provider TEXT NOT NULL,
    verification_type TEXT NOT NULL,
    status verification_status NOT NULL DEFAULT 'UNVERIFIED',
    verified_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,
    reference_hash TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Supported verification_type values: MOBILE, EMAIL, UAE_PASS, EMIRATES_ID, MANUAL, OTHER_APPROVED_PROVIDER.

The mechanisms actually supported are decided with the relevant authority/provider, not by this schema.

user_sessions ​

sql
CREATE TABLE user_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    refresh_token_hash TEXT UNIQUE NOT NULL,
    device_hash TEXT,
    issued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at TIMESTAMPTZ NOT NULL,
    revoked_at TIMESTAMPTZ,
    last_used_at TIMESTAMPTZ
);

POST /auth/logout revokes a row here. Access tokens stay short-lived and are not stored.

user_relationships ​

sql
CREATE TABLE user_relationships (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    related_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    relationship_type TEXT NOT NULL,
    verification_status relationship_verification NOT NULL DEFAULT 'UNVERIFIED',
    evidence_reference TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (user_id, related_user_id, relationship_type),
    CHECK (user_id <> related_user_id)
);

Relationship types: FRIEND, RELATIVE, CO_WORKER, SAME_EMPLOYER, SAME_SCHOOL, SAME_COMMUNITY, OTHER.

Not a legal determination

The application records the relationship. Whether it satisfies a regulatory criterion is decided by the active policy, never by this column.

emergency_contacts ​

sql
CREATE TABLE emergency_contacts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    mobile TEXT NOT NULL,
    relationship TEXT,
    is_primary BOOLEAN NOT NULL DEFAULT false,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Participants and vehicles ​

driver_profiles ​

sql
CREATE TABLE driver_profiles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    licence_reference_hash TEXT,
    verification_status verification_status NOT NULL DEFAULT 'UNVERIFIED',
    driver_status TEXT NOT NULL DEFAULT 'ACTIVE',
    approved_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

UNIQUE (user_id) is a compliance control, not just an index: it makes it impossible to escape verification by creating a second driver profile.

Licence references are never exposed to another user.

passenger_profiles ​

sql
CREATE TABLE passenger_profiles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    verification_status verification_status NOT NULL DEFAULT 'UNVERIFIED',
    preferred_language TEXT NOT NULL DEFAULT 'en-AE',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

vehicles ​

sql
CREATE TABLE vehicles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    owner_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    make TEXT NOT NULL,
    model TEXT NOT NULL,
    year INTEGER,
    colour TEXT,
    plate_hash TEXT,
    plate_display TEXT,
    seating_capacity INTEGER NOT NULL,
    status TEXT NOT NULL DEFAULT 'ACTIVE',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (seating_capacity > 0)
);

The vehicle belongs to a user (owner_user_id), not to a driver profile. A user who is both owner and driver has one identity.

vehicle_verifications ​

sql
CREATE TABLE vehicle_verifications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    vehicle_id UUID NOT NULL REFERENCES vehicles(id) ON DELETE CASCADE,
    verification_type TEXT NOT NULL,
    status verification_status NOT NULL DEFAULT 'UNVERIFIED',
    reference_hash TEXT,
    verified_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,
    verified_by UUID,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

A verification history, not a boolean. vehicle.isVerified = true cannot answer "verified by whom, when, until when", which an RTA-facing system needs.

Journeys ​

recurring_journeys ​

sql
CREATE TABLE recurring_journeys (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    driver_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    vehicle_id UUID NOT NULL REFERENCES vehicles(id) ON DELETE CASCADE,
    days SMALLINT[] NOT NULL,
    departure_time TIME NOT NULL,
    origin GEOGRAPHY(Point, 4326) NOT NULL,
    destination GEOGRAPHY(Point, 4326) NOT NULL,
    available_seats INTEGER NOT NULL DEFAULT 1,
    active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (available_seats >= 0)
);

days uses ISO weekday numbers (1 = Monday … 7 = Sunday).

journeys ​

sql
CREATE TABLE journeys (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    driver_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    vehicle_id UUID NOT NULL REFERENCES vehicles(id) ON DELETE CASCADE,
    recurring_journey_id UUID REFERENCES recurring_journeys(id) ON DELETE SET NULL,
    origin GEOGRAPHY(Point, 4326) NOT NULL,
    destination GEOGRAPHY(Point, 4326) NOT NULL,
    departure_at TIMESTAMPTZ NOT NULL,
    estimated_arrival_at TIMESTAMPTZ,
    available_seats INTEGER NOT NULL,
    journey_type journey_type NOT NULL DEFAULT 'ONE_TIME',
    status journey_status NOT NULL DEFAULT 'DRAFT',
    route_deviation_limit_meters INTEGER,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (available_seats >= 0)
);

A journey is an existing journey the driver is already making. The API creates the journey first; a passenger request can only attach to it. This is the "existing journey first" rule expressed as a constraint — a journey always belongs to a driver and a vehicle, and never originates from a passenger demand.

journey_routes ​

sql
CREATE TABLE journey_routes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    journey_id UUID UNIQUE NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
    route_geometry GEOGRAPHY(LineString, 4326) NOT NULL,
    distance_meters DOUBLE PRECISION,
    duration_seconds INTEGER,
    routing_provider TEXT,
    routing_version TEXT,
    calculated_at TIMESTAMPTZ
);

Route geometry lives here, not on journeys. One route per journey, versioned by routing_version so a routing-provider change is auditable.

journey_stops ​

sql
CREATE TABLE journey_stops (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    journey_id UUID NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
    stop_type TEXT NOT NULL,
    sequence_number INTEGER NOT NULL,
    location GEOGRAPHY(Point, 4326) NOT NULL,
    name TEXT,
    planned_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (journey_id, sequence_number)
);

Stop types: ORIGIN, PICKUP, DROPOFF, DESTINATION.

Stops are the privacy control: generalised commute hubs are stored as stops instead of exposing a passenger's home address.

Requests, matching and booking ​

ride_requests ​

sql
CREATE TABLE ride_requests (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    passenger_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    pickup GEOGRAPHY(Point, 4326) NOT NULL,
    dropoff GEOGRAPHY(Point, 4326) NOT NULL,
    requested_for TIMESTAMPTZ NOT NULL,
    passenger_count INTEGER NOT NULL DEFAULT 1,
    status request_status NOT NULL DEFAULT 'REQUESTED',
    expires_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (passenger_count > 0)
);

A request expresses want, never supply. It never creates a driver journey.

matches ​

sql
CREATE TABLE matches (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    ride_request_id UUID NOT NULL REFERENCES ride_requests(id) ON DELETE CASCADE,
    journey_id UUID NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
    route_score NUMERIC(6,2),
    pickup_score NUMERIC(6,2),
    dropoff_score NUMERIC(6,2),
    time_score NUMERIC(6,2),
    seat_score NUMERIC(6,2),
    overall_score NUMERIC(6,2),
    detour_meters DOUBLE PRECISION,
    detour_seconds INTEGER,
    detour_percentage NUMERIC(8,3),
    eligibility_status compliance_status NOT NULL DEFAULT 'PENDING',
    compliance_status compliance_status NOT NULL DEFAULT 'PENDING',
    status match_status NOT NULL DEFAULT 'CANDIDATE',
    algorithm_version TEXT NOT NULL DEFAULT 'matching-0.1',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at TIMESTAMPTZ,
    UNIQUE (ride_request_id, journey_id)
);

eligibility_status and compliance_status are separate columns on purpose: eligibility is a factual check, compliance is a policy decision, and conflating them hides which one blocked a match.

bookings ​

sql
CREATE TABLE bookings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    match_id UUID NOT NULL REFERENCES matches(id) ON DELETE CASCADE,
    journey_id UUID NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
    ride_request_id UUID NOT NULL REFERENCES ride_requests(id) ON DELETE CASCADE,
    driver_id UUID NOT NULL REFERENCES users(id),
    passenger_id UUID NOT NULL REFERENCES users(id),
    pickup_stop_id UUID REFERENCES journey_stops(id),
    dropoff_stop_id UUID REFERENCES journey_stops(id),
    status booking_status NOT NULL DEFAULT 'PENDING_CONFIRMATION',
    confirmed_at TIMESTAMPTZ,
    picked_up_at TIMESTAMPTZ,
    dropped_off_at TIMESTAMPTZ,
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    cancelled_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

The booking is the confirmed shared journey. It is not a "trip" and not a "ride": those imply a dispatch relationship that does not exist here.

Cost sharing and feedback ​

contributions ​

sql
CREATE TABLE contributions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    booking_id UUID NOT NULL REFERENCES bookings(id) ON DELETE CASCADE,
    contribution_type contribution_type NOT NULL,
    amount NUMERIC(12,2),
    currency CHAR(3) NOT NULL DEFAULT 'AED',
    calculation_method TEXT,
    policy_version TEXT,
    status TEXT NOT NULL DEFAULT 'PENDING',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Availability is determined by the active policy, not by this table. If the active policy does not enable contributions, nothing can be written here.

ratings ​

sql
CREATE TABLE ratings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    booking_id UUID NOT NULL REFERENCES bookings(id) ON DELETE CASCADE,
    reviewer_id UUID NOT NULL REFERENCES users(id),
    reviewee_id UUID NOT NULL REFERENCES users(id),
    rating INTEGER NOT NULL,
    punctuality INTEGER,
    communication INTEGER,
    safety INTEGER,
    comment TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (booking_id, reviewer_id),
    CHECK (rating BETWEEN 1 AND 5)
);

Ratings never influence a compliance decision.

incidents ​

sql
CREATE TABLE incidents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    reporter_id UUID NOT NULL REFERENCES users(id),
    user_id UUID REFERENCES users(id),
    journey_id UUID REFERENCES journeys(id) ON DELETE SET NULL,
    booking_id UUID REFERENCES bookings(id) ON DELETE SET NULL,
    incident_type TEXT NOT NULL,
    severity TEXT NOT NULL,
    description TEXT,
    status TEXT NOT NULL DEFAULT 'OPEN',
    resolution TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    resolved_at TIMESTAMPTZ
);

Incident types: SAFETY, HARASSMENT, VEHICLE, DRIVING, PAYMENT, IDENTITY, FRAUD, OTHER.

Compliance ​

policy_versions ​

sql
CREATE TABLE policy_versions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    version TEXT UNIQUE NOT NULL,
    label TEXT,
    status TEXT NOT NULL DEFAULT 'DRAFT',
    configuration JSONB NOT NULL DEFAULT '{}'::jsonb,
    activated_at TIMESTAMPTZ,
    superseded_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

configuration holds the policy document described in Compliance Engine.

An empty or null value in the configuration means the value must be supplied by an approved policy — it never means "no limit".

compliance_rules ​

sql
CREATE TABLE compliance_rules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    description TEXT,
    domain TEXT NOT NULL,
    severity TEXT NOT NULL,
    action TEXT NOT NULL,
    enabled BOOLEAN NOT NULL DEFAULT true,
    policy_version TEXT NOT NULL REFERENCES policy_versions(version),
    configuration JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

code is globally unique so a decision can always name the rule that produced it. policy_version makes a ruleset swappable without a code change.

compliance_decisions ​

sql
CREATE TABLE compliance_decisions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    journey_id UUID REFERENCES journeys(id) ON DELETE SET NULL,
    match_id UUID REFERENCES matches(id) ON DELETE SET NULL,
    booking_id UUID REFERENCES bookings(id) ON DELETE SET NULL,
    policy_version TEXT NOT NULL,
    decision TEXT NOT NULL,
    risk_level TEXT NOT NULL,
    reason_codes TEXT[] NOT NULL DEFAULT '{}',
    rule_results JSONB NOT NULL DEFAULT '[]'::jsonb,
    evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
    algorithm_version TEXT,
    request_id TEXT,
    actor_type TEXT NOT NULL DEFAULT 'SYSTEM',
    actor_id UUID,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Append-only. A superseding decision inserts a new row; it never updates or deletes the previous one.

compliance_events ​

sql
CREATE TABLE compliance_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    rule_id UUID REFERENCES compliance_rules(id) ON DELETE SET NULL,
    user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    journey_id UUID REFERENCES journeys(id) ON DELETE SET NULL,
    booking_id UUID REFERENCES bookings(id) ON DELETE SET NULL,
    policy_version TEXT,
    severity TEXT NOT NULL,
    event_type TEXT NOT NULL,
    description TEXT,
    evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
    status TEXT NOT NULL DEFAULT 'OPEN',
    resolution TEXT,
    resolved_by UUID,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    resolved_at TIMESTAMPTZ
);

An event is something that needs attention and a human. A decision is the engine's answer. They are separate: one match can produce a decision and no event, or several events and one decision.

Audit and notifications ​

audit_logs ​

sql
CREATE TABLE audit_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    actor_type TEXT NOT NULL DEFAULT 'SYSTEM',
    actor_id UUID,
    action TEXT NOT NULL,
    resource_type TEXT NOT NULL,
    resource_id UUID,
    old_values JSONB,
    new_values JSONB,
    ip_hash TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Effectively append-only: no UPDATE or DELETE grants at the database role level. Administrative actions are audited here.

notifications ​

sql
CREATE TABLE notifications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    type TEXT NOT NULL,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    data JSONB NOT NULL DEFAULT '{}'::jsonb,
    read_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Indexes ​

Spatial ​

sql
CREATE INDEX idx_journeys_origin ON journeys USING GIST (origin);
CREATE INDEX idx_journeys_destination ON journeys USING GIST (destination);
CREATE INDEX idx_journey_routes_geometry ON journey_routes USING GIST (route_geometry);
CREATE INDEX idx_journey_stops_location ON journey_stops USING GIST (location);
CREATE INDEX idx_ride_requests_pickup ON ride_requests USING GIST (pickup);
CREATE INDEX idx_ride_requests_dropoff ON ride_requests USING GIST (dropoff);

Matching ​

sql
CREATE INDEX idx_journeys_matching
    ON journeys (status, departure_at, available_seats);

The candidate query filters on exactly this triple, so the column order matters.

Compliance ​

sql
CREATE INDEX idx_compliance_decisions_journey ON compliance_decisions(journey_id);
CREATE INDEX idx_compliance_decisions_created ON compliance_decisions(created_at);
CREATE INDEX idx_compliance_events_journey ON compliance_events(journey_id);
CREATE INDEX idx_compliance_events_user ON compliance_events(user_id);
CREATE INDEX idx_compliance_events_status ON compliance_events(status);
CREATE INDEX idx_compliance_events_created ON compliance_events(created_at);

Reference queries ​

Candidate discovery ​

Find journeys whose origin is within a configurable radius with enough seats:

sql
SELECT id, driver_id, vehicle_id, departure_at
FROM journeys
WHERE status IN ('PUBLISHED', 'MATCHING')
  AND available_seats >= :passenger_count
  AND departure_at BETWEEN :window_start AND :window_end
  AND ST_DWithin(origin, :pickup_point, :pickup_radius_meters);

This is the spatial pre-filter. It is cheap and must run before route recalculation.

Route proximity ​

sql
SELECT
    j.id,
    ST_Distance(r.route_geometry, :pickup_point) AS pickup_distance
FROM journeys j
JOIN journey_routes r ON r.journey_id = j.id
WHERE j.status IN ('PUBLISHED', 'MATCHING')
ORDER BY pickup_distance ASC;

Migration sequence ​

text
001_extensions
002_enums
003_users
004_identities
005_sessions
006_relationships
007_emergency_contacts
008_driver_profiles
009_passenger_profiles
010_vehicles
011_vehicle_verifications
012_recurring_journeys
013_journeys
014_journey_routes
015_journey_stops
016_ride_requests
017_matches
018_bookings
019_contributions
020_ratings
021_incidents
022_policy_versions
023_compliance_rules
024_compliance_decisions
025_compliance_events
026_audit_logs
027_notifications
028_indexes

Migrations are append-only. A schema change is a new numbered migration, never an edit to a released one.

Implementation rule ​

The database stores facts, configuration and evidence.

It does not contain the business-policy engine as hard-coded SQL.

text
Database  ->  facts + configuration
         ->  application rules engine
         ->  compliance decision
         ->  audit record

Approved operating requirements must be able to change without redesigning the database. That is why policy lives in policy_versions and rules reference it by version rather than encoding thresholds in SQL.

KHAWI — same route, go together.