Auto-indexing service and GraphQL API for AT Protocol Records
quickslice.slices.network/
atproto
gleam
graphql
1// server/src/database/connection.gleam
2
3import database/executor.{type DbError, type Executor}
4import database/postgres/connection as postgres_connection
5import database/sqlite/connection as sqlite_connection
6import gleam/string
7
8/// Supported database backends
9pub type Backend {
10 SQLite
11 PostgreSQL
12}
13
14/// Parse DATABASE_URL and connect to the appropriate backend.
15///
16/// Note: This function connects to the database but does NOT run migrations.
17/// Schema migrations should be run externally using dbmate before starting
18/// the application:
19///
20/// ```sh
21/// DATABASE_URL=sqlite:data/quickslice.db dbmate up
22/// # or
23/// DATABASE_URL=postgres://localhost/quickslice dbmate --migrations-dir ./db/migrations_postgres up
24/// ```
25///
26/// Supported URL formats:
27/// - SQLite: "sqlite:./path/to/db.sqlite", "./path/to/db.sqlite", "file:./path"
28/// - PostgreSQL: "postgres://user:pass@host:port/db", "postgresql://..."
29pub fn connect(url: String) -> Result(Executor, DbError) {
30 case detect_backend(url) {
31 SQLite -> sqlite_connection.connect(url)
32 PostgreSQL -> postgres_connection.connect(url)
33 }
34}
35
36/// Detect the database backend from a URL
37pub fn detect_backend(url: String) -> Backend {
38 let url_lower = string.lowercase(url)
39
40 case
41 string.starts_with(url_lower, "postgres://")
42 || string.starts_with(url_lower, "postgresql://")
43 {
44 True -> PostgreSQL
45 False -> SQLite
46 }
47}