use serde_json::{Value, json};
use crate::db::{self, Dialect, Repo};
use crate::error::{Error, Result};
const MAX_ROWS: usize = 200;
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();
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)
}
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 {
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,
}))
}
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<_>>(),
}))
}
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<_>>(),
}))
}
pub async fn dump(repo: &Repo) -> Result<String> {
db::with(repo, dump_here(repo.dialect())).await
}
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)
}
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('"', "\"\""))
}
}
pub(crate) fn schedules(schedules: &[crate::jobs::Schedule]) -> String {
if schedules.is_empty() {
return "No recurring jobs or scheduled tasks.".to_owned();
}
let rows: Vec<[String; 3]> = schedules
.iter()
.map(|s| {
let next = s.next.map_or_else(
|| "never".to_owned(),
|at| at.format("%Y-%m-%d %H:%M UTC").to_string(),
);
[s.name.clone(), s.when.clone(), next]
})
.collect();
let header = ["NAME", "WHEN", "NEXT"].map(str::to_owned);
let widths: Vec<usize> = (0..2)
.map(|i| {
rows.iter()
.chain([&header])
.map(|r| r[i].chars().count())
.max()
.unwrap_or(0)
})
.collect();
std::iter::once(&header)
.chain(&rows)
.map(|r| {
format!(
"{:w0$} {:w1$} {}",
r[0],
r[1],
r[2],
w0 = widths[0],
w1 = widths[1]
)
})
.collect::<Vec<_>>()
.join("\n")
}
#[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);
}
}