glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! App tasks for tools (`GLACIER_TASK=db:schema` and friends): what's in
//! the database, a read-only query, the job queue. Each returns JSON for
//! the CLI or the MCP to pass on.

use serde_json::{Value, json};

use crate::db::{self, Dialect, Repo};
use crate::error::{Error, Result};

/// The most rows a query returns.
const MAX_ROWS: usize = 200;

/// Every table with its columns: name, type, whether NULL is allowed and
/// the default.
pub async fn schema(repo: &Repo) -> Result<Value> {
    let sql = match repo.dialect() {
        Dialect::Postgres => {
            "SELECT table_name, column_name, data_type, is_nullable = 'YES' AS nullable, \
             column_default AS default_value FROM information_schema.columns \
             WHERE table_schema = current_schema() ORDER BY table_name, ordinal_position"
        }
        Dialect::Sqlite => {
            "SELECT m.name AS table_name, p.name AS column_name, p.type AS data_type, \
             p.\"notnull\" = 0 AS nullable, p.dflt_value AS default_value \
             FROM sqlite_master m JOIN pragma_table_info(m.name) p \
             WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%' ORDER BY m.name, p.cid"
        }
    };
    let rows = db::with(repo, db::sql(sql).fetch_all()).await?;
    let mut tables: Vec<(String, Vec<Value>)> = Vec::new();
    for row in rows {
        let table: String = row.get("table_name")?;
        let values = row.to_json();
        // A boolean in Postgres, 0 or 1 in SQLite.
        let nullable = values["nullable"]
            .as_bool()
            .or_else(|| values["nullable"].as_i64().map(|n| n != 0))
            .unwrap_or(true);
        let column = json!({
            "name": values["column_name"],
            "type": values["data_type"],
            "nullable": nullable,
            "default": values["default_value"],
        });
        match tables.last_mut() {
            Some((name, columns)) if *name == table => columns.push(column),
            _ => tables.push((table, vec![column])),
        }
    }
    let mut out = json!({
        "database": repo.name(),
        "tables": tables
            .iter()
            .map(|(name, columns)| json!({"name": name, "columns": columns}))
            .collect::<Vec<_>>(),
    });
    if tables.is_empty() {
        out["hint"] = json!(
            "this database has no tables: it may not be the one the app uses. The URL \
             comes from database.url in config/, overridden by GLACIER__DATABASE__URL \
             in the environment the app runs with"
        );
    }
    Ok(out)
}

/// Runs `sql` read-only (in a transaction the database itself refuses to
/// write in, then rolled back) and returns its rows, at most 200.
pub async fn query(repo: &Repo, sql: &str) -> Result<Value> {
    let dialect = repo.dialect();
    let rows = db::sandbox(repo, async move {
        match dialect {
            Dialect::Postgres => db::sql("SET TRANSACTION READ ONLY").execute().await?,
            Dialect::Sqlite => db::sql("PRAGMA query_only = ON").execute().await?,
        };
        let rows = db::sql(sql).fetch_all().await;
        if dialect == Dialect::Sqlite {
            // The pragma outlives the transaction on a pooled connection.
            db::sql("PRAGMA query_only = OFF").execute().await?;
        }
        rows
    })
    .await?
    .map_err(|err| Error::internal(format!("{} (on {})", err.message(), repo.name())))?;
    let total = rows.len();
    let rows: Vec<Value> = rows.iter().take(MAX_ROWS).map(db::Row::to_json).collect();
    Ok(json!({
        "database": repo.name(),
        "rows": rows,
        "count": total,
        "truncated": total > MAX_ROWS,
    }))
}

