Add admin CRUD via schema-derived forms sharing validate/submit.
Infer fields from SQLite table_info; serve /admin/{table}/new|edit|delete.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ee019fb1c2
commit
897db76aa7
8 files changed
+494
-56
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted · 实现中**(旧实现已清空,按本文从零开发) |
|
||||
| 状态 | **Accepted · 实现中**(页面装配 / db CRUD / form §5.5 / admin schema 表单已落地) |
|
||||
| 日期 | 2026-08-11 |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) |
|
||||
| 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) |
|
||||
|
||||
+7
-3
@@ -18,9 +18,13 @@ Canonical sample (design §4): [`examples/web-site/`](../../examples/web-site/).
|
||||
|
||||
```bash
|
||||
cargo run -- run examples/web-site/index.mq.md
|
||||
# http://127.0.0.1:18081/ · /admin
|
||||
# http://127.0.0.1:18081/
|
||||
# /_form/article · /admin · /admin/articles/new
|
||||
```
|
||||
|
||||
Offline assemble smoke: `tests/ext/web-smoke.mq.md`.
|
||||
Offline smokes: `tests/ext/web-smoke.mq.md`, `web-form-smoke.mq.md`, `web-admin-smoke.mq.md`.
|
||||
|
||||
**Form / validate / submit** (§5.5): field table + rules + `mount_form` → `GET|POST /_form/{id}`.
|
||||
| Feature | Notes |
|
||||
|---------|--------|
|
||||
| Form §5.5 | field/rules tables · `validate` · `submit` · `mount_form` → `GET\|POST /_form/{id}` |
|
||||
| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` |
|
||||
@@ -286,3 +286,32 @@ pub fn list_tables(url: &str) -> Result<Vec<String>, String> {
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ColumnInfo {
|
||||
pub name: String,
|
||||
pub sql_type: String,
|
||||
pub notnull: bool,
|
||||
pub pk: bool,
|
||||
}
|
||||
|
||||
/// `PRAGMA table_info` → column metadata for admin forms.
|
||||
pub fn table_info(url: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
|
||||
let table = ident(table)?;
|
||||
let conn = open(url)?;
|
||||
let sql = format!("PRAGMA table_info(\"{table}\")");
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let rows = stmt
|
||||
.query_map([], |r| {
|
||||
Ok(ColumnInfo {
|
||||
name: r.get::<_, String>(1)?,
|
||||
sql_type: r.get::<_, String>(2).unwrap_or_else(|_| "TEXT".into()),
|
||||
notnull: r.get::<_, i64>(3).unwrap_or(0) != 0,
|
||||
pk: r.get::<_, i64>(5).unwrap_or(0) != 0,
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string())?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(rows)
|
||||
}
|
||||
+131
-15
@@ -175,6 +175,74 @@ pub fn form_new(table: Option<&str>, action: &str, id: Option<&str>) -> Value {
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
fn sql_type_to_input(sql_type: &str, name: &str) -> &'static str {
|
||||
let t = sql_type.to_ascii_uppercase();
|
||||
if t.contains("INT") || t.contains("REAL") || t.contains("FLOAT") || t.contains("DOUBLE") {
|
||||
return "number";
|
||||
}
|
||||
if name == "body" || name.ends_with("_body") || name.ends_with("_text") {
|
||||
return "textarea";
|
||||
}
|
||||
if name.contains("email") {
|
||||
return "email";
|
||||
}
|
||||
if name.contains("url") || name == "href" {
|
||||
return "url";
|
||||
}
|
||||
"text"
|
||||
}
|
||||
|
||||
/// Build a form handle from live SQLite schema (admin new/edit).
|
||||
pub fn from_schema(
|
||||
db_url: &str,
|
||||
table: &str,
|
||||
action: &str,
|
||||
id: Option<&str>,
|
||||
) -> Result<Value, String> {
|
||||
let action = match action {
|
||||
"update" | "更新" => "update",
|
||||
_ => "insert",
|
||||
};
|
||||
let cols = db::table_info(db_url, table)?;
|
||||
if cols.is_empty() {
|
||||
return Err(format!("unknown table `{table}`"));
|
||||
}
|
||||
let mut fields = Vec::new();
|
||||
for c in &cols {
|
||||
if action == "insert" && c.pk && c.name == "id" {
|
||||
continue; // SERIAL / AUTOINCREMENT
|
||||
}
|
||||
let input = sql_type_to_input(&c.sql_type, &c.name);
|
||||
let required = c.notnull || (action == "update" && c.pk);
|
||||
fields.push(json!({
|
||||
"name": c.name,
|
||||
"label": c.name,
|
||||
"type": input,
|
||||
"required": required,
|
||||
"default": "",
|
||||
"pk": c.pk,
|
||||
}));
|
||||
}
|
||||
let mut form = form_new(Some(table), action, id);
|
||||
if let Some(obj) = form.as_object_mut() {
|
||||
obj.insert("fields".into(), Value::Array(fields));
|
||||
obj.insert("redirect".into(), json!(format!("/admin/{table}")));
|
||||
if action == "insert" {
|
||||
obj.insert("action_url".into(), json!(format!("/admin/{table}/new")));
|
||||
obj.insert("title".into(), json!(format!("New {table}")));
|
||||
} else if let Some(i) = id {
|
||||
obj.insert(
|
||||
"action_url".into(),
|
||||
json!(format!("/admin/{table}/{i}/edit")),
|
||||
);
|
||||
obj.insert("title".into(), json!(format!("Edit {table} #{i}")));
|
||||
obj.insert("id".into(), json!(i));
|
||||
}
|
||||
obj.insert("cancel_href".into(), json!(format!("/admin/{table}")));
|
||||
}
|
||||
Ok(form)
|
||||
}
|
||||
|
||||
pub fn set_fields(form: &Value, fields: &Value) -> Value {
|
||||
let mut obj = form.as_object().cloned().unwrap_or_default();
|
||||
obj.insert("fields".into(), as_form_fields(fields));
|
||||
@@ -384,44 +452,82 @@ pub fn render(form: &Value, form_id: &str, data: Option<&Value>, errors: Option<
|
||||
.get("table")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let heading = form
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(form_id);
|
||||
let post_to = form
|
||||
.get("action_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("/_form/{form_id}"));
|
||||
let cancel = form
|
||||
.get("cancel_href")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("/");
|
||||
let row_id = form.get("id").map(cell_str).unwrap_or_default();
|
||||
|
||||
let mut body = String::from(
|
||||
r#"<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/>"#,
|
||||
);
|
||||
body.push_str(&format!("<title>form {id}</title>", id = esc(form_id)));
|
||||
body.push_str(&format!("<title>{}</title>", esc(heading)));
|
||||
body.push_str(
|
||||
r#"<style>
|
||||
body{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;background:#fafaf9;color:#1c1917}
|
||||
form{max-width:28rem;display:grid;gap:.85rem}
|
||||
label{display:grid;gap:.25rem;font-size:.9rem}
|
||||
input,textarea{padding:.5rem .6rem;border:1px solid #e7e5e4;border-radius:4px;font:inherit}
|
||||
input[readonly]{background:#f5f5f4;color:#57534e}
|
||||
.err{color:#b91c1c;font-size:.85rem}
|
||||
.actions{display:flex;gap:.75rem;align-items:center}
|
||||
.actions{display:flex;gap:.75rem;align-items:center;flex-wrap:wrap}
|
||||
button{background:#0f766e;color:#fff;border:0;padding:.55rem 1rem;border-radius:4px;cursor:pointer}
|
||||
a{color:#0f766e}
|
||||
.meta{color:#57534e;font-size:.9rem}
|
||||
</style></head><body>"#,
|
||||
);
|
||||
body.push_str(&format!(
|
||||
"<h1>{}</h1><p class=\"meta\">table=<code>{}</code> · action=<code>{}</code></p>",
|
||||
esc(form_id),
|
||||
esc(heading),
|
||||
esc(table),
|
||||
esc(action)
|
||||
));
|
||||
body.push_str(&format!(
|
||||
"<form method=\"post\" action=\"/_form/{}\">",
|
||||
esc(form_id)
|
||||
"<form method=\"post\" action=\"{}\">",
|
||||
esc(&post_to)
|
||||
));
|
||||
if action == "update" && !row_id.is_empty() {
|
||||
body.push_str(&format!(
|
||||
"<input type=\"hidden\" name=\"id\" value=\"{}\"/>",
|
||||
esc(&row_id)
|
||||
));
|
||||
}
|
||||
for f in &fields {
|
||||
let name = f.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let label = f.get("label").and_then(|v| v.as_str()).unwrap_or(name);
|
||||
let ty = f.get("type").and_then(|v| v.as_str()).unwrap_or("text");
|
||||
let required = f.get("required").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let default = f.get("default").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let pk = f.get("pk").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let value = if data.contains_key(name) {
|
||||
field_text(&data, name)
|
||||
} else if name == "id" && !row_id.is_empty() {
|
||||
row_id.clone()
|
||||
} else {
|
||||
default.to_string()
|
||||
};
|
||||
let readonly = action == "update" && pk && name == "id";
|
||||
if readonly {
|
||||
// already emitted as hidden; show read-only label
|
||||
body.push_str(&format!(
|
||||
"<label>{}<input type=\"text\" value=\"{}\" readonly/></label>",
|
||||
esc(label),
|
||||
esc(&value)
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let req_attr = if required { " required" } else { "" };
|
||||
body.push_str("<label>");
|
||||
body.push_str(&esc(label));
|
||||
@@ -460,15 +566,29 @@ a{color:#0f766e}
|
||||
}
|
||||
body.push_str("</label>");
|
||||
}
|
||||
body.push_str(
|
||||
"<div class=\"actions\"><button type=\"submit\">Submit</button><a href=\"/\">home</a></div>",
|
||||
);
|
||||
body.push_str(&format!(
|
||||
"<div class=\"actions\"><button type=\"submit\">Submit</button><a href=\"{}\">cancel</a></div>",
|
||||
esc(cancel)
|
||||
));
|
||||
body.push_str("</form></body></html>");
|
||||
body
|
||||
}
|
||||
|
||||
pub fn submit(form: &Value, data: &Value, db_url: &str) -> Result<Value, String> {
|
||||
let v = validate(form, None, data);
|
||||
let action = form
|
||||
.get("action")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("insert");
|
||||
let mut row_map = data_map(data);
|
||||
if action == "update" {
|
||||
if let Some(fid) = form.get("id").map(cell_str).filter(|s| !s.is_empty()) {
|
||||
if !row_map.contains_key("id") {
|
||||
row_map.insert("id".to_string(), json!(fid));
|
||||
}
|
||||
}
|
||||
}
|
||||
let data = Value::Object(row_map.clone());
|
||||
let v = validate(form, None, &data);
|
||||
if !v.get("ok").and_then(|x| x.as_bool()).unwrap_or(false) {
|
||||
return Ok(json!({
|
||||
"ok": false,
|
||||
@@ -479,17 +599,13 @@ pub fn submit(form: &Value, data: &Value, db_url: &str) -> Result<Value, String>
|
||||
.get("table")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "form missing `table`".to_string())?;
|
||||
let action = form
|
||||
.get("action")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("insert");
|
||||
let row = Value::Object(data_map(data));
|
||||
let row = Value::Object(row_map);
|
||||
let result = if action == "update" {
|
||||
let id = form
|
||||
.get("id")
|
||||
.map(cell_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.or_else(|| data_map(data).get("id").map(cell_str))
|
||||
.or_else(|| data_map(&data).get("id").map(cell_str))
|
||||
.ok_or_else(|| "update requires `id`".to_string())?;
|
||||
db::update(db_url, table, &id, &row)?
|
||||
} else {
|
||||
|
||||
+187
-37
@@ -1,4 +1,4 @@
|
||||
//! Blocking HTTP listen: page shell, `/_part/{id}`, `/_form/{id}`, optional `/admin`.
|
||||
//! Blocking HTTP listen: page shell, `/_part/{id}`, `/_form/{id}`, `/admin` CRUD.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
@@ -44,6 +44,12 @@ pub fn listen(
|
||||
.route("/_form/{id}", get(form_get).post(form_post))
|
||||
.route("/admin", get(admin_home))
|
||||
.route("/admin/{table}", get(admin_table))
|
||||
.route("/admin/{table}/new", get(admin_new_get).post(admin_new_post))
|
||||
.route(
|
||||
"/admin/{table}/{id}/edit",
|
||||
get(admin_edit_get).post(admin_edit_post),
|
||||
)
|
||||
.route("/admin/{table}/{id}/delete", get(admin_delete))
|
||||
.with_state(state);
|
||||
|
||||
let addr: SocketAddr = format!("{host}:{port}")
|
||||
@@ -97,11 +103,24 @@ async fn form_post(
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
submit_and_respond(frm, &id, url, posted)
|
||||
}
|
||||
|
||||
fn posted_to_value(posted: HashMap<String, String>) -> Value {
|
||||
let mut data = Map::new();
|
||||
for (k, v) in posted {
|
||||
data.insert(k, json!(v));
|
||||
}
|
||||
let data_v = Value::Object(data);
|
||||
Value::Object(data)
|
||||
}
|
||||
|
||||
fn submit_and_respond(
|
||||
frm: &Value,
|
||||
form_id: &str,
|
||||
url: &str,
|
||||
posted: HashMap<String, String>,
|
||||
) -> Response {
|
||||
let data_v = posted_to_value(posted);
|
||||
match form::submit(frm, &data_v, url) {
|
||||
Ok(res) if res.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) => {
|
||||
let redirect = res
|
||||
@@ -112,44 +131,65 @@ async fn form_post(
|
||||
}
|
||||
Ok(res) => {
|
||||
let errors = res.get("errors");
|
||||
Html(form::render(frm, &id, Some(&data_v), errors)).into_response()
|
||||
Html(form::render(frm, form_id, Some(&data_v), errors)).into_response()
|
||||
}
|
||||
Err(e) => Html(format!("<p>submit error: {}</p>", esc(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_home(State(st): State<Arc<AppState>>) -> Response {
|
||||
fn admin_gate(st: &AppState) -> Option<Response> {
|
||||
if !st.admin {
|
||||
return Html(String::from("<p>admin disabled</p>")).into_response();
|
||||
return Some(Html(String::from("<p>admin disabled</p>")).into_response());
|
||||
}
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
if st.db_url.is_none() {
|
||||
return Some(Html(String::from("<p>no database</p>")).into_response());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn admin_shell(title: &str, inner: &str) -> String {
|
||||
format!(
|
||||
r#"<!DOCTYPE html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>{title}</title>
|
||||
<style>
|
||||
body{{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;background:#fafaf9;color:#1c1917}}
|
||||
a{{color:#0f766e;text-decoration:none}} a:hover{{text-decoration:underline}}
|
||||
table{{border-collapse:collapse;background:#fff}} th,td{{border:1px solid #e7e5e4;padding:.45rem .65rem;text-align:left}}
|
||||
.toolbar{{display:flex;gap:1rem;align-items:center;margin:.75rem 0 1.25rem;flex-wrap:wrap}}
|
||||
.btn{{display:inline-block;background:#0f766e;color:#fff!important;padding:.4rem .75rem;border-radius:4px}}
|
||||
.btn-muted{{background:#78716c}}
|
||||
.danger{{color:#b91c1c}}
|
||||
</style></head><body>{inner}</body></html>"#,
|
||||
title = esc(title),
|
||||
inner = inner
|
||||
)
|
||||
}
|
||||
|
||||
async fn admin_home(State(st): State<Arc<AppState>>) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
let tables = db::list_tables(url).unwrap_or_default();
|
||||
let mut body = String::from(
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><title>admin</title></head><body>",
|
||||
);
|
||||
body.push_str("<h1>admin</h1><ul>");
|
||||
let mut inner = String::from("<h1>admin</h1><div class=\"toolbar\"><a href=\"/\">home</a></div><h2>tables</h2><ul>");
|
||||
for t in &tables {
|
||||
body.push_str(&format!("<li><a href=\"/admin/{t}\">{t}</a></li>"));
|
||||
inner.push_str(&format!("<li><a href=\"/admin/{t}\">{t}</a></li>"));
|
||||
}
|
||||
inner.push_str("</ul>");
|
||||
if !st.forms.is_empty() {
|
||||
body.push_str("</ul><h2>forms</h2><ul>");
|
||||
inner.push_str("<h2>mounted forms</h2><ul>");
|
||||
for id in st.forms.keys() {
|
||||
body.push_str(&format!("<li><a href=\"/_form/{id}\">{id}</a></li>"));
|
||||
inner.push_str(&format!("<li><a href=\"/_form/{id}\">{id}</a></li>"));
|
||||
}
|
||||
inner.push_str("</ul>");
|
||||
}
|
||||
body.push_str("</ul><p><a href=\"/\">home</a></p></body></html>");
|
||||
Html(body).into_response()
|
||||
Html(admin_shell("admin", &inner)).into_response()
|
||||
}
|
||||
|
||||
async fn admin_table(State(st): State<Arc<AppState>>, Path(table): Path<String>) -> Response {
|
||||
if !st.admin {
|
||||
return Redirect::to("/").into_response();
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
let Ok(data) = db::select(url, &table, 200) else {
|
||||
return Html(format!("<p>cannot read {table}</p>")).into_response();
|
||||
};
|
||||
@@ -158,24 +198,34 @@ async fn admin_table(State(st): State<Arc<AppState>>, Path(table): Path<String>)
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut body = format!(
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><title>{table}</title></head><body>"
|
||||
);
|
||||
body.push_str(&format!(
|
||||
"<h1>{table}</h1><p><a href=\"/admin\">back</a></p><table border=\"1\" cellpadding=\"6\"><thead><tr>"
|
||||
));
|
||||
let cols: Vec<String> = rows
|
||||
let mut cols: Vec<String> = rows
|
||||
.first()
|
||||
.and_then(|r| r.as_object())
|
||||
.map(|m| m.keys().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
for c in &cols {
|
||||
body.push_str(&format!("<th>{c}</th>"));
|
||||
if cols.is_empty() {
|
||||
if let Ok(info) = db::table_info(url, &table) {
|
||||
cols = info.into_iter().map(|c| c.name).collect();
|
||||
}
|
||||
}
|
||||
body.push_str("</tr></thead><tbody>");
|
||||
// prefer id first
|
||||
if let Some(i) = cols.iter().position(|c| c == "id") {
|
||||
let idc = cols.remove(i);
|
||||
cols.insert(0, idc);
|
||||
}
|
||||
|
||||
let mut inner = format!("<h1>{table}</h1>");
|
||||
inner.push_str(&format!(
|
||||
"<div class=\"toolbar\"><a class=\"btn\" href=\"/admin/{table}/new\">New</a><a href=\"/admin\">back</a><a href=\"/\">home</a></div>"
|
||||
));
|
||||
inner.push_str("<table><thead><tr>");
|
||||
for c in &cols {
|
||||
inner.push_str(&format!("<th>{}</th>", esc(c)));
|
||||
}
|
||||
inner.push_str("<th></th></tr></thead><tbody>");
|
||||
for row in &rows {
|
||||
body.push_str("<tr>");
|
||||
let m = row.as_object().cloned().unwrap_or_else(Map::new);
|
||||
inner.push_str("<tr>");
|
||||
for c in &cols {
|
||||
let cell = m
|
||||
.get(c)
|
||||
@@ -185,12 +235,112 @@ async fn admin_table(State(st): State<Arc<AppState>>, Path(table): Path<String>)
|
||||
other => other.to_string(),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
body.push_str(&format!("<td>{}</td>", esc(&cell)));
|
||||
inner.push_str(&format!("<td>{}</td>", esc(&cell)));
|
||||
}
|
||||
body.push_str("</tr>");
|
||||
let id = m
|
||||
.get("id")
|
||||
.map(|v| match v {
|
||||
Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !id.is_empty() {
|
||||
inner.push_str(&format!(
|
||||
"<td><a href=\"/admin/{table}/{id}/edit\">edit</a> · <a class=\"danger\" href=\"/admin/{table}/{id}/delete\" onclick=\"return confirm('Delete #{id}?')\">delete</a></td>"
|
||||
));
|
||||
} else {
|
||||
inner.push_str("<td></td>");
|
||||
}
|
||||
inner.push_str("</tr>");
|
||||
}
|
||||
body.push_str("</tbody></table></body></html>");
|
||||
Html(body).into_response()
|
||||
if rows.is_empty() {
|
||||
inner.push_str("<tr><td colspan=\"99\">(empty)</td></tr>");
|
||||
}
|
||||
inner.push_str("</tbody></table>");
|
||||
Html(admin_shell(&table, &inner)).into_response()
|
||||
}
|
||||
|
||||
async fn admin_new_get(State(st): State<Arc<AppState>>, Path(table): Path<String>) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
match form::from_schema(url, &table, "insert", None) {
|
||||
Ok(frm) => Html(form::render(&frm, &format!("admin-{table}-new"), None, None))
|
||||
.into_response(),
|
||||
Err(e) => Html(format!("<p>{}</p>", esc(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_new_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Path(table): Path<String>,
|
||||
Form(posted): Form<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
match form::from_schema(url, &table, "insert", None) {
|
||||
Ok(frm) => submit_and_respond(&frm, &format!("admin-{table}-new"), url, posted),
|
||||
Err(e) => Html(format!("<p>{}</p>", esc(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_edit_get(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Path((table, id)): Path<(String, String)>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
let row = match db::get(url, &table, &id) {
|
||||
Ok(Value::Null) => {
|
||||
return Html(format!("<p>row {id} not found</p>")).into_response();
|
||||
}
|
||||
Ok(v) => v,
|
||||
Err(e) => return Html(format!("<p>{}</p>", esc(&e))).into_response(),
|
||||
};
|
||||
match form::from_schema(url, &table, "update", Some(&id)) {
|
||||
Ok(frm) => Html(form::render(
|
||||
&frm,
|
||||
&format!("admin-{table}-edit"),
|
||||
Some(&row),
|
||||
None,
|
||||
))
|
||||
.into_response(),
|
||||
Err(e) => Html(format!("<p>{}</p>", esc(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_edit_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Path((table, id)): Path<(String, String)>,
|
||||
Form(posted): Form<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
match form::from_schema(url, &table, "update", Some(&id)) {
|
||||
Ok(frm) => submit_and_respond(&frm, &format!("admin-{table}-edit"), url, posted),
|
||||
Err(e) => Html(format!("<p>{}</p>", esc(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_delete(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Path((table, id)): Path<(String, String)>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
if let Err(e) = db::delete(url, &table, &id) {
|
||||
return Html(format!("<p>delete failed: {}</p>", esc(&e))).into_response();
|
||||
}
|
||||
Redirect::to(&format!("/admin/{table}")).into_response()
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
|
||||
@@ -411,6 +411,35 @@ web_ffi!(web_form_submit, |args: &Value| {
|
||||
form::submit(&form_v, &data, &url)
|
||||
});
|
||||
|
||||
web_ffi!(web_form_from_schema, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let action = arg_str_opt(args, "action").unwrap_or("insert");
|
||||
let id = match args.get("id") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(arg_text(args, "id")?),
|
||||
};
|
||||
form::from_schema(&url, &table, action, id.as_deref())
|
||||
});
|
||||
|
||||
web_ffi!(web_db_table_info, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let cols = db::table_info(&url, &table)?;
|
||||
let arr: Vec<Value> = cols
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
json!({
|
||||
"name": c.name,
|
||||
"type": c.sql_type,
|
||||
"notnull": c.notnull,
|
||||
"pk": c.pk,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "columns": arr }))
|
||||
});
|
||||
|
||||
web_ffi!(web_listen, |args: &Value| {
|
||||
use std::collections::HashMap;
|
||||
let (page, db_url, host, port, admin, forms) = if args.get("page").is_some()
|
||||
@@ -532,6 +561,12 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
),
|
||||
("web_form_render", "form,id", web_form_render as PluginFn),
|
||||
("web_form_submit", "form,data,url", web_form_submit as PluginFn),
|
||||
(
|
||||
"web_form_from_schema",
|
||||
"url,table,action",
|
||||
web_form_from_schema as PluginFn,
|
||||
),
|
||||
("web_db_table_info", "url,table", web_db_table_info as PluginFn),
|
||||
("web_listen", "app", web_listen as PluginFn),
|
||||
];
|
||||
for (name, params, f) in regs {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
title: web admin form-from-schema smoke
|
||||
description: Schema-derived admin forms share validate/submit (offline).
|
||||
> ext/web/web.mq.md
|
||||
> web-fixtures/db/articles.mq.md as articles
|
||||
> lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`store` = > web.db url="sqlite:web-fixtures/data/admin-smoke.db" *
|
||||
*`schema` = > articles.schema *
|
||||
> `store`.init name=articles fields=`schema`
|
||||
*`url` = > json.get value=`store` key=url *
|
||||
|
||||
*`info` = > web_db_table_info url=`url` table=articles *
|
||||
*`cols` = > json.get value=`info` key=columns *
|
||||
*`n` = > len value=`cols` *
|
||||
1. `n` >= 2
|
||||
> print text=schema-ok
|
||||
2. *
|
||||
> print text=schema-fail
|
||||
|
||||
*`fnew` = > web_form_from_schema url=`url` table=articles action=insert *
|
||||
*`fields` = > json.get value=`fnew` key=fields *
|
||||
*`nf` = > len value=`fields` *
|
||||
1. `nf` >= 1
|
||||
> print text=new-form-ok
|
||||
2. *
|
||||
> print text=new-form-fail
|
||||
|
||||
`row` =
|
||||
|
||||
| title | body |
|
||||
|-------|------|
|
||||
| Admin create | via schema form |
|
||||
|
||||
*`sub` = > web_form_submit form=`fnew` data=`row` url=`url` *
|
||||
*`sok` = > json.get value=`sub` key=ok *
|
||||
1. `sok`
|
||||
> print text=insert-ok
|
||||
2. *
|
||||
> print text=insert-fail
|
||||
|
||||
*`got` = > `store`.get table=articles id=1 *
|
||||
*`title` = > json.get value=`got` key=title *
|
||||
1. `title` == "Admin create"
|
||||
> print text=get-ok
|
||||
2. *
|
||||
> print text=get-fail
|
||||
|
||||
*`fedit` = > web_form_from_schema url=`url` table=articles action=update id=1 *
|
||||
`patch` =
|
||||
|
||||
| title | body |
|
||||
|-------|------|
|
||||
| Admin edited | body updated |
|
||||
|
||||
*`up` = > web_form_submit form=`fedit` data=`patch` url=`url` *
|
||||
*`uok` = > json.get value=`up` key=ok *
|
||||
1. `uok`
|
||||
> print text=update-ok
|
||||
2. *
|
||||
> print text=update-fail
|
||||
|
||||
*`got2` = > `store`.get table=articles id=1 *
|
||||
*`title2` = > json.get value=`got2` key=title *
|
||||
1. `title2` == "Admin edited"
|
||||
> print text=edit-ok
|
||||
2. *
|
||||
> print text=edit-fail
|
||||
|
||||
`empty` =
|
||||
|
||||
| title | body |
|
||||
|-------|------|
|
||||
| | |
|
||||
|
||||
*`bad` = > web_form_submit form=`fnew` data=`empty` url=`url` *
|
||||
*`bok` = > json.get value=`bad` key=ok *
|
||||
1. `bok`
|
||||
> print text=required-should-fail
|
||||
2. *
|
||||
> print text=required-ok
|
||||
@@ -1258,6 +1258,26 @@ render-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_admin_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "-p", "marqdo_plugin_web"])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.status()
|
||||
.expect("build web plugin");
|
||||
assert!(status.success(), "failed to build marqdo_plugin_web");
|
||||
assert_out(
|
||||
"tests/ext/web-admin-smoke.mq.md",
|
||||
"schema-ok
|
||||
new-form-ok
|
||||
insert-ok
|
||||
get-ok
|
||||
update-ok
|
||||
edit-ok
|
||||
required-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_agent_framework_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
|
||||
Reference in new issue
Block a user