Pular para o conteúdo

Database Architecture

RedeCasas uses two Cloudflare storage services: D1 (SQLite) for relational data and KV for ephemeral session tokens.

D1 (SQLite)

The D1 database is defined in db/schema.sql and seeded via db/seeder/.

Schema Domains

DomainTables
Geographicbrazil_regions, brazil_states, geo_region_types, geo_regions, brazil_cities
Content Configscopes, topics, page_types
Pagespages, page_content_cache, page_generation_log
Real Estateproperty_types, listings, real_estate_agents, imobiliarias
Blogblog_themes, blog_posts
Adscity_ads
Analyticsnotfound_urls, page_views, search_queries
Schedulerdaily_rotation_tracker

Key Design Patterns

  • Slugs are used for URLs: sao-paulo, rio-de-janeiro, energia-solar
  • Content caching: page_content_cache stores pre-rendered HTML so the site generator doesn’t need to re-query all relationships on every build
  • Analytics: notfound_urls tracks 404s from production so the generator can create missing pages

KV (Key-Value)

KV is used exclusively for session storage.

Session Key Format

  • Key: session:{token} (random 32-byte hex string)
  • Value: { userId, email, createdAt, expiresAt }
  • TTL: 7 days (604800 seconds)

Why KV for Sessions?

  • Sub-millisecond reads — faster than D1 for auth validation on every request
  • Instant revocation — delete the key and the session is gone
  • No migration needed — session schema changes don’t require ALTER TABLE
  • Auto-expiry — TTL means old sessions clean themselves up

Local Development

For local development, use SQLite directly:

Terminal window
cd db
sqlite3 redecasas.db < schema.sql

Workers running with wrangler dev will use the local D1 emulator if configured in wrangler.toml.