/// The job queue: how many jobs are due, scheduled, running and failed,
/// and the failed ones with their last errors.
pub async fn jobs(repo: &Repo) -> Result<Value> {
    let exists = match repo.dialect() {
        Dialect::Postgres => {
            "SELECT 1 AS found FROM information_schema.tables \
             WHERE table_schema = current_schema() AND table_name = 'glacier_jobs'"
        }
        Dialect::Sqlite => {
            "SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = 'glacier_jobs'"
        }
    };
    if db::with(repo, db::sql(exists).fetch_all())
        .await?
        .is_empty()
    {
        return Ok(json!({
            "installed": false,
            "hint": "the app has no job table yet: `glacier generate job <Name>` adds its migration",
        }));
    }
    let now = crate::time::now();
    let counts = db::with(
        repo,
        db::sql(
            "SELECT \
             SUM(CASE WHEN failed_at IS NULL AND locked_at IS NULL AND run_at <= ? THEN 1 ELSE 0 END) AS due, \
             SUM(CASE WHEN failed_at IS NULL AND locked_at IS NULL AND run_at > ? THEN 1 ELSE 0 END) AS scheduled, \
             SUM(CASE WHEN failed_at IS NULL AND locked_at IS NOT NULL THEN 1 ELSE 0 END) AS running, \
             SUM(CASE WHEN failed_at IS NOT NULL THEN 1 ELSE 0 END) AS failed \
             FROM glacier_jobs",
        )
        .bind(now)
        .bind(now)
        .fetch_all(),
    )
    .await?;
    let failed = db::with(
        repo,
        db::sql(
            "SELECT id, name, queue, attempts, last_error, failed_at FROM glacier_jobs \
             WHERE failed_at IS NOT NULL ORDER BY failed_at DESC LIMIT 20",
        )
        .fetch_all(),
    )
    .await?;
    let queues = db::with(
        repo,
        db::sql(
            "SELECT queue, \
             SUM(CASE WHEN failed_at IS NULL AND locked_at IS NULL AND run_at <= ? THEN 1 ELSE 0 END) AS due, \
             SUM(CASE WHEN failed_at IS NULL AND locked_at IS NULL AND run_at > ? THEN 1 ELSE 0 END) AS scheduled, \
             SUM(CASE WHEN failed_at IS NULL AND locked_at IS NOT NULL THEN 1 ELSE 0 END) AS running, \
             SUM(CASE WHEN failed_at IS NOT NULL THEN 1 ELSE 0 END) AS failed \
             FROM glacier_jobs GROUP BY queue ORDER BY queue",
        )
        .bind(now)
        .bind(now)
        .fetch_all(),
    )
    .await?;
    let counts = counts.first().map(db::Row::to_json).unwrap_or_default();
    let number = |key: &str| counts[key].as_i64().unwrap_or(0);
    Ok(json!({
        "installed": true,
        "due": number("due"),
        "scheduled": number("scheduled"),
        "running": number("running"),
        "failed": number("failed"),
        "queues": queues.iter().map(db::Row::to_json).collect::<Vec<_>>(),
        "recent_failures": failed.iter().map(db::Row::to_json).collect::<Vec<_>>(),
    }))
}

/// The webhook events: counts by provider and status, and the latest 20.
pub async fn webhooks(repo: &Repo) -> Result<Value> {
    let counts = db::with(
        repo,
        db::sql(
            "SELECT provider, status, COUNT(*) AS events FROM webhook_events \
             GROUP BY provider, status ORDER BY provider, status",
        )
        .fetch_all(),
    )
    .await;
    let Ok(counts) = counts else {
        return Ok(json!({
            "installed": false,
            "hint": "the app has no webhook_events table: add a migration calling glacier::webhooks::create_table(s)",
        }));
    };
    let latest = db::with(
        repo,
        db::sql(
            "SELECT id, provider, event_id, event_type, status, attempts, last_error, inserted_at, processed_at \
             FROM webhook_events ORDER BY id DESC LIMIT 20",
        )
        .fetch_all(),
    )
    .await?;
    Ok(json!({
        "installed": true,
        "counts": counts.iter().map(db::Row::to_json).collect::<Vec<_>>(),
        "latest": latest.iter().map(db::Row::to_json).collect::<Vec<_>>(),
    }))
}

/// The schema as SQL, for `db/schema.sql`: every table (but the
/// migrations table), its columns, constraints and indexes, in name order.
/// SQLite keeps each statement as written; for Postgres it's rebuilt from
/// the catalog.
pub async fn dump(repo: &Repo) -> Result<String> {
    db::with(repo, dump_here(repo.dialect())).await
}

/// [`dump`] on the ambient connection.
async fn dump_here(dialect: Dialect) -> Result<String> {
    let (skip, beside_rails) = (
        crate::db::migration::MIGRATIONS_TABLE,
        crate::db::migration::BESIDE_RAILS_TABLE,
    );
    let mut statements = Vec::new();
    match dialect {
        Dialect::Sqlite => {
            let rows = (db::sql(
                "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL \
                     AND name NOT LIKE 'sqlite_%' AND tbl_name NOT IN (?, ?) \
                     ORDER BY tbl_name, type DESC, name",
            )
            .bind(skip)
            .bind(beside_rails)
            .fetch_all())
            .await?;
            for row in rows {
                statements.push(row.get::<String>("sql")?);
            }
        }
        Dialect::Postgres => {
            let columns = (db::sql(
                "SELECT c.relname AS table_name, a.attname AS column_name, \
                     format_type(a.atttypid, a.atttypmod) AS column_type, \
                     a.attnotnull AS not_null, pg_get_expr(d.adbin, d.adrelid) AS default_value \
                     FROM pg_attribute a JOIN pg_class c ON a.attrelid = c.oid \
                     JOIN pg_namespace n ON c.relnamespace = n.oid \
                     LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
                     WHERE n.nspname = current_schema() AND c.relkind = 'r' \
                     AND a.attnum > 0 AND NOT a.attisdropped AND c.relname NOT IN (?, ?) \
                     ORDER BY c.relname, a.attnum",
            )
            .bind(skip)
            .bind(beside_rails)
            .fetch_all())
            .await?;
            let constraints = (db::sql(
                "SELECT c.relname AS table_name, k.conname AS name, \
                     pg_get_constraintdef(k.oid) AS definition \
                     FROM pg_constraint k JOIN pg_class c ON k.conrelid = c.oid \
                     JOIN pg_namespace n ON c.relnamespace = n.oid \
                     WHERE n.nspname = current_schema() AND c.relname NOT IN (?, ?) \
                     AND k.contype IN ('p', 'u', 'f', 'c') \
                     ORDER BY c.relname, k.contype, k.conname",
            )
            .bind(skip)
            .bind(beside_rails)
            .fetch_all())
            .await?;
            let indexes = (db::sql(
                "SELECT i.tablename AS table_name, i.indexdef AS definition FROM pg_indexes i \
                     WHERE i.schemaname = current_schema() AND i.tablename NOT IN (?, ?) \
                     AND NOT EXISTS (SELECT 1 FROM pg_constraint k \
                       WHERE k.conindid = format('%I.%I', i.schemaname, i.indexname)::regclass) \
                     ORDER BY i.tablename, i.indexname",
            )
            .bind(skip)
            .bind(beside_rails)
            .fetch_all())
            .await?;
            let mut tables: Vec<(String, Vec<String>)> = Vec::new();
            for row in &columns {
                let table: String = row.get("table_name")?;
                let mut line = format!(
                    "  {} {}",
                    quote(&row.get::<String>("column_name")?),
                    row.get::<String>("column_type")?
                );
                if let Some(default) = row.get::<Option<String>>("default_value")? {
                    line.push_str(&format!(" DEFAULT {default}"));
                }
                if row.get::<bool>("not_null")? {
                    line.push_str(" NOT NULL");
                }
                match tables.last_mut() {
                    Some((name, lines)) if *name == table => lines.push(line),
                    _ => tables.push((table, vec![line])),
                }
            }
            for row in &constraints {
                let table: String = row.get("table_name")?;
                if let Some((_, lines)) = tables.iter_mut().find(|(name, _)| *name == table) {
                    lines.push(format!(
                        "  CONSTRAINT {} {}",
                        quote(&row.get::<String>("name")?),
                        row.get::<String>("definition")?
                    ));
                }
            }
            for (table, lines) in tables {
                statements.push(format!(
                    "CREATE TABLE {} (\n{}\n)",
                    quote(&table),
                    lines.join(",\n")
                ));
                for row in &indexes {
                    if row.get::<String>("table_name")? == table {
                        statements.push(row.get::<String>("definition")?);
                    }
                }
            }
        }
    }
    let mut out = String::from(
        "-- The database schema, written by `glacier db migrate`. Change it with\n\
         -- a migration, never by editing this file.\n\n",
    );
    for statement in statements {
        out.push_str(statement.trim_end());
        out.push_str(";\n\n");
    }
    out.truncate(out.trim_end().len());
    out.push('\n');
    Ok(out)
}

/// A Postgres identifier, quoted only when it has to be.
fn quote(name: &str) -> String {
    let plain = name
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
        && !name.starts_with(|c: char| c.is_ascii_digit());
    if plain {
        name.to_owned()
    } else {
        format!("\"{}\"", name.replace('"', "\"\""))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn repo(name: &str) -> (Repo, std::path::PathBuf) {
        let path = std::env::temp_dir().join(format!(
            "glacier-tasks-{name}-{}.sqlite3",
            std::process::id()
        ));
        let _ = std::fs::remove_file(&path);
        let repo = Repo::connect(&format!("sqlite://{}?mode=rwc", path.display()))
            .await
            .unwrap();
        db::with(&repo, async {
            db::sql("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL, views INTEGER DEFAULT 0, published BOOLEAN)")
                .execute()
                .await
                .unwrap();
            db::sql("INSERT INTO posts (title, views, published) VALUES ('Hi', 3, 1), ('There', 5, NULL)")
                .execute()
                .await
                .unwrap();
        })
        .await;
        (repo, path)
    }

    #[tokio::test]
    async fn describes_the_schema() {
        let (repo, path) = repo("schema").await;
        let schema = schema(&repo).await.unwrap();
        let posts = &schema["tables"][0];
        assert_eq!(posts["name"], "posts");
        assert_eq!(
            posts["columns"][1],
            json!({"name": "title", "type": "TEXT", "nullable": false, "default": null})
        );
        assert_eq!(posts["columns"][2]["default"], "0");
        let _ = std::fs::remove_file(path);
    }

    #[tokio::test]
    async fn queries_read_only() {
        let (repo, path) = repo("query").await;
        let found = query(
            &repo,
            "SELECT title, views, published FROM posts ORDER BY id",
        )
        .await
        .unwrap();
        assert_eq!(
            found["rows"],
            json!([
                {"title": "Hi", "views": 3, "published": 1},
                {"title": "There", "views": 5, "published": null}
            ])
        );
        assert!(
            query(&repo, "DELETE FROM posts").await.is_err(),
            "writes refused"
        );
        let still = query(&repo, "SELECT COUNT(*) AS n FROM posts")
            .await
            .unwrap();
        assert_eq!(still["rows"][0]["n"], 2);
        let _ = std::fs::remove_file(path);
    }

    #[tokio::test]
    async fn reads_every_postgres_type() {
        let Ok(url) = std::env::var("GLACIER_TEST_POSTGRES_URL") else {
            return;
        };
        let repo = Repo::connect(&url).await.unwrap();
        let found = query(
            &repo,
            "SELECT 1::int4 AS a, 2::int8 AS b, 3::int2 AS c, true AS d, 1.50::numeric AS e, \
             2.5::float8 AS f, 'x'::text AS g, '{\"k\": 1}'::jsonb AS h, NULL::text AS i, \
             '2026-10-04 12:00:00'::timestamp AS j, DATE '2026-10-04' AS k, \
             '7c9e6679-7425-40de-944b-e07fc1f90ae7'::uuid AS l",
        )
        .await
        .unwrap();
        assert_eq!(
            found["rows"][0],
            json!({
                "a": 1, "b": 2, "c": 3, "d": true, "e": "1.5", "f": 2.5, "g": "x",
                "h": {"k": 1}, "i": null, "j": "2026-10-04 12:00:00", "k": "2026-10-04",
                "l": "7c9e6679-7425-40de-944b-e07fc1f90ae7"
            })
        );
        assert!(
            query(&repo, "CREATE TABLE glacier_should_not_exist (id int)")
                .await
                .is_err(),
            "read-only"
        );
    }

    #[tokio::test]
    async fn dumps_the_schema() {
        let (repo, path) = repo("dump").await;
        db::with(&repo, async {
            db::sql("CREATE INDEX index_posts_on_title ON posts (title)")
                .execute()
                .await
                .unwrap();
            db::sql("CREATE TABLE schema_migrations (version TEXT)")
                .execute()
                .await
                .unwrap();
        })
        .await;
        assert_eq!(
            dump(&repo).await.unwrap(),
            "-- The database schema, written by `glacier db migrate`. Change it with\n\
             -- a migration, never by editing this file.\n\n\
             CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL, views INTEGER DEFAULT 0, published BOOLEAN);\n\n\
             CREATE INDEX index_posts_on_title ON posts (title);\n"
        );
        let _ = std::fs::remove_file(path);
    }

    #[tokio::test]
    async fn dumps_a_postgres_schema() {
        let Ok(url) = std::env::var("GLACIER_TEST_POSTGRES_URL") else {
            return;
        };
        let repo = Repo::connect(&url).await.unwrap();
        let dumped = db::sandbox(&repo, async {
            db::sql("CREATE SCHEMA glacier_dump_test").execute().await?;
            db::sql("SET LOCAL search_path TO glacier_dump_test").execute().await?;
            db::sql(
                "CREATE TABLE authors (id bigserial PRIMARY KEY, name varchar(80) NOT NULL UNIQUE)",
            )
            .execute()
            .await?;
            db::sql(
                "CREATE TABLE books (id bigserial PRIMARY KEY, \"Title\" text, \
                 author_id bigint NOT NULL REFERENCES authors (id), pages integer DEFAULT 0 CHECK (pages >= 0))",
            )
            .execute()
            .await?;
            db::sql("CREATE INDEX index_books_on_author_id ON books (author_id)")
                .execute()
                .await?;
            dump_here(Dialect::Postgres).await
        })
        .await
        .unwrap()
        .unwrap();
        assert_eq!(
            dumped,
            "-- The database schema, written by `glacier db migrate`. Change it with\n\
             -- a migration, never by editing this file.\n\n\
             CREATE TABLE authors (\n  \
             id bigint DEFAULT nextval('authors_id_seq'::regclass) NOT NULL,\n  \
             name character varying(80) NOT NULL,\n  \
             CONSTRAINT authors_pkey PRIMARY KEY (id),\n  \
             CONSTRAINT authors_name_key UNIQUE (name)\n);\n\n\
             CREATE TABLE books (\n  \
             id bigint DEFAULT nextval('books_id_seq'::regclass) NOT NULL,\n  \
             \"Title\" text,\n  \
             author_id bigint NOT NULL,\n  \
             pages integer DEFAULT 0,\n  \
             CONSTRAINT books_pages_check CHECK ((pages >= 0)),\n  \
             CONSTRAINT books_author_id_fkey FOREIGN KEY (author_id) REFERENCES authors(id),\n  \
             CONSTRAINT books_pkey PRIMARY KEY (id)\n);\n\n\
             CREATE INDEX index_books_on_author_id ON glacier_dump_test.books USING btree (author_id);\n"
        );
    }

    #[tokio::test]
    async fn summarises_the_job_queue() {
        let (repo, path) = repo("jobs").await;
        db::with(&repo, async {
            let migration = crate::db::migration::Migration::new("m1", crate::jobs::create_table, |_| {});
            for statement in migration.up_sql(repo.dialect()) {
                db::sql(&statement).execute().await.unwrap();
            }
            for (name, run_at, failed) in [
                ("due", "2000-01-01T00:00:00+00:00", None),
                ("later", "2999-01-01T00:00:00+00:00", None),
                ("broken", "2000-01-01T00:00:00+00:00", Some("2000-01-02T00:00:00+00:00")),
            ] {
                db::sql("INSERT INTO glacier_jobs (name, queue, args, attempts, max_attempts, run_at, failed_at, last_error, inserted_at, updated_at) VALUES (?, 'default', '{}', 1, 5, ?, ?, 'boom', ?, ?)")
                    .bind(name)
                    .bind(run_at)
                    .bind(failed)
                    .bind(run_at)
                    .bind(run_at)
                    .execute()
                    .await
                    .unwrap();
            }
        })
        .await;
        let summary = jobs(&repo).await.unwrap();
        assert_eq!(
            (
                summary["due"].clone(),
                summary["scheduled"].clone(),
                summary["failed"].clone()
            ),
            (json!(1), json!(1), json!(1))
        );
        assert_eq!(summary["recent_failures"][0]["name"], "broken");
        assert_eq!(summary["recent_failures"][0]["last_error"], "boom");
        let _ = std::fs::remove_file(path);
    }
}