Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,65 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn provider_verify_restricts_the_entire_call_graph_to_global_reads() {
|
||||
let root = project(
|
||||
"verify-global-contract",
|
||||
r#"
|
||||
type Identity { id: Text, user_id: demo.user.data.id?, tenant_id: data.id? }
|
||||
flow lookup(session: Text) (out: data.Article?)
|
||||
| step | kind | do |
|
||||
| out | data | data.first(title == session) |
|
||||
flow verify(claims: dever.auth.Claims) (identity: Identity)
|
||||
| step | kind | do |
|
||||
| session | flow | lookup(claims.session) |
|
||||
| - | check | session != null else Unauthorized |
|
||||
| identity | calc | Identity {id = claims.subject, user_id = null, tenant_id = null} |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
write_source(&model, "global type Article {title:Text}").unwrap();
|
||||
analyze(&root);
|
||||
write_source(&model, "type Article {title:Text}").unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("tenant Model"), "{error:?}");
|
||||
write_source(&model, "global type Article {title:Text}").unwrap();
|
||||
for operation in [
|
||||
"| - | data | data.create({title = claims.subject}) |",
|
||||
"| - | flow | dever.time.sleep(1) |",
|
||||
"| - | flow | dever.io.println(claims.subject) |",
|
||||
] {
|
||||
let app = format!(
|
||||
"type Identity {{ id: Text, user_id: demo.user.data.id?, tenant_id: data.id? }}\nflow verify(claims: dever.auth.Claims) (identity: Identity)\n| step | kind | do |\n{operation}\n| identity | calc | Identity {{id=claims.subject,user_id=null,tenant_id=null}} |\n"
|
||||
);
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C014", "{operation}: {error:?}");
|
||||
assert!(error.message.contains("Provider verify"), "{error:?}");
|
||||
}
|
||||
for identity in [
|
||||
"type Identity {id:Text,user_id:Int?,tenant_id:Int?}",
|
||||
"type Identity {id:Text,user_id:demo.user.data.id?,tenant_id:data.id?,extra:Text?}",
|
||||
"type Identity {private id:Text,user_id:demo.user.data.id?,tenant_id:data.id?}",
|
||||
] {
|
||||
let app = format!(
|
||||
"{identity}\nflow verify(claims: dever.auth.Claims) (identity: Identity)\n| step | kind | do |\n| identity | calc | Identity {{id=claims.subject,user_id=null,tenant_id=null{} }} |\n",
|
||||
if identity.contains("extra") {
|
||||
",extra=null"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{identity}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn named_databases_keep_schemas_separate_and_reject_cross_database_transactions() {
|
||||
let root = project(
|
||||
"model-bindings-native",
|
||||
r#"
|
||||
flow save(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({title = title}) |
|
||||
transaction flow article(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(title) |
|
||||
flow both(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(title) |
|
||||
| - | flow | demo.user.app.save(title) |
|
||||
flow stages(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | article(title) |
|
||||
| - | flow | demo.user.app.transactional(title) |
|
||||
flow link(user_id: demo.user.data.id) (out: data.Article) {
|
||||
out = data.create({title = "linked", author_id = user_id})
|
||||
}
|
||||
flow linked(user_id: demo.user.data.id) (out: data.Article) {
|
||||
out = data.get(author_id == user_id)
|
||||
}
|
||||
flow counts() (articles: Int, users: Int)
|
||||
| step | kind | do |
|
||||
| articles | data | data.count() |
|
||||
| users | flow | demo.user.app.count() |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, author_id: demo.user.data.id? external }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"database archive\nglobal type User { name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/app/main.dever"),
|
||||
r#"
|
||||
flow save(name: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({name = name}) |
|
||||
transaction flow transactional(name: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(name) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd both = app.both\nlong cmd stages = app.stages\ncmd counts = app.counts\ncmd link = app.link\ncmd linked = app.linked",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(&config,r#"{"database":{"default":{"type":"sqlite","path":"data/main.db"},"archive":{"type":"sqlite","path":"data/archive.db"}}}"#).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let user = program
|
||||
.definitions
|
||||
.iter()
|
||||
.find(|d| d.name == "demo.user.data.User")
|
||||
.unwrap();
|
||||
assert!(user.model.as_ref().unwrap().global);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(
|
||||
!call("both", r#"{"title":"must roll back"}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let counts: serde_json::Value = serde_json::from_str(&success(call("counts", "{}"))).unwrap();
|
||||
assert_eq!(counts["data"], serde_json::json!({"articles":0,"users":0}));
|
||||
success(call("stages", r#"{"title":"committed stages"}"#));
|
||||
let counts: serde_json::Value = serde_json::from_str(&success(call("counts", "{}"))).unwrap();
|
||||
assert_eq!(counts["data"], serde_json::json!({"articles":1,"users":1}));
|
||||
let user = r#"{"user_id":1}"#;
|
||||
let saved: serde_json::Value = serde_json::from_str(&success(call("link", user))).unwrap();
|
||||
let found: serde_json::Value = serde_json::from_str(&success(call("linked", user))).unwrap();
|
||||
assert_eq!(saved["data"]["author_id"], 1);
|
||||
assert_eq!(found["data"], saved["data"]);
|
||||
// 读取本测试生成的两个真实文件,确认各库没有另一库的业务表。
|
||||
for (file, expected, absent) in [
|
||||
("main.db", "demo_article", "demo_user"),
|
||||
("archive.db", "demo_user", "demo_article"),
|
||||
] {
|
||||
let path = root.join("data").join(file);
|
||||
let db = dever_runtime::database::Database::sqlite(
|
||||
&path,
|
||||
false,
|
||||
dever_runtime::database::Options {
|
||||
max_page_size: 100,
|
||||
max_connections: 1,
|
||||
wait_timeout: std::time::Duration::from_secs(5),
|
||||
io_timeout: std::time::Duration::from_secs(30),
|
||||
},
|
||||
None,
|
||||
);
|
||||
let path_check = dever_runtime::task::run(true, 8, async |scope| {
|
||||
let mut executor = db.await.unwrap().acquire().await.unwrap();
|
||||
executor
|
||||
.query(
|
||||
scope,
|
||||
"SELECT name FROM sqlite_schema WHERE type='table'".into(),
|
||||
vec![],
|
||||
|row| row.get::<String>(0),
|
||||
)
|
||||
.await
|
||||
})
|
||||
.unwrap();
|
||||
let names = path_check.unwrap();
|
||||
assert!(names.iter().any(|n| n == expected));
|
||||
assert!(!names.iter().any(|n| n == absent));
|
||||
}
|
||||
fs::rename(
|
||||
root.join("data/archive.db"),
|
||||
root.join("data/archive.saved.db"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!call("counts", "{}").status.success());
|
||||
assert!(!root.join("data/archive.db").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_table_names_are_unique_per_database_binding() {
|
||||
let root = directory("physical-table-collision");
|
||||
let first = "module/sales/item_log/data/item_log.dv";
|
||||
let second = "module/sales_item/log/data/log.dv";
|
||||
write_source(root.join(first), "type ItemLog { title: Text }").unwrap();
|
||||
write_source(root.join(second), "type Log { title: Text }").unwrap();
|
||||
let check = || cli(&["check", root.to_str().unwrap()]);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = check();
|
||||
let error = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
!output.status.success()
|
||||
&& error.contains("duplicate physical table sales_item_log in database default"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(error.contains(first) && error.contains(second), "{error}");
|
||||
write_source(
|
||||
root.join(second),
|
||||
"database archive\ntype Log { title: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(check());
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn migration_data_steps_bind_parameters_and_rollback_with_schema_changes() {
|
||||
let root = project(
|
||||
"model-data-migration",
|
||||
"flow get(article_id: data.id) (out: data.Article)\n| step | kind | do |\n| out | data | data.get(article_id) |\n",
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
write_source(&model, "type Article { title: Text unique, obsolete: Text default \"old\" }\nseed { {title = \"initial\"} }").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let read = |binary: &Path| {
|
||||
let out = success(
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(["demo.article.get", r#"{"article_id":1}"#])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
serde_json::from_str::<serde_json::Value>(&out).unwrap()["data"].clone()
|
||||
};
|
||||
let original = build();
|
||||
success(migrate(&original.binary));
|
||||
let initial = read(&original.binary);
|
||||
let old_binary = root.join("original");
|
||||
fs::copy(&original.binary, &old_binary).unwrap();
|
||||
drop(original);
|
||||
let migration = r#"
|
||||
type Article { title: Text unique, copies: Int default 0 }
|
||||
migrate rewrite {
|
||||
before {
|
||||
sqlite = "UPDATE demo_article SET title = title || ?1 WHERE obsolete = ?2"
|
||||
postgres = "UPDATE demo_article SET title = title || $1 WHERE obsolete = $2"
|
||||
parameters = ["'; -- _dever_history", "old"]
|
||||
}
|
||||
drop obsolete
|
||||
after {
|
||||
sqlite = "UPDATE demo_article SET copies = copies + ?1"
|
||||
postgres = "UPDATE demo_article SET copies = copies + $1"
|
||||
parameters = [2]
|
||||
}
|
||||
}
|
||||
"#;
|
||||
// after 失败时,before 的数据改写和删列都必须回滚。
|
||||
write_source(
|
||||
&model,
|
||||
migration.replace("copies = copies + ?1", "missing = ?1"),
|
||||
)
|
||||
.unwrap();
|
||||
let failed = build();
|
||||
assert!(!migrate(&failed.binary).status.success());
|
||||
assert_eq!(read(&old_binary), initial);
|
||||
drop(failed);
|
||||
write_source(&model, migration).unwrap();
|
||||
let valid = build();
|
||||
success(migrate(&valid.binary));
|
||||
success(migrate(&valid.binary));
|
||||
let updated = read(&valid.binary);
|
||||
assert_eq!(updated["title"], "initial'; -- _dever_history");
|
||||
assert_eq!(updated["copies"], 2);
|
||||
assert!(updated.get("obsolete").is_none());
|
||||
assert_eq!(updated["id"], initial["id"]);
|
||||
assert_eq!(updated["created_at"], initial["created_at"]);
|
||||
let valid_binary = root.join("valid");
|
||||
fs::copy(&valid.binary, &valid_binary).unwrap();
|
||||
drop(valid);
|
||||
// 已执行参数也是历史内容;改写必须失败,不能重跑迁移。
|
||||
write_source(
|
||||
&model,
|
||||
migration.replace("parameters = [2]", "parameters = [3]"),
|
||||
)
|
||||
.unwrap();
|
||||
let changed = build();
|
||||
let failed = migrate(&changed.binary);
|
||||
assert!(!failed.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&failed.stderr)
|
||||
.contains("applied migration content or order changed")
|
||||
);
|
||||
assert_eq!(read(&valid_binary), updated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_sql_uses_library_parsing_and_rejects_invalid_boundaries() {
|
||||
let root = project("model-data-sql-check", "");
|
||||
let path = root.join("module/demo/article/data/main.dever");
|
||||
let source = |sqlite: &str, postgres: &str, parameters: &str| {
|
||||
format!(
|
||||
"type Article {{ title: Text }}\nmigrate rewrite {{ after {{ sqlite = {}, postgres = {}, parameters = {parameters} }} }}",
|
||||
serde_json::to_string(sqlite).unwrap(),
|
||||
serde_json::to_string(postgres).unwrap()
|
||||
)
|
||||
};
|
||||
for (sqlite, postgres, parameters) in [
|
||||
(
|
||||
"UPDATE demo_article SET title=?1 /* ; ?2 */",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"ok\"]",
|
||||
),
|
||||
(
|
||||
"INSERT INTO demo_article (created_at,title) VALUES (?1,?2)",
|
||||
"INSERT INTO demo_article (created_at,title) VALUES ($1,$2)",
|
||||
"[-1,\"text\"]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article WHERE title='?1'",
|
||||
"DELETE FROM demo_article WHERE title=$$$_dever_history$$",
|
||||
"[]",
|
||||
),
|
||||
] {
|
||||
write_source(&path, source(sqlite, postgres, parameters)).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
program::check(&loaded.declarations, &loaded.modules).unwrap();
|
||||
let formatted = dever::compiler::format::definitions(
|
||||
loaded
|
||||
.declarations
|
||||
.iter()
|
||||
.filter(|d| loaded.modules[d.span().source].domain == "article"),
|
||||
);
|
||||
write_source(&path, &formatted).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
assert_eq!(
|
||||
formatted,
|
||||
dever::compiler::format::definitions(
|
||||
loaded
|
||||
.declarations
|
||||
.iter()
|
||||
.filter(|d| loaded.modules[d.span().source].domain == "article")
|
||||
)
|
||||
);
|
||||
}
|
||||
for (sqlite, postgres, parameters) in [
|
||||
(
|
||||
"UPDATE demo_article SET title=?2",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=?1",
|
||||
"UPDATE demo_article SET title=$2",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=?1",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\",2]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=?",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=:name",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title='x'; DELETE FROM demo_article",
|
||||
"DELETE FROM demo_article",
|
||||
"[]",
|
||||
),
|
||||
("UPDATE demo_article SET", "DELETE FROM demo_article", "[]"),
|
||||
("DROP TABLE demo_article", "DELETE FROM demo_article", "[]"),
|
||||
(
|
||||
"UPDATE \"_dever_history\" SET name='x'",
|
||||
"DELETE FROM demo_article",
|
||||
"[]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=(SELECT name FROM sqlite_schema LIMIT 1)",
|
||||
"DELETE FROM demo_article",
|
||||
"[]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article",
|
||||
"DELETE FROM pg_catalog.pg_class",
|
||||
"[]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[1.2]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[1e999]",
|
||||
),
|
||||
] {
|
||||
write_source(&path, source(sqlite, postgres, parameters)).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{sqlite} / {postgres} / {parameters}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn seeds_insert_missing_keys_without_overwriting_live_records() {
|
||||
let root = project(
|
||||
"model-seed-native",
|
||||
r#"
|
||||
type Entry {code:Text, amount:Decimal, title:Text, token:Uuid}
|
||||
loop entries(rows:List<data.Article>) (out:List<Entry>)
|
||||
| each row in rows | result |
|
||||
| out | list Entry {code=row.code,amount=row.amount,title=row.title,token=row.token} |
|
||||
flow all() (total:Int, items:List<Entry>)
|
||||
| step | kind | do |
|
||||
| page | data | data.page(order = id.asc) |
|
||||
| total | calc | page.total |
|
||||
| items | loop | entries(page.items) |
|
||||
flow change(article_id: data.id, title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.update(article_id, {title = title}) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"type User { name: Text unique }\nseed { {name = \"作者\"} }",
|
||||
)
|
||||
.unwrap();
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
let base = "type Article { user_id: demo.user.data.id, code: Text lower, title: Text(1,30), token: Uuid generated, amount: Decimal(8,2) default 0.50 }\nunique(user_id,code)\n";
|
||||
write_source(
|
||||
&model,
|
||||
format!("{base}seed {{ {{user_id = 1, code = \" FIRST \", title = \"first\"}} }}"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd all = app.all\ncmd change = app.change",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
success(
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let call = |binary: &Path, name: &str, input: &str| {
|
||||
success(
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let page = |binary: &Path| {
|
||||
serde_json::from_str::<serde_json::Value>(&call(binary, "demo.article.all", "{}")).unwrap()
|
||||
["data"]
|
||||
.clone()
|
||||
};
|
||||
let artifact = build();
|
||||
migrate(&artifact.binary);
|
||||
let first = page(&artifact.binary);
|
||||
assert_eq!(first["total"], 1);
|
||||
assert_eq!(first["items"][0]["code"], "first");
|
||||
assert_eq!(first["items"][0]["amount"], "0.5");
|
||||
call(
|
||||
&artifact.binary,
|
||||
"demo.article.change",
|
||||
r#"{"article_id":1,"title":"edited"}"#,
|
||||
);
|
||||
migrate(&artifact.binary);
|
||||
assert_eq!(page(&artifact.binary)["items"][0]["title"], "edited");
|
||||
drop(artifact);
|
||||
write_source(&model, format!("{base}seed {{ {{user_id = 1, code = \"FIRST\", title = \"must not replace\"}}\n{{user_id = 1,code = \"second\",title = \"new\",amount = 12.50}} }}")).unwrap();
|
||||
let artifact = build();
|
||||
migrate(&artifact.binary);
|
||||
migrate(&artifact.binary);
|
||||
let after = page(&artifact.binary);
|
||||
assert_eq!(after["total"], 2);
|
||||
assert_eq!(after["items"][0]["title"], "edited");
|
||||
assert_eq!(after["items"][0]["token"], first["items"][0]["token"]);
|
||||
assert_eq!(after["items"][1]["amount"], "12.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_rename_addition_and_failed_migration_preserve_real_data() {
|
||||
let root = project(
|
||||
"model-migration-native",
|
||||
r#"
|
||||
flow create(title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = title}) |
|
||||
flow get(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.get(article_id) |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
write_source(&model, "type Article { title: Text(2,20) }").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd create = app.create\ncmd get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let call = |binary: &Path, name: &str, input: &str| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
// NUL 也按 Unicode 码点计算,不能使用 SQLite 内建 length 的截断语义。
|
||||
let original: serde_json::Value = serde_json::from_str(&success(call(
|
||||
&artifact.binary,
|
||||
"demo.article.create",
|
||||
r#"{"title":"文\u0000章"}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
drop(artifact);
|
||||
write_source(root.join("module/demo/article/app/main.dever"), "flow get(article_id: data.id) (out: data.Article)\n| step | kind | do |\n| out | data | data.get(article_id) |").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
let renamed = "type Article { heading: Text(2,20) from title, token: Uuid generated unique, amount: Decimal(8,2) default 12.50, label: Text lower default \" NEWS \", note: Text(1,10)? }";
|
||||
write_source(&model, renamed).unwrap();
|
||||
let artifact = build();
|
||||
assert!(
|
||||
!call(&artifact.binary, "demo.article.get", r#"{"article_id":1}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let read = |binary: &Path| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(
|
||||
binary,
|
||||
"demo.article.get",
|
||||
r#"{"article_id":1}"#,
|
||||
)))
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let after = read(&artifact.binary);
|
||||
assert_eq!(after["id"], original["data"]["id"]);
|
||||
assert_eq!(after["created_at"], original["data"]["created_at"]);
|
||||
assert_eq!(after["heading"], original["data"]["title"]);
|
||||
assert_eq!(after["label"], "news");
|
||||
assert_eq!(after["amount"], "12.5");
|
||||
assert!(after["note"].is_null());
|
||||
assert_eq!(after["token"].as_str().unwrap().chars().nth(14), Some('7'));
|
||||
let valid_binary = root.join("renamed");
|
||||
fs::copy(&artifact.binary, &valid_binary).unwrap();
|
||||
drop(artifact);
|
||||
for invalid in [
|
||||
renamed.replace("Text(2,20)", "Text(1,2)"),
|
||||
renamed.replace("heading: Text(2,20) from title, ", ""),
|
||||
renamed.replace(
|
||||
"Decimal(8,2) default 12.50",
|
||||
"Decimal(8,2) <= 10 default 1.00",
|
||||
),
|
||||
] {
|
||||
write_source(&model, invalid).unwrap();
|
||||
let artifact = build();
|
||||
assert!(!migrate(&artifact.binary).status.success());
|
||||
assert_eq!(read(&valid_binary), after);
|
||||
}
|
||||
write_source(
|
||||
&model,
|
||||
renamed.replace(
|
||||
"Decimal(8,2) default 12.50",
|
||||
"Decimal(8,2) > 12.491 and < 12.509 default 12.50",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
assert_eq!(read(&artifact.binary), after);
|
||||
drop(artifact);
|
||||
let dropped = format!(
|
||||
"{}\nmigrate remove_heading {{ drop heading }}",
|
||||
renamed.replace("heading: Text(2,20) from title, ", "")
|
||||
);
|
||||
write_source(&model, &dropped).unwrap();
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let mut expected = after.clone();
|
||||
expected.as_object_mut().unwrap().remove("heading");
|
||||
assert_eq!(read(&artifact.binary), expected);
|
||||
drop(artifact);
|
||||
write_source(
|
||||
&model,
|
||||
dropped.replace("drop heading", "drop different_column"),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
let failure = migrate(&artifact.binary);
|
||||
assert!(!failure.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&failure.stderr)
|
||||
.contains("applied migration content or order changed")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
use super::*;
|
||||
mod data_migration;
|
||||
mod migration;
|
||||
|
||||
#[test]
|
||||
fn composite_upsert_and_foreign_keys_execute_in_the_database() {
|
||||
let root = project(
|
||||
"model-index-native",
|
||||
r#"
|
||||
flow save(user_id: demo.user.data.id, category: Text?, title: Text) (id: data.id, author: demo.user.data.id, saved_title: Text)
|
||||
| step | kind | do |
|
||||
| row | data | data.upsert({category = category, user_id = user_id}, {title = title}, {title = title}) |
|
||||
| id | calc | row.id |
|
||||
| author | calc | row.user_id |
|
||||
| saved_title | calc | row.title |
|
||||
flow create(user_id: demo.user.data.id, category: Text?, title: Text) (id: data.id)
|
||||
| step | kind | do |
|
||||
| row | data | data.create({user_id = user_id, category = category, title = title}) |
|
||||
| id | calc | row.id |
|
||||
flow remove(article_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(article_id) |
|
||||
flow defaultUser() (id: data.id, user_id: demo.user.data.id)
|
||||
| step | kind | do |
|
||||
| row | data | data.create({title = "default user"}) |
|
||||
| id | calc | row.id |
|
||||
| user_id | calc | row.user_id |
|
||||
"#,
|
||||
);
|
||||
write_source(root.join("module/demo/article/data/main.dever"), "type Article { user_id: demo.user.data.id default 1, category: Text?, title: Text, parent_id: data.id? }\nunique(user_id, category)\nindex(title, created_at)").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd save = app.save\ncmd create = app.create\ncmd remove = app.remove\ncmd defaultUser = app.defaultUser",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/app/main.dever"),
|
||||
r#"
|
||||
flow create(name: Text) (out: data.User)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({name = name}) |
|
||||
flow remove(user_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(user_id) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/user/api.dever"),
|
||||
"cmd create = app.create\ncmd remove = app.remove",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let formatted = dever::compiler::format::format(
|
||||
&loaded
|
||||
.declarations
|
||||
.iter()
|
||||
.filter(|d| matches!(d, dever::syntax::ast::Declaration::Index { .. }))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
assert!(formatted.contains("unique(user_id, category)"));
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let data = |name: &str, input| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name, input))).unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let user = data("demo.user.create", serde_json::json!({"name":"author"}));
|
||||
let default = data("demo.article.defaultUser", serde_json::json!({}));
|
||||
assert_eq!(default["user_id"], user["id"]);
|
||||
assert_eq!(
|
||||
data(
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"article_id":default["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
let key = serde_json::json!({"user_id":user["id"],"category":" news ","title":"first"});
|
||||
let first = data("demo.article.save", key.clone());
|
||||
let mut updated = key.clone();
|
||||
updated["title"] = "updated".into();
|
||||
let second = data("demo.article.save", updated);
|
||||
assert_eq!(first["id"], second["id"]);
|
||||
assert_eq!(second["saved_title"], "updated");
|
||||
assert_eq!(second["author"], user["id"]);
|
||||
for input in [
|
||||
key,
|
||||
serde_json::json!({"user_id":999,"category":"bad","title":"missing parent"}),
|
||||
] {
|
||||
let output = call("demo.article.create", input);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Constraint"));
|
||||
}
|
||||
let output = call(
|
||||
"demo.article.save",
|
||||
serde_json::json!({"user_id":user["id"],"category":null,"title":"null key"}),
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("InvalidData"));
|
||||
assert!(
|
||||
!call(
|
||||
"demo.user.remove",
|
||||
serde_json::json!({"user_id":user["id"]})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"article_id":first["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"demo.user.remove",
|
||||
serde_json::json!({"user_id":user["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
// 真实 catalog 验证外键默认索引与复合前缀去重。
|
||||
dever_runtime::task::run(true, 8, async |scope| {
|
||||
let database = dever_runtime::database::Database::sqlite(
|
||||
&root.join("data/model.db"),
|
||||
false,
|
||||
dever_runtime::database::Options {
|
||||
max_page_size: 100,
|
||||
max_connections: 1,
|
||||
wait_timeout: std::time::Duration::from_secs(5),
|
||||
io_timeout: std::time::Duration::from_secs(30),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut executor = database.acquire().await.unwrap();
|
||||
let indexes = executor
|
||||
.query(
|
||||
scope,
|
||||
"SELECT name FROM pragma_index_list('demo_article') ORDER BY name".into(),
|
||||
vec![],
|
||||
|row| row.get::<String>(0),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
indexes,
|
||||
[
|
||||
"demo_article__compound_0",
|
||||
"demo_article__compound_1",
|
||||
"demo_article_parent_id_idx"
|
||||
]
|
||||
);
|
||||
Ok::<_, std::convert::Infallible>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_indexes_and_cross_database_references_are_rejected() {
|
||||
let root = project(
|
||||
"model-index-errors",
|
||||
"copy(value: data.Article) (out: data.Article) { out = value }",
|
||||
);
|
||||
for model in [
|
||||
"type Article { title: Text }\nindex(missing)",
|
||||
"type Article { title: Text }\nunique(title, title)",
|
||||
"type Article { title: Text }\nindex(title)\nunique(title)",
|
||||
"database archive\ntype Article { user_id: demo.user.data.id }",
|
||||
"global type Article { user_id: demo.user.data.id }",
|
||||
"type Article { title: Text external }",
|
||||
"type Article { user_id: demo.user.data.id external }",
|
||||
"global type Article { user_id: demo.user.data.id external }",
|
||||
"type Article { title: Text from title }",
|
||||
"type Article { title: Text, heading: Text from title }",
|
||||
"type Article { title: Text from old_title, heading: Text from old_title }",
|
||||
"type Article { title: Text }\nseed {{title = \"x\"}}",
|
||||
"type Article { title: Text unique }\nseed {{id = 1,title = \"x\"}}",
|
||||
"type Article { title: Text(3,10) unique }\nseed {{title = \"x\"}}",
|
||||
"type Article { title: Text? unique }\nseed {{title = null}}",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/data/main.dever"), model).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{model}");
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C005", "{error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_wire_checks_stored_fields_without_traversing_virtual_relations() {
|
||||
let root = project(
|
||||
"model-relation-wire",
|
||||
"flow read(article_id: data.id) (out: data.Article?)\n| step | kind | do |\n| out | data | data.first(id == article_id) |",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, category_id: data.category.id? }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("module/demo/article/data")).unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/data/category.dever"),
|
||||
"type Category { name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd read = app.read",
|
||||
)
|
||||
.unwrap();
|
||||
// 关联目标的私有字段不在 Article 的协议里。自身存储字段的限制仍须保留。
|
||||
fs::write(
|
||||
root.join("module/demo/article/data/category.dever"),
|
||||
"type Category { private name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
analyze(&root);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { private title: Text, category_id: data.category.id? }",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C006", "{error:?}");
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, category_id: data.category.id? }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(root.join("module/demo/article/app/main.dever"), "type Envelope { article:data.Article, key:Secret }\necho(value:Envelope) (out:Envelope) {out=value}").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd echo=app.echo",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C005", "{error:?}");
|
||||
assert!(error.message.contains("Secret"), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_constraint_indexes_are_unique_across_model_tables() {
|
||||
let root = project(
|
||||
"model-pg-names",
|
||||
"flow read() (out: data.Article?)\n| step | kind | do |\n| out | data | data.first() |",
|
||||
);
|
||||
for (domain, model) in [("article", "Article"), ("user", "User")] {
|
||||
fs::write(
|
||||
root.join(format!("module/demo/{domain}/data/main.dever")),
|
||||
format!("type {model} {{ slug: Text unique }}"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
let text = generated
|
||||
.values()
|
||||
.map(|file| file.text.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
for table in ["demo_article", "demo_user"] {
|
||||
assert!(text.contains(&format!("{table}_pkey")));
|
||||
assert!(text.contains(&format!("_dever_unique_{table}_2")));
|
||||
}
|
||||
assert!(!text.contains("_dever_pk"));
|
||||
assert!(!text.contains("_dever_unique_2"));
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_crud_and_transaction_use_real_database() {
|
||||
let root = project(
|
||||
"model-crud-native",
|
||||
r#"
|
||||
flow create(title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({ title = title, with = title }) |
|
||||
|
||||
flow read(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.get(article_id) |
|
||||
|
||||
transaction flow rename(article_id: data.id, title: Text) (changed: Int)
|
||||
| step | kind | do |
|
||||
| changed | data | data.update({ where = id == article_id }, { title = title }) |
|
||||
|
||||
flow reject(title: Text, accepted: Bool) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({ title = title }) |
|
||||
| - | check | accepted else Conflict |
|
||||
|
||||
flow list(page: Int, size: Int) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(page = page, size = size, order = id.asc) |
|
||||
|
||||
flow items(page: Int, size: Int) (out: List<data.Article>) {
|
||||
out = data.page(title.contains("标题"), page = page, size = size, order = id.asc).items
|
||||
}
|
||||
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
|
||||
flow remove(article_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(article_id) |
|
||||
"#,
|
||||
);
|
||||
write_source(root.join("module/demo/article/data/main.dever"), "type Status { Draft, Published }\ntype Article { title: Text(1, 120) unique, status: Status default Draft index, body: Text? raw, with: Text? }").unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"),"cmd create = app.create\ncmd read = app.read\ncmd rename = app.rename\ncmd reject = app.reject\ncmd count = app.count\ncmd list = app.list\ncmd items = app.items\ncmd remove = app.remove").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
assert!(!call("demo.article.count", "{}").status.success());
|
||||
assert!(!root.join("data/model.db").exists());
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let output = success(call("demo.article.create", r#"{"title":"' OR 1=1 --"}"#));
|
||||
let saved: serde_json::Value = serde_json::from_str(&output).unwrap();
|
||||
let id = saved["data"]["id"].as_i64().unwrap();
|
||||
assert_eq!(saved["data"]["title"], "' OR 1=1 --");
|
||||
assert_eq!(saved["data"]["with"], saved["data"]["title"]);
|
||||
assert_eq!(saved["data"]["status"], "Draft");
|
||||
assert_eq!(saved["data"]["body"], serde_json::Value::Null);
|
||||
let duplicate = call("demo.article.create", r#"{"title":"' OR 1=1 --"}"#);
|
||||
assert!(!duplicate.status.success());
|
||||
assert!(String::from_utf8_lossy(&duplicate.stderr).contains("Constraint"));
|
||||
assert!(
|
||||
!call("demo.article.create", r#"{"title":" "}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let input = serde_json::json!({"article_id":id}).to_string();
|
||||
let read: serde_json::Value =
|
||||
serde_json::from_str(&success(call("demo.article.read", &input))).unwrap();
|
||||
assert_eq!(read["data"], saved["data"]);
|
||||
success(call(
|
||||
"demo.article.rename",
|
||||
&serde_json::json!({"article_id":id,"title":" 新标题 "}).to_string(),
|
||||
));
|
||||
let output = call(
|
||||
"demo.article.reject",
|
||||
r#"{"title":"必须回滚","accepted":false}"#,
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
let count: serde_json::Value =
|
||||
serde_json::from_str(&success(call("demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(count["data"], 1);
|
||||
let page: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.list",
|
||||
r#"{"page":1,"size":2}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(page["data"]["total"], 1);
|
||||
assert_eq!(page["data"]["pages"], 1);
|
||||
let items = |p: i64, size: i64| {
|
||||
call(
|
||||
"demo.article.items",
|
||||
&serde_json::json!({"page":p,"size":size}).to_string(),
|
||||
)
|
||||
};
|
||||
let first: serde_json::Value = serde_json::from_str(&success(items(1, 2))).unwrap();
|
||||
assert_eq!(first["data"], page["data"]["items"]);
|
||||
let past: serde_json::Value = serde_json::from_str(&success(items(2, 2))).unwrap();
|
||||
assert_eq!(past["data"], serde_json::json!([]));
|
||||
assert!(!items(0, 2).status.success());
|
||||
assert!(!items(i64::MAX, 2).status.success());
|
||||
assert_eq!(page["data"]["items"][0]["title"], "新标题");
|
||||
let page: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.list",
|
||||
r#"{"page":2,"size":2}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(page["data"]["total"], 1);
|
||||
assert_eq!(page["data"]["items"], serde_json::json!([]));
|
||||
assert!(
|
||||
!call("demo.article.list", r#"{"page":0,"size":2}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
!call("demo.article.list", r#"{"page":1,"size":101}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(call("demo.article.remove", &input));
|
||||
let output = call("demo.article.read", &input);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("NotFound"));
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
use super::*;
|
||||
|
||||
fn executable(name: &str, app: &str, api: &str) -> (PathBuf, PathBuf) {
|
||||
let root = project(name, app);
|
||||
fs::write(root.join("module/demo/article/api.dever"), api).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db","max_connections":4}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
(artifact.binary, config)
|
||||
}
|
||||
fn call(binary: &std::path::Path, config: &std::path::Path, name: &str, input: &str) -> Output {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_failure_cannot_be_captured_and_committed() {
|
||||
let (binary, config) = executable(
|
||||
"model-nested-rollback",
|
||||
r#"
|
||||
type Problem { error Denied }
|
||||
type Attempt { Saved, error Rejected(value: Problem), error Storage(value: dever.database.Error) }
|
||||
transaction flow inner(title: Text, allowed: Bool) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({title = title}) |
|
||||
| - | check | allowed else Problem.Denied |
|
||||
rule handled(value: Attempt) (out: Bool) recover("报告被拒绝的请求")
|
||||
| value | out |
|
||||
| Saved | true |
|
||||
| Rejected(error) | false |
|
||||
| Storage(error) | fail(error) |
|
||||
transaction flow outer(title: Text, allowed: Bool) (out: Bool)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(inner(title, allowed)) |
|
||||
| out | rule | handled(attempt) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
"cmd outer = app.outer\ncmd count = app.count",
|
||||
);
|
||||
let output = call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.outer",
|
||||
r#"{"title":"不得提交","allowed":false}"#,
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Database"));
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&binary, &config, "demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(output["data"], 0);
|
||||
success(call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.outer",
|
||||
r#"{"title":"正常提交","allowed":true}"#,
|
||||
));
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&binary, &config, "demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(output["data"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_entry_commits_explicit_stages_and_tasks_use_separate_contexts() {
|
||||
let (binary, config) = executable(
|
||||
"model-long-stages",
|
||||
r#"
|
||||
transaction flow save(title: Text) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({title = title}) |
|
||||
flow stages(title: Text, allowed: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(title) |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| - | check | allowed else Conflict |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow concurrent() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(count()) |
|
||||
| out | calc | wait(task) |
|
||||
flow counts() (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | data | reads | data.count() |
|
||||
| right | flow | reads | count() |
|
||||
"#,
|
||||
"long cmd stages = app.stages\ncmd count = app.concurrent\ncmd counts = app.counts",
|
||||
);
|
||||
assert!(
|
||||
!call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.stages",
|
||||
r#"{"title":"已提交阶段","allowed":false}"#
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&binary, &config, "demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(output["data"], 1);
|
||||
let output: serde_json::Value = serde_json::from_str(&success(call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.counts",
|
||||
"{}",
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(output["data"], serde_json::json!({"left":1,"right":1}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_transaction_and_model_access_constraints_are_static() {
|
||||
let root = project(
|
||||
"model-entry-constraints",
|
||||
r#"
|
||||
flow create(title: Text) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({title = title}) |
|
||||
"#,
|
||||
);
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"long cmd create = app.create",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("transaction flow"), "{error:?}");
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd create = app.create",
|
||||
)
|
||||
.unwrap();
|
||||
for app in [
|
||||
"flow create(title: Text) ()\n| step | kind | do |\n| saved | data | data.create({title = title}) |\n| - | flow | dever.time.sleep(1) |",
|
||||
"flow create(title: Text) ()\n| step | kind | do |\n| changed | data | data.update({}, {title = title}) |",
|
||||
"flow create(title: Text) ()\n| step | kind | do |\n| saved | data | demo.user.data.create({name = title}) |",
|
||||
"transaction flow create(title: Text) ()\n| step | kind | parallel | do |\n| left | data | reads | data.count() |\n| right | data | reads | data.count() |",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{app}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_services_migrate_when_configured() {
|
||||
services_migrate_when_configured(
|
||||
"sqlite-startup-migration",
|
||||
serde_json::json!({"type":"sqlite","path":"data/model.db"}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_services_migrate_when_configured() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
|
||||
services_migrate_when_configured(
|
||||
"postgres-startup-migration",
|
||||
serde_json::json!({"type":"postgres","url":url,"tls":"disabled"}),
|
||||
);
|
||||
}
|
||||
|
||||
fn services_migrate_when_configured(name: &str, database: serde_json::Value) {
|
||||
use crate::api::{Server, config};
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
flow create(title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = title}) |
|
||||
flow get(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.get(article_id) |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
let api = root.join("module/demo/article/api/front");
|
||||
fs::create_dir_all(&api).unwrap();
|
||||
fs::write(
|
||||
api.join("main.dever"),
|
||||
"public post create = app.create\npublic get get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["database"] = serde_json::json!({"create":true,"default":database});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let artifact = build();
|
||||
let first = Server::start(&artifact.binary, &path, port);
|
||||
let (status, original) = first.call(
|
||||
"POST",
|
||||
"/demo/article/front/main/create",
|
||||
r#"{"title":"original"}"#,
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{original}");
|
||||
let (_, second_port, mut second_settings) = config(&root);
|
||||
let second_path = path.with_file_name("second.json");
|
||||
second_settings["database"] = settings["database"].clone();
|
||||
fs::write(&second_path, second_settings.to_string()).unwrap();
|
||||
first.stop();
|
||||
drop(artifact);
|
||||
|
||||
write_source(
|
||||
&model,
|
||||
"type Article { title: Text, state: Text default \"draft\" }",
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
settings["database"]["create"] = false.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let reserved = std::net::TcpListener::bind(("127.0.0.1", port)).unwrap();
|
||||
let rejected = Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("api")
|
||||
.output()
|
||||
.unwrap();
|
||||
drop(reserved);
|
||||
assert!(!rejected.status.success());
|
||||
let error = String::from_utf8_lossy(&rejected.stderr);
|
||||
assert!(error.contains("schema is outdated or changed"), "{error}");
|
||||
|
||||
settings["database"]["create"] = true.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (first, second) = std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| Server::start(&artifact.binary, &path, port));
|
||||
let second = scope.spawn(|| Server::start(&artifact.binary, &second_path, second_port));
|
||||
(first.join().unwrap(), second.join().unwrap())
|
||||
});
|
||||
for server in [first, second] {
|
||||
let (status, updated) =
|
||||
server.call("GET", "/demo/article/front/main/get?article_id=1", "", "");
|
||||
assert_eq!(status, 200, "{updated}");
|
||||
assert_eq!(updated["data"]["id"], original["data"]["id"]);
|
||||
assert_eq!(
|
||||
updated["data"]["created_at"],
|
||||
original["data"]["created_at"]
|
||||
);
|
||||
assert_eq!(updated["data"]["title"], "original");
|
||||
assert_eq!(updated["data"]["state"], "draft");
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_startup_prepares_declared_models_without_database_calls() {
|
||||
use crate::api::{Server, config};
|
||||
let root = project("declared-model-startup", "hello() (out: Int) { out = 42 }");
|
||||
let api = root.join("module/demo/article/api/front");
|
||||
fs::create_dir_all(&api).unwrap();
|
||||
fs::write(api.join("main.dever"), "public get hello = app.hello").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["database"] =
|
||||
serde_json::json!({"create":true,"default":{"type":"sqlite","path":"data/model.db"}});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
assert!(root.join("data/model.db").is_file());
|
||||
let (status, value) = server.call("GET", "/demo/article/front/main/hello", "", "");
|
||||
assert_eq!(status, 200, "{value}");
|
||||
assert_eq!(value["data"], 42);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn front_startup_prepares_declared_models() {
|
||||
use crate::api::{Server, config};
|
||||
let root = project("front-model-startup", "hello() (out: Int) { out = 42 }");
|
||||
let front = root.join("module/demo/front/src");
|
||||
for directory in [&front, &root.join("config"), &root.join("data")] {
|
||||
fs::create_dir_all(directory).unwrap();
|
||||
}
|
||||
fs::write(front.join("index.html"), "<h1>Dever</h1>").unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["sites"]["front"]["front"] = serde_json::json!({"component":"demo","path":"/"});
|
||||
settings["database"] =
|
||||
serde_json::json!({"create":true,"default":{"type":"sqlite","path":"data/model.db"}});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
Server::start(&artifact.binary, &path, port).stop();
|
||||
|
||||
settings["database"]["create"] = false.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let (status, body, _) = server.raw_response("GET", "/", "", "");
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(body, "<h1>Dever</h1>");
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::*;
|
||||
use dever::compiler::model::{Shape, Type};
|
||||
mod auth;
|
||||
mod bindings;
|
||||
mod constraints;
|
||||
mod crud;
|
||||
mod lifecycle;
|
||||
mod query;
|
||||
mod scalars;
|
||||
mod transaction;
|
||||
mod writes;
|
||||
|
||||
fn project(name: &str, app: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
for (domain, model) in [
|
||||
("article", "type Article { title: Text }"),
|
||||
("user", "type User { name: Text }"),
|
||||
] {
|
||||
let path = root.join(format!("module/demo/{domain}"));
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
write_source(path.join("data/main.dever"), model).unwrap();
|
||||
}
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ids_and_generated_fields_execute_through_the_real_wire_boundary() {
|
||||
let root = project(
|
||||
"model-id-native",
|
||||
"echo(article: data.Article) (out: data.Article) { out = article }\nkey(article_id: data.id) (out: Text) { out = dever.id.toText(article_id) }\nflow taskKey(article_id: data.id) (out: Text) { out = parallel(dever.id.toText(article_id)) }",
|
||||
);
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd echo = app.echo\ncmd key = app.key\ncmd taskKey = app.taskKey",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let article = program
|
||||
.definitions
|
||||
.iter()
|
||||
.find(|definition| definition.name == "demo.article.data.Article")
|
||||
.unwrap();
|
||||
let Shape::Record(fields) = &article.shape else {
|
||||
panic!("Model record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| field.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["id", "created_at", "title"]
|
||||
);
|
||||
assert!(matches!(fields[0].kind, Type::ModelId(_)));
|
||||
let files = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
let app = &files["module/d_4_demo_7_article_3_app.rs"].text;
|
||||
assert!(!app.contains("clone"), "{app}");
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
for (cmd, id) in [
|
||||
("demo.article.key", 1),
|
||||
("demo.article.key", i64::MAX),
|
||||
("demo.article.taskKey", i64::MAX),
|
||||
] {
|
||||
let output = success(
|
||||
Command::new(&artifact.binary)
|
||||
.args([cmd, &serde_json::json!({"article_id":id}).to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"],
|
||||
id.to_string()
|
||||
);
|
||||
}
|
||||
let input =
|
||||
serde_json::json!({"article":{"id":7,"created_at":"2026-11-12T12:00:00Z","title":"文章"}});
|
||||
let output = success(
|
||||
Command::new(&artifact.binary)
|
||||
.args(["demo.article.echo", &input.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let output: serde_json::Value = serde_json::from_str(&output).unwrap();
|
||||
assert_eq!(output["data"], input["article"]);
|
||||
for id in [
|
||||
serde_json::json!(0),
|
||||
serde_json::json!(-1),
|
||||
serde_json::json!("7"),
|
||||
serde_json::json!(7.5),
|
||||
] {
|
||||
let mut input = input.clone();
|
||||
input["article"]["id"] = id;
|
||||
let output = Command::new(&artifact.binary)
|
||||
.args(["demo.article.echo", &input.to_string()])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success(), "invalid Model ID accepted");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ids_are_nominal_and_model_topics_keep_separate_identity() {
|
||||
let root = project(
|
||||
"model-id-check",
|
||||
"same(left: data.id, right: data.id) (out: Bool) { out = left == right }",
|
||||
);
|
||||
let topic = root.join("module/demo/article/data");
|
||||
fs::create_dir_all(&topic).unwrap();
|
||||
fs::write(
|
||||
topic.join("revision.dever"),
|
||||
"type Revision { article_id: data.id }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(root.join("module/demo/article/app/main.dever"), "same(left: data.id, right: data.id) (out: Bool) { out = left == right }\ncopy(value: data.revision.id) (out: data.revision.id) { out = value }\npage(value: data.Page) (out: data.Page) { out = value }").unwrap();
|
||||
analyze(&root);
|
||||
for app in [
|
||||
"wrong(value: data.id) (out: demo.user.data.id) { out = value }",
|
||||
"wrong(value: data.id) (out: data.revision.id) { out = value }",
|
||||
"wrong(value: Int) (out: data.id) { out = value }",
|
||||
"wrong() (out: data.id) { out = 1 }",
|
||||
"wrong(value: data.id?) (out: Text) { out = dever.id.toText(value) }",
|
||||
"wrong(value: Int) (out: Text) { out = dever.id.toText(value) }",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{app}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_generated_fields_and_role_boundaries_cannot_be_overridden() {
|
||||
let root = project(
|
||||
"model-generated-check",
|
||||
"read(value: data.Article) (out: Text) { out = value.title }",
|
||||
);
|
||||
for model in [
|
||||
"type Article { id: Int }",
|
||||
"type Article { created_at: DateTime }",
|
||||
"type Article { title: Text }\ntype Page { total: Int }",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/data/main.dever"), model).unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{model}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/domain.dever"),
|
||||
"copy(value: data.id) (out: data.id) { out = value }",
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(program::check(&project.declarations, &project.modules).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nominal_id_references_participate_in_domain_cycle_checks() {
|
||||
let root = project(
|
||||
"model-id-domain-cycle",
|
||||
"copy(value: demo.user.data.id) (out: demo.user.data.id) { out = value }",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/user/app/main.dever"),
|
||||
"copy(value: demo.article.data.id) (out: demo.article.data.id) { out = value }",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("cyclic domain"), "{error:?}");
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn sqlite_model_filters_apply_to_pages_cursors_and_writes() {
|
||||
filters(
|
||||
"sqlite-model-filters",
|
||||
json!({"type":"sqlite","path":"data/article.db"}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_model_filters_apply_to_pages_cursors_and_writes() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").unwrap();
|
||||
filters(
|
||||
"postgres-model-filters",
|
||||
json!({"type":"postgres","url":url,"tls":"disabled"}),
|
||||
);
|
||||
}
|
||||
|
||||
fn filters(name: &str, database: Value) {
|
||||
let sqlite = database["type"] == "sqlite";
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(domain.join("flow/article.dv"), r#"
|
||||
flow add(title: Text, rank: Int, cost: Decimal) (out: data.Article) {
|
||||
out = data.create({title = title, rank = rank, cost = cost})
|
||||
}
|
||||
flow required(rank_value: Int) (out: data.Article) {
|
||||
out = data.get(rank == rank_value)
|
||||
}
|
||||
flow earliest(rank_value: Int) (out: data.Article) {
|
||||
out = data.get(rank == rank_value, order = id.asc)
|
||||
}
|
||||
flow page(prefix: Text, suffix: Text, minimum: Decimal, maximum: Decimal) (out: data.Page) {
|
||||
out = data.page(in(rank, [1, 2]) and between(cost, minimum, maximum) and startsWith(title, prefix) and endsWith(title, suffix) and not (title.contains("跳过") or note != null), order = cost.asc, size = 1)
|
||||
}
|
||||
flow scoped(store: Int, sku: Text, name: Text, take: Int) (out: List<data.Article>) {
|
||||
out = data.list(rank == store and (title == sku or title == name), order = id.asc, limit = take)
|
||||
}
|
||||
flow optional(term: Text?, rank_value: Int?, note_value: Text?) (out: Int) {
|
||||
out = data.count(ifSet(title.contains(term)) and ifSet(rank == rank_value) and ifSet(note == note_value))
|
||||
}
|
||||
flow grouped(term: Text?, n: Int?) (disj: Int, nested: Int, neg: Int, root: Int, neq: Int, plain: Int) {
|
||||
disj = data.count(rank == 3 or ifSet(title == term))
|
||||
nested = data.count(rank == 3 or (ifSet(rank == n) and ifSet(title == term)))
|
||||
neg = data.count(not (ifSet(title == term)))
|
||||
root = data.count(ifSet(rank == n) or ifSet(title == term))
|
||||
neq = data.count(ifSet(note != term))
|
||||
plain = data.count(note != term)
|
||||
}
|
||||
flow change(term: Text?) (out: Int) {
|
||||
out = data.update({where = rank == 3 or ifSet(title == term)}, {note = "selected"})
|
||||
}
|
||||
flow optionalChange(term: Text?, n: Int?) (out: Int) {
|
||||
out = data.update({where = ifSet(rank == n) or ifSet(title == term)}, {note = "optional"})
|
||||
}
|
||||
flow optionalDelete(n: Int?) (out: Int) {
|
||||
out = data.delete({where = not (ifSet(rank != n))})
|
||||
}
|
||||
flow scan(after: data.Article?, prefix: Text, suffix: Text) (out: data.Cursor) {
|
||||
out = data.cursor(startsWith(title, prefix) and endsWith(title, suffix) and not (rank == 3), after = after, order = cost.asc, size = 1)
|
||||
}
|
||||
flow mark(prefix: Text, suffix: Text, cost: Decimal) (out: Int) {
|
||||
out = data.update({where = in(cost, [cost]) and startsWith(title, prefix) and endsWith(title, suffix)}, {note = "marked"})
|
||||
}
|
||||
flow count(suffix: Text) (out: Int) {
|
||||
out = data.count(endsWith(title, suffix))
|
||||
}
|
||||
"#).unwrap();
|
||||
write_source(
|
||||
domain.join("data/article.dv"),
|
||||
"type Article {title: Text raw,rank: Int,cost: Decimal(20,2),note: Text?}",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(domain.join("api/article.dv"), "cmd add = app.add\ncmd required = app.required\ncmd earliest = app.earliest\ncmd page = app.page\ncmd scan = app.scan\ncmd mark = app.mark\ncmd count = app.count\ncmd optional = app.optional\ncmd scoped = app.scoped\ncmd grouped = app.grouped\ncmd change = app.change\ncmd optionalChange = app.optionalChange\ncmd optionalDelete = app.optionalDelete").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
let command = || {
|
||||
let mut command = Command::new(&artifact.binary);
|
||||
command.arg("--config").arg(&config);
|
||||
command
|
||||
};
|
||||
success(command().arg("migrate").output().unwrap());
|
||||
let call = |name: &str, args: Value| -> Value {
|
||||
let text = success(
|
||||
command()
|
||||
.args([&format!("demo.article.{name}"), &args.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
serde_json::from_str::<Value>(&text).unwrap()["data"].clone()
|
||||
};
|
||||
let prefix = "边%a_";
|
||||
let suffix = "_尾%";
|
||||
let low = "9007199254740992.01";
|
||||
let high = "9007199254740992.02";
|
||||
for (title, rank, cost) in [
|
||||
("边%a_x_尾%", 1, low),
|
||||
("边%a_y_尾%", 2, high),
|
||||
("边%a_跳过_尾%", 2, high),
|
||||
("边%a_z_尾%", 3, high),
|
||||
("边%a_z_尾%", 2, "9007199254740992.03"),
|
||||
("边%a_wrong尾%", 1, low),
|
||||
("边%Ax_尾%", 1, low),
|
||||
] {
|
||||
call("add", json!({"title":title,"rank":rank,"cost":cost}));
|
||||
}
|
||||
assert_eq!(
|
||||
call("required", json!({"rank_value": 2}))["title"],
|
||||
"边%a_z_尾%"
|
||||
);
|
||||
assert_eq!(
|
||||
call("earliest", json!({"rank_value": 2}))["title"],
|
||||
"边%a_y_尾%"
|
||||
);
|
||||
let scoped =
|
||||
|store, take| json!({"store":store,"sku":"边%a_y_尾%","name":"边%a_z_尾%","take":take});
|
||||
let found = call("scoped", scoped(2, 10));
|
||||
let found = found.as_array().unwrap();
|
||||
assert_eq!(found.len(), 2);
|
||||
assert!(found.iter().all(|row| row["rank"] == 2));
|
||||
assert_eq!(call("scoped", scoped(2, 1)), json!([found[0]]));
|
||||
assert_eq!(call("scoped", scoped(99, 10)), json!([]));
|
||||
for take in [0, -1, i64::MAX] {
|
||||
let invalid = command()
|
||||
.args(["demo.article.scoped", &scoped(2, take).to_string()])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("InvalidData"));
|
||||
}
|
||||
let miss = command()
|
||||
.args(["demo.article.required", r#"{"rank_value":99}"#])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!miss.status.success());
|
||||
assert!(String::from_utf8_lossy(&miss.stderr).contains("NotFound"));
|
||||
let args = json!({"prefix":prefix,"suffix":suffix,"minimum":low,"maximum":high});
|
||||
assert_eq!(call("optional", json!({})), 7);
|
||||
assert_eq!(call("optional", json!({"term":"%a_", "rank_value":2})), 3);
|
||||
assert_eq!(call("optional", json!({"note_value":"absent"})), 0);
|
||||
let page = call("page", args.clone());
|
||||
assert_eq!(page["total"], 2);
|
||||
assert_eq!(page["items"][0]["title"], "边%a_x_尾%");
|
||||
let first = call(
|
||||
"scan",
|
||||
json!({"after":null,"prefix":prefix,"suffix":suffix}),
|
||||
);
|
||||
assert_eq!(first["items"][0]["title"], "边%a_x_尾%");
|
||||
assert_eq!(first["has_more"], true);
|
||||
let second = call(
|
||||
"scan",
|
||||
json!({"after":first["next"],"prefix":prefix,"suffix":suffix}),
|
||||
);
|
||||
assert_eq!(second["items"][0]["cost"], high);
|
||||
assert_eq!(
|
||||
call("mark", json!({"prefix":prefix,"suffix":suffix,"cost":low})),
|
||||
1
|
||||
);
|
||||
assert_eq!(call("page", args)["total"], 1);
|
||||
assert_eq!(call("count", json!({"suffix":""})), 7);
|
||||
assert_eq!(call("count", json!({"suffix":"' OR 1=1 --"})), 0);
|
||||
if sqlite {
|
||||
for title in ["边%a_z_尾%\0后续", "边%a_z\0_尾%"] {
|
||||
call("add", json!({"title":title,"rank":1,"cost":low}));
|
||||
}
|
||||
assert_eq!(call("count", json!({"suffix":suffix})), 7);
|
||||
assert_eq!(call("count", json!({"suffix":"\0_尾%"})), 1);
|
||||
}
|
||||
let total = if sqlite { 9 } else { 7 };
|
||||
for cmd in ["optionalChange", "optionalDelete"] {
|
||||
let invalid = command()
|
||||
.args([&format!("demo.article.{cmd}"), "{}"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("InvalidData"));
|
||||
}
|
||||
assert_eq!(call("optional", json!({"note_value":"optional"})), 0);
|
||||
let empty = call("grouped", json!({}));
|
||||
assert_eq!(empty["disj"], 1);
|
||||
assert_eq!(empty["nested"], 1);
|
||||
assert_eq!(empty["neg"], total);
|
||||
assert_eq!(empty["root"], total);
|
||||
assert_eq!(call("change", json!({})), 1);
|
||||
let selected = call("grouped", json!({"term":"selected"}));
|
||||
assert_eq!(selected["neq"], total - 1);
|
||||
assert_eq!(selected["neq"], selected["plain"]);
|
||||
assert_eq!(call("grouped", json!({"n":2}))["nested"], 4);
|
||||
assert_eq!(call("optionalChange", json!({"n":3})), 1);
|
||||
assert_eq!(call("optionalDelete", json!({"n":3})), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_filters_reject_invalid_fields_types_and_lists() {
|
||||
let root = directory("invalid-model-filters");
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(
|
||||
domain.join("data/article.dv"),
|
||||
"type Article { title: Text, rank: Int }",
|
||||
)
|
||||
.unwrap();
|
||||
let path = domain.join("flow/article.dv");
|
||||
for condition in [
|
||||
"in(title, [])",
|
||||
"in(title, [1])",
|
||||
"in(rank, values)",
|
||||
"between(title, 1, 2)",
|
||||
"startsWith(id, \"a\")",
|
||||
"endsWith(title, null)",
|
||||
"not (missing == \"a\")",
|
||||
] {
|
||||
write_source(
|
||||
&path,
|
||||
format!(
|
||||
"flow scan(values: List<Text>) (out: Int) {{\n out = data.count({condition})\n}}"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{condition}");
|
||||
assert_eq!(
|
||||
program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.code,
|
||||
"C005",
|
||||
"{condition}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use super::*;
|
||||
mod filters;
|
||||
mod native;
|
||||
mod postgres;
|
||||
mod relation;
|
||||
mod stream;
|
||||
|
||||
#[test]
|
||||
fn cursor_reads_stable_pages_without_count_and_preserves_exact_decimal_order() {
|
||||
let root = project(
|
||||
"model-cursor-native",
|
||||
r#"
|
||||
flow create(title: Text, rank: Int, cost: Decimal) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = title, rank = rank, cost = cost}) |
|
||||
flow page(after: data.Article?, size: Int, keyword: Text) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(title.contains(keyword), order = [rank.asc, cost.desc], after = after, size = size) |
|
||||
flow newest(after: data.Article?, size: Int) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(after = after, size = size) |
|
||||
flow remove(article_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(article_id) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, rank: Int, cost: Decimal(20,2), note: Text? }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd create = app.create\ncmd page = app.page\ncmd newest = app.newest\ncmd remove = app.remove").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/cursor.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
let app = &generated["module/d_4_demo_7_article_3_app.rs"].text;
|
||||
assert!(!app.contains("COUNT("));
|
||||
assert!(!app.contains("OFFSET"));
|
||||
assert!(
|
||||
!app.contains("(NOT "),
|
||||
"cursor SQL must seek without an optional-cursor OR flag"
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let data = |name: &str, input| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name, input))).unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let empty = data(
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null,"size":2,"keyword":"keep"}),
|
||||
);
|
||||
assert_eq!(
|
||||
empty,
|
||||
serde_json::json!({"items":[],"next":null,"has_more":false})
|
||||
);
|
||||
let mut rows = Vec::new();
|
||||
for (title, rank, cost) in [
|
||||
("keep A", 1, "9007199254740992.01"),
|
||||
("keep B", 1, "9007199254740992.02"),
|
||||
("keep C", 1, "9007199254740992.02"),
|
||||
("keep D", 2, "1.00"),
|
||||
("skip", 0, "2.00"),
|
||||
] {
|
||||
rows.push(data(
|
||||
"demo.article.create",
|
||||
serde_json::json!({"title":title,"rank":rank,"cost":cost}),
|
||||
));
|
||||
}
|
||||
let first = data(
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null,"size":2,"keyword":"keep"}),
|
||||
);
|
||||
assert_eq!(first["items"], serde_json::json!([rows[2], rows[1]]));
|
||||
assert_eq!(first["has_more"], true);
|
||||
assert_eq!(first["next"], rows[1]);
|
||||
// 游标值携带排序键,上一页末记录删除后仍能继续,不重新查询该记录。
|
||||
data(
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"article_id":rows[1]["id"]}),
|
||||
);
|
||||
let second = data(
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":first["next"],"size":2,"keyword":"keep"}),
|
||||
);
|
||||
assert_eq!(second["items"], serde_json::json!([rows[0], rows[3]]));
|
||||
assert_eq!(second["has_more"], false);
|
||||
assert!(second["next"].is_null());
|
||||
let newest = data(
|
||||
"demo.article.newest",
|
||||
serde_json::json!({"after":null,"size":1}),
|
||||
);
|
||||
assert_eq!(newest["items"], serde_json::json!([rows[4]]));
|
||||
for size in [0, -1, i64::MAX] {
|
||||
let output = call(
|
||||
"demo.article.newest",
|
||||
serde_json::json!({"after":null,"size":size}),
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("InvalidData"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_rejects_nullable_keys_wrong_identity_and_unknown_options() {
|
||||
let root = project("model-cursor-errors", "");
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text?, rank: Int }",
|
||||
)
|
||||
.unwrap();
|
||||
for query in [
|
||||
"order = [title.asc]",
|
||||
"order = [rank.asc, rank.desc]",
|
||||
"order = []",
|
||||
"order = [missing.asc]",
|
||||
"page = 1",
|
||||
"after = 1",
|
||||
"size = null",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), format!("flow read() (out: data.Cursor)\n| step | kind | do |\n| out | data | data.cursor({query}) |\n")).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{query}");
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{query}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn named_sql_runs_typed_queries_and_keeps_real_result_failures() {
|
||||
let root = project(
|
||||
"named-sql-native",
|
||||
r#"
|
||||
type Title { title: Text }
|
||||
flow lookup(title: Text) (out: Title?)
|
||||
| step | kind | do |
|
||||
| out | data | data.lookup(title) |
|
||||
flow titles(limit: Int >= 1 and <= 10) (out: List<Title>)
|
||||
| step | kind | do |
|
||||
| out | data | data.titles(limit) |
|
||||
flow full() (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.full() |
|
||||
flow invalid() (out: Title)
|
||||
| step | kind | do |
|
||||
| out | data | data.invalid() |
|
||||
flow duplicate() (out: Title?)
|
||||
| step | kind | do |
|
||||
| out | data | data.duplicate() |
|
||||
flow invalidId() (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.invalidId() |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
r#"
|
||||
type Article { title: Text(2,80) unique }
|
||||
seed { {title = "hello"}, {title = "雪' OR 1=1 --"} }
|
||||
sql lookup(title: Text) (row: app.Title?) {
|
||||
sqlite = "SELECT title FROM demo_article WHERE title=?1"
|
||||
postgres = "SELECT title FROM demo_article WHERE title=$1"
|
||||
}
|
||||
sql titles(limit: Int >= 1 and <= 10) (rows: List<app.Title>) {
|
||||
sqlite = "SELECT title FROM demo_article ORDER BY id LIMIT ?1"
|
||||
postgres = "SELECT title FROM demo_article ORDER BY id LIMIT $1"
|
||||
}
|
||||
sql full() (row: Article) {
|
||||
sqlite = "SELECT id,created_at,title FROM demo_article WHERE id=1"
|
||||
postgres = "SELECT id,created_at,title FROM demo_article WHERE id=1"
|
||||
}
|
||||
sql invalid() (row: app.Title) {
|
||||
sqlite = "SELECT 3 AS title"
|
||||
postgres = "SELECT 3::BIGINT AS title"
|
||||
}
|
||||
sql duplicate() (row: app.Title?) {
|
||||
sqlite = "SELECT title FROM demo_article"
|
||||
postgres = "SELECT title FROM demo_article"
|
||||
}
|
||||
sql invalidId() (row: Article) {
|
||||
sqlite = "SELECT 0 AS id, created_at, title FROM demo_article WHERE id=1"
|
||||
postgres = "SELECT 0::BIGINT AS id, created_at, title FROM demo_article WHERE id=1"
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd lookup = app.lookup\ncmd titles = app.titles\ncmd full = app.full\ncmd invalid = app.invalid\ncmd duplicate = app.duplicate\ncmd invalidId = app.invalidId").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db","max_page_size":2}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let index = dever::compiler::inspect::analyze(&loaded, None, 0, true).unwrap();
|
||||
let query = index
|
||||
.symbols
|
||||
.iter()
|
||||
.find(|s| s.name == "demo.article.data.lookup")
|
||||
.unwrap();
|
||||
assert_eq!(query.kind, "sql");
|
||||
assert!(
|
||||
index
|
||||
.calls
|
||||
.iter()
|
||||
.any(|edge| edge.callee == query.id && edge.kind == "sql")
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value = |name: &str, input: serde_json::Value| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name, input))).unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
value(
|
||||
"demo.article.lookup",
|
||||
serde_json::json!({"title":"雪' OR 1=1 --"})
|
||||
)["title"],
|
||||
"雪' OR 1=1 --"
|
||||
);
|
||||
assert!(value("demo.article.lookup", serde_json::json!({"title":"absent"})).is_null());
|
||||
assert_eq!(
|
||||
value("demo.article.titles", serde_json::json!({"limit":2}))
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(value("demo.article.full", serde_json::json!({}))["id"], 1);
|
||||
for name in [
|
||||
"demo.article.invalid",
|
||||
"demo.article.duplicate",
|
||||
"demo.article.invalidId",
|
||||
] {
|
||||
assert!(
|
||||
!call(name, serde_json::json!({})).status.success(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_sql_checks_contracts_and_only_proves_direct_reads() {
|
||||
let root = project(
|
||||
"named-sql-contract",
|
||||
"type Title { title: Text }\nflow find() (out: List<Title>)\n| step | kind | do |\n| out | data | data.find() |\n",
|
||||
);
|
||||
let path = root.join("module/demo/article/data/main.dever");
|
||||
let source = |sql: &str| {
|
||||
format!(
|
||||
"type Article {{ title: Text }}\nsql find() (rows: List<app.Title>) {{ sqlite = {}, postgres = {} }}",
|
||||
serde_json::to_string(sql).unwrap(),
|
||||
serde_json::to_string(sql).unwrap()
|
||||
)
|
||||
};
|
||||
for name in ["notifyChange", "waitChange"] {
|
||||
write_source(
|
||||
&path,
|
||||
source("SELECT title FROM demo_article").replace("sql find", &format!("sql {name}")),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(
|
||||
error.message.contains("reserved Model SQL operation"),
|
||||
"{error:?}"
|
||||
);
|
||||
}
|
||||
for (sql, readonly) in [
|
||||
("SELECT title FROM demo_article WHERE title='?1'", true),
|
||||
("SELECT upper(title) AS title FROM demo_article", false),
|
||||
(
|
||||
"SELECT a.title FROM demo_article AS a JOIN demo_user AS u ON u.id=a.id",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"WITH titles AS (SELECT title FROM demo_article) SELECT title FROM titles",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
write_source(&path, source(sql)).unwrap();
|
||||
let (_, program) = analyze(&root);
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "demo.article.app.find")
|
||||
.unwrap();
|
||||
assert_eq!(!function.effects.database_write, readonly, "{sql}");
|
||||
}
|
||||
for sql in [
|
||||
"SELECT * FROM _dever_history",
|
||||
"SELECT title FROM demo_article; SELECT 1",
|
||||
"DELETE FROM demo_article",
|
||||
] {
|
||||
write_source(&path, source(sql)).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{sql}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"database archive\ntype User { name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
&path,
|
||||
source("SELECT a.title FROM demo_article AS a JOIN demo_user AS u ON a.id=u.id"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.message
|
||||
.contains("database bindings")
|
||||
);
|
||||
write_source(
|
||||
&path,
|
||||
source("SELECT title FROM demo_article").replace("List<app.Title>", "Text"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
use super::*;
|
||||
use dever_runtime::{
|
||||
database::{Sql, config::Config},
|
||||
task,
|
||||
};
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_models_queries_transactions_and_migrations() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
|
||||
let root = project(
|
||||
"postgres-model-native",
|
||||
r#"
|
||||
type Title { title: Text }
|
||||
flow save(code: Text, title: Text, cost: Decimal) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.upsert({code = code}, {title = title, cost = cost}, {title = title, cost = cost}) |
|
||||
flow page(after: data.Article?) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(after = after, size = 1, order = cost.asc) |
|
||||
flow filtered(after: data.Article?, minimum: Decimal) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(cost >= minimum, after = after, size = 1, order = cost.asc) |
|
||||
flow total() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow exactPage(page: Int) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(page = page, size = 1) |
|
||||
flow filteredTotal() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count(code == "two") |
|
||||
flow remove(id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(id) |
|
||||
flow titles() (out: List<Title>)
|
||||
| step | kind | do |
|
||||
| out | data | data.titles() |
|
||||
flow rejected(accept: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({code = "rollback", title = "new", cost = 2.50}) |
|
||||
| - | check | accept else Invalid |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
let original = r#"
|
||||
type Article { code: Text unique, title: Text(2,50), cost: Decimal(20,2), live: Bool default true, obsolete: Text default "old" }
|
||||
sql titles() (rows: List<app.Title>) {
|
||||
sqlite = "SELECT title FROM demo_article ORDER BY id"
|
||||
postgres = "SELECT title FROM demo_article ORDER BY id"
|
||||
}
|
||||
"#;
|
||||
write_source(&model, original).unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"type User { name: Text unique }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"),"cmd save = app.save\ncmd page = app.page\ncmd filtered = app.filtered\ncmd titles = app.titles\ncmd rejected = app.rejected\ncmd total = app.total\ncmd exactPage = app.exactPage\ncmd filteredTotal = app.filteredTotal\ncmd remove = app.remove").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
let connection = |url: &str| serde_json::json!({"type":"postgres","url":url,"tls":"disabled","max_connections":2});
|
||||
let setting =
|
||||
|url: &str| serde_json::json!({"database":{"default":connection(url)}}).to_string();
|
||||
fs::write(&config, setting(&url)).unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let call = |binary: &Path, name: &str, input: serde_json::Value| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let value = |binary: &Path, name: &str, input: serde_json::Value| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(binary,name,input))).unwrap()["data"].clone()
|
||||
};
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let first = value(
|
||||
&artifact.binary,
|
||||
"demo.article.save",
|
||||
serde_json::json!({"code":"one","title":"first","cost":"9007199254740993.01"}),
|
||||
);
|
||||
assert_eq!(first["cost"], "9007199254740993.01");
|
||||
assert_eq!(first["live"], true);
|
||||
let updated = value(
|
||||
&artifact.binary,
|
||||
"demo.article.save",
|
||||
serde_json::json!({"code":"one","title":"updated","cost":"9007199254740993.01"}),
|
||||
);
|
||||
assert_eq!(updated["id"], first["id"]);
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.save",
|
||||
serde_json::json!({"code":"two","title":"second","cost":"9007199254740993.02"}),
|
||||
);
|
||||
let page = value(
|
||||
&artifact.binary,
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null}),
|
||||
);
|
||||
assert_eq!(page["items"][0]["title"], "updated");
|
||||
assert_eq!(page["has_more"], true);
|
||||
let last = value(
|
||||
&artifact.binary,
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":page["next"]}),
|
||||
);
|
||||
assert_eq!(last["items"][0]["title"], "second");
|
||||
assert_eq!(last["has_more"], false);
|
||||
for (after, minimum, expected) in [
|
||||
(serde_json::Value::Null, "9007199254740993.01", page.clone()),
|
||||
(page["next"].clone(), "9007199254740993.01", last.clone()),
|
||||
(serde_json::Value::Null, "9007199254740993.02", last.clone()),
|
||||
] {
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.filtered",
|
||||
serde_json::json!({"after":after,"minimum":minimum})
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!call(
|
||||
&artifact.binary,
|
||||
"demo.article.rejected",
|
||||
serde_json::json!({"accept":false})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.titles",
|
||||
serde_json::json!({})
|
||||
)
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
let total = |binary: &Path| value(binary, "demo.article.total", serde_json::json!({}));
|
||||
assert_eq!(total(&artifact.binary), 2);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.filteredTotal",
|
||||
serde_json::json!({})
|
||||
),
|
||||
1
|
||||
);
|
||||
let beyond = value(
|
||||
&artifact.binary,
|
||||
"demo.article.exactPage",
|
||||
serde_json::json!({"page":3}),
|
||||
);
|
||||
assert_eq!(
|
||||
beyond,
|
||||
serde_json::json!({"items":[],"page":3,"size":1,"total":2,"pages":2})
|
||||
);
|
||||
drop(artifact);
|
||||
let changed = format!(
|
||||
"{}\n{}",
|
||||
original.replace(", obsolete: Text default \"old\"", ""),
|
||||
r#"
|
||||
migrate revise {
|
||||
before { sqlite = "UPDATE demo_article SET title = title || ?1", postgres = "UPDATE demo_article SET title = title || $1", parameters = ["!"] }
|
||||
drop obsolete
|
||||
after { sqlite = "UPDATE demo_article SET live=?1", postgres = "UPDATE demo_article SET live=$1", parameters = [false] }
|
||||
}
|
||||
"#
|
||||
);
|
||||
write_source(&model, &changed).unwrap();
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let page = value(
|
||||
&artifact.binary,
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null}),
|
||||
);
|
||||
assert_eq!(page["items"][0]["title"], "updated!");
|
||||
assert_eq!(page["items"][0]["live"], false);
|
||||
assert!(page["items"][0].get("obsolete").is_none());
|
||||
assert_eq!(total(&artifact.binary), 2);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"id":first["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
assert_eq!(total(&artifact.binary), 1);
|
||||
let database: Config = serde_json::from_value(connection(&url)).unwrap();
|
||||
task::run(true, 16, async |scope| {
|
||||
let database = database.open(&root, false).await?;
|
||||
let mut executor = database.acquire().await?;
|
||||
for sql in [
|
||||
"CREATE ROLE dever_page_viewer",
|
||||
"GRANT SELECT ON demo_article, _dever_model_count, _dever_history TO dever_page_viewer",
|
||||
"ALTER TABLE demo_article ENABLE ROW LEVEL SECURITY",
|
||||
"CREATE POLICY published_article ON demo_article FOR SELECT TO dever_page_viewer USING (code='one')",
|
||||
] {
|
||||
executor.execute(scope, Sql::same(sql), vec![]).await?;
|
||||
}
|
||||
Ok::<_, dever_runtime::database::Error>(())
|
||||
}).unwrap().unwrap();
|
||||
fs::write(
|
||||
&config,
|
||||
setting(&format!("{url} options='-c role=dever_page_viewer'")),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(total(&artifact.binary), 0);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.exactPage",
|
||||
serde_json::json!({"page":1})
|
||||
)["total"],
|
||||
0
|
||||
);
|
||||
fs::write(&config, setting(&url)).unwrap();
|
||||
drop(artifact);
|
||||
write_source(
|
||||
&model,
|
||||
changed.replace("parameters = [false]", "parameters = [true]"),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
assert!(!migrate(&artifact.binary).status.success());
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn related_records_load_in_batches_on_one_sqlite_connection() {
|
||||
exercise(
|
||||
"model-relations",
|
||||
serde_json::json!({"type":"sqlite","path":"data/main.db","max_connections":1,"max_page_size":2}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_related_records_load_in_batches() {
|
||||
exercise(
|
||||
"model-relations-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":1,"max_page_size":2}),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, mut database: serde_json::Value) {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/people");
|
||||
fs::create_dir_all(domain.join("data")).unwrap();
|
||||
for (name, source) in [
|
||||
(
|
||||
"organization",
|
||||
"type Organization {name:Text unique}\nseed {{name=\"Team\"}}",
|
||||
),
|
||||
(
|
||||
"user",
|
||||
"type User {name:Text unique,organization_id:data.organization.id?,manager_id:data.user.id?,extra:Json default \"{\\\"x\\\":1}\"}\nrelation posts = data.post.author_id\nseed {{name=\"Ada\",organization_id=1,manager_id=null},{name=\"Ben\",organization_id=null,manager_id=1}}",
|
||||
),
|
||||
(
|
||||
"post",
|
||||
"type Post {title:Text unique,author_id:data.user.id}\nseed {{title=\"first\",author_id=1},{title=\"second\",author_id=1},{title=\"third\",author_id=2}}",
|
||||
),
|
||||
] {
|
||||
fs::write(domain.join(format!("data/{name}.dever")), source).unwrap();
|
||||
}
|
||||
write_source(domain.join("app/main.dever"), r#"
|
||||
rule orgName(value:data.organization.Organization?) (out:Text)
|
||||
| value | out |
|
||||
| null | "none" |
|
||||
| other | value.name |
|
||||
rule organization(value:Related<data.organization.Organization?>) (out:Text)
|
||||
| value | out |
|
||||
| Unloaded | "unloaded" |
|
||||
| Loaded(row) | orgName(row) |
|
||||
rule posts(value:Related<List<data.post.Post>>) (out:Int)
|
||||
| value | out |
|
||||
| Unloaded | -1 |
|
||||
| Loaded(rows) | length(rows) |
|
||||
rule takePosts(value:Related<List<data.post.Post>>) (out:List<data.post.Post>)
|
||||
| value | out |
|
||||
| Unloaded | [] |
|
||||
| Loaded(rows) | rows |
|
||||
loop titles(rows:List<data.post.Post>) (out:List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list row.title |
|
||||
rule managerName(value:Related<data.user.User?>) (out:Text)
|
||||
| value | out |
|
||||
| Unloaded | "unloaded" |
|
||||
| Loaded(row) | optionalUser(row) |
|
||||
rule optionalUser(value:data.user.User?) (out:Text)
|
||||
| value | out |
|
||||
| null | "none" |
|
||||
| other | value.name+":"+organization(value.organization) |
|
||||
flow owned() (names:List<Text>, copies:List<Text>, manager:Text)
|
||||
| step | kind | do |
|
||||
| first | data | data.user.get(name=="Ada", with = [posts]) |
|
||||
| last | data | data.user.first(name=="Ben", with = [manager]) |
|
||||
| - | check | last != null else NotFound |
|
||||
| names | loop | titles(takePosts(first.posts)) |
|
||||
| copies | loop | titles(takePosts(first.posts)) |
|
||||
| manager | rule | managerName(last.manager) |
|
||||
show(value:data.user.User) (out:Text) {out=value.name+":"+organization(value.organization)+":"+int.toText(posts(value.posts))}
|
||||
loop labels(rows:List<data.user.User>) (out:List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list show(row) |
|
||||
flow plain() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| page | data | data.user.page(order = id.asc, size = 2) |
|
||||
| out | loop | labels(page.items) |
|
||||
flow users() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | data | data.user.page(order = id.asc, size = 2, with = [organization,manager,posts]).items |
|
||||
| out | loop | labels(rows) |
|
||||
flow first() (out:Text)
|
||||
| step | kind | do |
|
||||
| user | data | data.user.first(order = id.asc, with = [organization,posts]) |
|
||||
| - | check | user != null else NotFound |
|
||||
| out | calc | show(user) |
|
||||
flow cursor() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| first | data | data.user.cursor(order = id.asc, size = 1, with = [organization,posts]) |
|
||||
| next | data | data.user.cursor(order = id.asc, size = 1, after = first.next, with = [organization,posts]) |
|
||||
| out | loop | labels(next.items) |
|
||||
flow empty() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| page | data | data.user.page(name=="missing", size = 2, with = [organization,posts]) |
|
||||
| out | loop | labels(page.items) |
|
||||
echo(value:data.user.User) (out:data.user.User) {out=value}
|
||||
decoded(value:data.user.User) (out:Text) {out=show(value)}
|
||||
flow plainRows() (out:data.user.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.user.page(order = id.asc, size = 2) |
|
||||
flow loadedRows() (out:data.user.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.user.page(order = id.asc, size = 2, with = [organization,manager,posts]) |
|
||||
flow post() (out:data.post.Post?)
|
||||
| step | kind | do |
|
||||
| out | data | data.post.first(title=="first", with = [author]) |
|
||||
"#).unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd plain=app.plain\ncmd users=app.users\ncmd first=app.first\ncmd cursor=app.cursor\ncmd empty=app.empty\ncmd owned=app.owned\ncmd echo=app.echo\ncmd decoded=app.decoded\ncmd plainRows=app.plainRows\ncmd loadedRows=app.loadedRows\ncmd post=app.post").unwrap();
|
||||
fs::create_dir_all(domain.join("api/front")).unwrap();
|
||||
fs::write(domain.join("api/front/wire.dever"), "public post echo=app.echo\npublic get plainRows=app.plainRows\npublic get loadedRows=app.loadedRows\npublic get post=app.post").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (config, port, mut settings) = crate::api::config(&root);
|
||||
settings["database"] = serde_json::json!({"default":database});
|
||||
fs::write(&config, settings.to_string()).unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
let binary = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&binary.binary)
|
||||
.args(["--config", config.to_str().unwrap(), "migrate"])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let call = |name: &str| {
|
||||
Command::new(&binary.binary)
|
||||
.args([
|
||||
"--config",
|
||||
config.to_str().unwrap(),
|
||||
&format!("demo.people.{name}"),
|
||||
"{}",
|
||||
])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let data = |name: &str| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name))).unwrap()["data"].clone()
|
||||
};
|
||||
assert_eq!(
|
||||
data("plain"),
|
||||
serde_json::json!(["Ada:unloaded:-1", "Ben:unloaded:-1"])
|
||||
);
|
||||
assert_eq!(
|
||||
data("users"),
|
||||
serde_json::json!(["Ada:Team:2", "Ben:none:1"])
|
||||
);
|
||||
assert_eq!(data("first"), "Ada:Team:2");
|
||||
assert_eq!(data("cursor"), serde_json::json!(["Ben:none:1"]));
|
||||
assert_eq!(data("empty"), serde_json::json!([]));
|
||||
assert_eq!(
|
||||
data("owned"),
|
||||
serde_json::json!({"names":["second","first"],"copies":["second","first"],"manager":"Ada:unloaded"})
|
||||
);
|
||||
wire_contract(&binary.binary, &config, port, data);
|
||||
database["max_page_size"] = 1.into();
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!call("first").status.success());
|
||||
}
|
||||
|
||||
fn wire_contract(
|
||||
binary: &Path,
|
||||
config: &Path,
|
||||
port: u16,
|
||||
data: impl Fn(&str) -> serde_json::Value,
|
||||
) {
|
||||
let page = data("plainRows");
|
||||
assert_eq!(page, data("loadedRows"));
|
||||
let user = &page["items"][0];
|
||||
let keys = user
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
"created_at",
|
||||
"extra",
|
||||
"id",
|
||||
"manager_id",
|
||||
"name",
|
||||
"organization_id"
|
||||
]
|
||||
);
|
||||
assert_eq!(user["extra"], serde_json::json!({"x":1}));
|
||||
assert!(page["items"][1]["organization_id"].is_null());
|
||||
let input = serde_json::json!({"value":user});
|
||||
let echo = |name: &str, value: &serde_json::Value| {
|
||||
Command::new(binary)
|
||||
.args([
|
||||
"--config",
|
||||
config.to_str().unwrap(),
|
||||
&format!("demo.people.{name}"),
|
||||
&value.to_string(),
|
||||
])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(echo("echo", &input))).unwrap()["data"],
|
||||
*user
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(echo("decoded", &input))).unwrap()["data"],
|
||||
"Ada:unloaded:-1"
|
||||
);
|
||||
let server = crate::api::Server::start(binary, config, port);
|
||||
for name in ["plainRows", "loadedRows", "post"] {
|
||||
let (status, reply) =
|
||||
server.call("GET", &format!("/demo/people/front/wire/{name}"), "", "");
|
||||
assert_eq!(status, 200, "{reply}");
|
||||
assert_eq!(reply["data"], data(name));
|
||||
}
|
||||
let (status, reply) = server.call(
|
||||
"POST",
|
||||
"/demo/people/front/wire/echo",
|
||||
&input.to_string(),
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{reply}");
|
||||
assert_eq!(reply["data"], *user);
|
||||
for relation in ["organization", "manager", "posts"] {
|
||||
for state in [
|
||||
serde_json::json!("Unloaded"),
|
||||
serde_json::json!({"Loaded":null}),
|
||||
] {
|
||||
let mut input = input.clone();
|
||||
input["value"][relation] = state;
|
||||
assert!(!echo("echo", &input).status.success());
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/people/front/wire/echo",
|
||||
&input.to_string(),
|
||||
"Content-Type: application/json\r\n"
|
||||
)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relation_contract_rejects_invalid_declarations_queries_and_explicit_wire_relations() {
|
||||
let root = project(
|
||||
"model-relation-contract",
|
||||
"flow read() (out:Int)\n| step | kind | do |\n| out | data | data.count() |",
|
||||
);
|
||||
let article = root.join("module/demo/article/data/main.dever");
|
||||
let user = root.join("module/demo/user/data/main.dever");
|
||||
let app = root.join("module/demo/article/app/main.dever");
|
||||
let base = "type Article {title:Text, author_id:demo.user.data.id}";
|
||||
write_source(&article, base).unwrap();
|
||||
for query in [
|
||||
"data.page(with = [unknown])",
|
||||
"data.page(with = [author,author])",
|
||||
"data.page(with = [author.name])",
|
||||
"data.page(with = author)",
|
||||
"data.count(with = [author])",
|
||||
"data.list(page = 1)",
|
||||
"data.page(limit = 3)",
|
||||
"data.list(limit = 1, limit = 2)",
|
||||
"data.get()",
|
||||
"data.get(order = id.asc)",
|
||||
"data.get(with = [author])",
|
||||
"data.create({title=\"x\",author_id=1,author=Unloaded})",
|
||||
] {
|
||||
write_source(
|
||||
&app,
|
||||
format!("flow read() ()\n| step | kind | do |\n| - | data | {query} |"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"accepted {query}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
&app,
|
||||
"flow read() (out:data.Article?)\n| step | kind | do |\n| out | data | data.first() |",
|
||||
)
|
||||
.unwrap();
|
||||
for model in [
|
||||
"type Article {title:Text,author:Text,author_id:demo.user.data.id}",
|
||||
"type Article {title:Text}\nrelation users = demo.user.data.name",
|
||||
"type Article {title:Text}\nrelation users = demo.user.data.missing",
|
||||
] {
|
||||
write_source(&article, model).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"accepted {model}"
|
||||
);
|
||||
}
|
||||
write_source(&article, base).unwrap();
|
||||
write_source(&user, "database archive\ntype User {name:Text}").unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
write_source(&user, "type User {name:Text}").unwrap();
|
||||
write_source(
|
||||
&app,
|
||||
"echo(value:Related<demo.user.data.User>) (out:Related<demo.user.data.User>) {out=value}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd echo=app.echo",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("relation"), "{error:?}");
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_streams_propagate_driver_errors_and_consume_rows_in_loops() {
|
||||
exercise(
|
||||
"model-stream",
|
||||
serde_json::json!({"type":"sqlite","path":"data/model.db","max_connections":1}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_model_streams() {
|
||||
exercise(
|
||||
"model-stream-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":1}),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, database: serde_json::Value) {
|
||||
let app = r#"
|
||||
flow rows(keyword: Text) (out: AsyncStream<data.Article>)
|
||||
| step | kind | do |
|
||||
| out | data | data.stream(title.contains(keyword), order = id.asc) |
|
||||
loop titles(rows: AsyncStream<data.Article>) (out: List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list row.title |
|
||||
loop first(rows: AsyncStream<data.Article>) (out: Text?)
|
||||
| each row in rows | result |
|
||||
| out | first row.title |
|
||||
loop parallelTitles(rows: AsyncStream<data.Article>) (out: List<Text>)
|
||||
| each row in rows parallel(2) | result |
|
||||
| out | list row.title |
|
||||
flow list(keyword: Text) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | flow | rows(keyword) |
|
||||
| out | loop | titles(rows) |
|
||||
flow parallelList(keyword: Text) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | flow | rows(keyword) |
|
||||
| out | loop | parallelTitles(rows) |
|
||||
flow firstThenCount(keyword: Text) (first: Text?, count: Int)
|
||||
| step | kind | do |
|
||||
| rows | flow | rows(keyword) |
|
||||
| first | loop | first(rows) |
|
||||
| count | data | data.count() |
|
||||
flow fromList(value: data.Article) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | calc | stream([value]) |
|
||||
| out | loop | titles(rows) |
|
||||
"#;
|
||||
let root = project(name, app);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article {title:Text unique}\nseed {{title=\"first\"},{title=\"second\"},{title=\"third\"}}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd list = app.list\ncmd parallelList = app.parallelList\ncmd firstThenCount = app.firstThenCount\ncmd fromList = app.fromList").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for entry in ["list", "parallelList"] {
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
&format!("demo.article.{entry}"),
|
||||
r#"{"keyword":""}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response["data"],
|
||||
serde_json::json!(["first", "second", "third"])
|
||||
);
|
||||
}
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.firstThenCount",
|
||||
r#"{"keyword":""}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response["data"],
|
||||
serde_json::json!({"first":"first","count":3})
|
||||
);
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.list",
|
||||
r#"{"keyword":"missing"}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(response["data"], serde_json::json!([]));
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.fromList",
|
||||
r#"{"value":{"id":1,"created_at":"2026-11-12T00:00:00Z","title":"local"}}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(response["data"], serde_json::json!(["local"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_creation_and_consumption_are_rejected_in_transaction_flows() {
|
||||
let root = project(
|
||||
"model-stream-transaction",
|
||||
"transaction flow rows() (out: AsyncStream<data.Article>)\n| step | kind | do |\n| out | data | data.stream() |",
|
||||
);
|
||||
let project = Project::load(&root).unwrap();
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C013");
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_methods_apply_text_rules_by_column() {
|
||||
let root = directory("data-text-conditions");
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(domain.join("data/article.dv"), "type Article {title: Text(2,12) lower, code: Text? upper, label: Text, signature: Text raw}").unwrap();
|
||||
write_source(domain.join("flow/article.dv"), r#"
|
||||
flow probe(term: Text, code: Text?, missing: Text?) (stored: Text, hit: Bool, kept: Bool, optional: Bool, skipped: Bool, fragment: Bool, short: Bool, updated: Int, removed: Int) {
|
||||
row = data.create({title = term, code = code, label = " Label ", signature = " Raw "})
|
||||
stored = row.title
|
||||
hit = data.exists(title == term and code == code and label == " Label ")
|
||||
kept = data.exists(signature == " Raw " and signature != "Raw")
|
||||
optional = data.exists(ifSet(title == code))
|
||||
skipped = data.exists(ifSet(title == missing))
|
||||
fragment = data.exists(title.contains(" É "))
|
||||
short = data.exists(title == " ")
|
||||
terms = [term, "Other"]
|
||||
updated = data.update({where = in(title, terms)}, {code = missing})
|
||||
removed = data.delete({where = title == term and code == missing})
|
||||
}
|
||||
"#).unwrap();
|
||||
write_source(domain.join("api/article.dv"), "cmd probe = app.probe").unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
write_source(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/probe.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let binary = build::build(&loaded, &program, "main", Profile::Dev, None)
|
||||
.unwrap()
|
||||
.binary;
|
||||
let run = |args: &[&str]| {
|
||||
success(
|
||||
Command::new(&binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
run(&["migrate"]);
|
||||
let out: serde_json::Value = serde_json::from_str(&run(&[
|
||||
"demo.article.probe",
|
||||
r#"{"term":" Écho ","code":" éCHO ","missing":null}"#,
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out["data"],
|
||||
serde_json::json!({"stored":"écho","hit":true,"kept":true,"optional":true,"skipped":true,"fragment":false,"short":false,"updated":1,"removed":1})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_text_input_normalizes_before_the_function_body() {
|
||||
let root = project(
|
||||
"data-text-input",
|
||||
"flow checkName(account:data.title, password:Text) (name:Text, original:Text) { name = account\noriginal = password }",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article {title:Text(1,4) lower unique}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd account = app.checkName",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.args([
|
||||
"demo.article.account",
|
||||
&serde_json::json!({"account":name,"password":" XyZ "}).to_string(),
|
||||
])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let value: serde_json::Value = serde_json::from_str(&success(call(" É雪 "))).unwrap();
|
||||
assert_eq!(
|
||||
value["data"],
|
||||
serde_json::json!({"name":"é雪","original":" XyZ "})
|
||||
);
|
||||
for invalid in [" ", "12345"] {
|
||||
let error = call(invalid);
|
||||
assert!(!error.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&error.stdout).contains("Invalid")
|
||||
|| String::from_utf8_lossy(&error.stderr).contains("Invalid"),
|
||||
"{:?}",
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_bytes_move_owned_buffers_and_preserve_shared_inputs() {
|
||||
bytes_storage(serde_json::json!({"type":"sqlite","path":"data/model.db"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_model_bytes_preserve_owned_shared_and_optional_values() {
|
||||
bytes_storage(serde_json::json!({
|
||||
"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),
|
||||
"tls":"disabled","max_connections":1
|
||||
}));
|
||||
}
|
||||
|
||||
fn bytes_storage(database: serde_json::Value) {
|
||||
let root = project(
|
||||
"model-bytes-storage",
|
||||
r#"
|
||||
flow save(text: Text) (out: Text)
|
||||
| step | kind | do |
|
||||
| content | calc | dever.bytes.fromText(text) |
|
||||
| row | data | data.create({content = content, optional = null}) |
|
||||
| out | calc | dever.bytes.toText(row.content) |
|
||||
flow copy(article_id: data.id) (out: Text, original: Text, optional: Text)
|
||||
| step | kind | do |
|
||||
| source | data | data.get(article_id) |
|
||||
| row | data | data.create({content = source.content, optional = source.content}) |
|
||||
| optional_content | calc | row.optional |
|
||||
| - | check | optional_content != null else NotFound |
|
||||
| out | calc | dever.bytes.toText(row.content) |
|
||||
| original | calc | dever.bytes.toText(source.content) |
|
||||
| optional | calc | dever.bytes.toText(optional_content) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article {content:Bytes(0,65536),optional:Bytes?}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd save = app.save\ncmd copy = app.copy",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
assert!(
|
||||
generated
|
||||
.values()
|
||||
.all(|file| !file.text.contains("value.to_vec()"))
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |arguments: &[&str]| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(arguments)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(call(&["migrate"]));
|
||||
for text in ["".to_owned(), "雪🙂\0".repeat(4096)] {
|
||||
let input = serde_json::json!({"text":text}).to_string();
|
||||
let out: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&["demo.article.save", &input]))).unwrap();
|
||||
assert_eq!(out["data"], text);
|
||||
}
|
||||
let copied: serde_json::Value = serde_json::from_str(&success(call(&[
|
||||
"demo.article.copy",
|
||||
r#"{"article_id":2}"#,
|
||||
])))
|
||||
.unwrap();
|
||||
for field in ["out", "original", "optional"] {
|
||||
assert_eq!(copied["data"][field], "雪🙂\0".repeat(4096));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_writes_use_proven_ranges_and_still_reject_unknown_invalid_values() {
|
||||
let root = project(
|
||||
"model-proven-ranges",
|
||||
r#"
|
||||
flow known(amount: Int >= 0 and <= 10, flag: Bool?, note: Text?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({amount = amount, flag = flag, note = note}) |
|
||||
flow copy(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| row | data | data.get(article_id) |
|
||||
| out | data | data.create({amount = row.amount, flag = row.flag, note = row.note}) |
|
||||
flow unknown(amount: Int) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({amount = amount}) |
|
||||
flow defaultAmount() (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({}) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { amount: Int >= 0 and <= 10 default 7, flag: Bool?, note: Text? raw }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd known = app.known\ncmd copy = app.copy\ncmd unknown = app.unknown\ncmd defaultAmount = app.defaultAmount\ncmd count = app.count",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
assert_eq!(
|
||||
generated
|
||||
.values()
|
||||
.map(|file| file
|
||||
.text
|
||||
.matches("Model field amount is out of range")
|
||||
.count())
|
||||
.sum::<usize>(),
|
||||
1,
|
||||
"only the unconstrained input needs a Model range check"
|
||||
);
|
||||
assert!(generated.values().all(|file| {
|
||||
!file
|
||||
.text
|
||||
.contains("value.map(|value| -> Result<_,dever_runtime::database::Error>")
|
||||
}));
|
||||
assert!(
|
||||
generated
|
||||
.values()
|
||||
.all(|file| !file.text.contains("text::TextMode::Raw"))
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
for (amount, flag, note) in [(0, None, None), (10, Some(true), Some(" 原文 "))] {
|
||||
let input = serde_json::json!({"amount":amount,"flag":flag,"note":note});
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call("known", &input.to_string()))).unwrap();
|
||||
assert_eq!(output["data"]["amount"], amount);
|
||||
assert_eq!(output["data"]["flag"], input["flag"]);
|
||||
assert_eq!(output["data"]["note"], input["note"]);
|
||||
}
|
||||
let copied: serde_json::Value =
|
||||
serde_json::from_str(&success(call("copy", r#"{"article_id":2}"#))).unwrap();
|
||||
assert_eq!(copied["data"]["amount"], 10);
|
||||
assert_eq!(copied["data"]["flag"], true);
|
||||
assert_eq!(copied["data"]["note"], " 原文 ");
|
||||
assert!(success(call("defaultAmount", "{}")).contains(r#""amount":7"#));
|
||||
for name in ["known", "unknown"] {
|
||||
for amount in [-1, 11] {
|
||||
let output = call(name, &format!(r#"{{"amount":{amount}}}"#));
|
||||
assert!(!output.status.success(), "{name} accepted {amount}");
|
||||
assert!(!output.stderr.is_empty());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!call("known", r#"{"amount":1,"flag":"true"}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(success(call("count", "{}")).contains(r#""data":4"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_defaults_share_the_runtime_validation_contract() {
|
||||
let root = project("invalid-json-defaults", "");
|
||||
for raw in [
|
||||
"{".to_owned(),
|
||||
r#"{"a":1,"\u0061":2}"#.to_owned(),
|
||||
format!("{}0{}", "[".repeat(65), "]".repeat(65)),
|
||||
format!("[{}0]", "0,".repeat(65_536)),
|
||||
] {
|
||||
let literal = serde_json::to_string(&raw).unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
format!("type Article {{content:Json default {literal}}}"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("JSON"), "{}", error.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_storage_preserves_precision_order_and_json_original_text() {
|
||||
let root = project(
|
||||
"model-scalars-native",
|
||||
r#"
|
||||
flow create(amount: Decimal, discount: Decimal?, content: Json) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({amount = amount, discount = discount, content = content}) |
|
||||
flow list(minimum: Decimal) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(amount >= minimum, order = amount.asc) |
|
||||
flow count(amount: Decimal) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count(amount == amount) |
|
||||
flow change(article_id: data.id, discount: Decimal?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.update(article_id,{discount = discount}) |
|
||||
"#,
|
||||
);
|
||||
write_source(root.join("module/demo/article/data/main.dever"), r#"type Article { amount: Decimal(34,2), discount: Decimal(8,2)?, content: Json, extra: Json? default "{ \"large\":1e9999 }" }"#).unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd create = app.create\ncmd list = app.list\ncmd count = app.count\ncmd change = app.change").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for amount in [
|
||||
"-10.25",
|
||||
"0.00",
|
||||
"2.01",
|
||||
"99999999999999999999999999999999.99",
|
||||
] {
|
||||
let input = format!(
|
||||
r#"{{"amount":"{amount}","discount":null,"content": {{ "large":1e9999, "text":"原文" }} }}"#
|
||||
);
|
||||
let out = success(call("create", &input));
|
||||
assert!(out.contains(r#"{ "large":1e9999 }"#), "{out}");
|
||||
assert!(
|
||||
out.contains(r#"{ "large":1e9999, "text":"原文" }"#),
|
||||
"{out}"
|
||||
);
|
||||
}
|
||||
for amount in ["1.001", "100000000000000000000000000000000"] {
|
||||
assert!(
|
||||
!call(
|
||||
"create",
|
||||
&format!(r#"{{"amount":"{amount}","discount":null,"content":null}}"#)
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
let page = success(call("list", r#"{"minimum":"-100"}"#));
|
||||
// 使用原文检查,避免测试端 JSON 库把高精度内容变成 Float。
|
||||
assert!(page.contains(r#""total":4"#), "{page}");
|
||||
let positions = [
|
||||
"-10.25",
|
||||
"\"0\"",
|
||||
"2.01",
|
||||
"99999999999999999999999999999999.99",
|
||||
]
|
||||
.map(|value| page.find(value).unwrap());
|
||||
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]));
|
||||
assert!(success(call("count", r#"{"amount":"2.01"}"#)).contains(r#""data":1"#));
|
||||
let changed = success(call("change", r#"{"article_id":1,"discount":"3.50"}"#));
|
||||
assert!(changed.contains(r#""discount":"3.5""#), "{changed}");
|
||||
assert!(
|
||||
!call("change", r#"{"article_id":1,"discount":"3.501"}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
success(call("change", r#"{"article_id":1,"discount":null}"#))
|
||||
.contains(r#""discount":null"#)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn transaction_flow_preserves_syntax_and_inspection_and_allows_clock_reads() {
|
||||
let root = project(
|
||||
"transaction-clock",
|
||||
"transaction flow stamp() (out: DateTime)\n| step | kind | do |\n| out | flow | dever.time.now() |\ntransaction flow nested() (out: DateTime)\n| step | kind | do |\n| out | flow | stamp() |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.article.app.nested",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(run(&artifact.binary).starts_with("DateTime("));
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
assert!(
|
||||
fs::read_to_string(root.join("module/demo/article/app/main.dever"))
|
||||
.unwrap()
|
||||
.contains("transaction flow stamp")
|
||||
);
|
||||
let inspection: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path,
|
||||
"--json",
|
||||
"--symbol",
|
||||
"demo.article.app.stamp",
|
||||
"--depth",
|
||||
"0",
|
||||
])))
|
||||
.unwrap();
|
||||
assert!(inspection["flows"].as_array().unwrap().iter().any(|flow| {
|
||||
flow["nodes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|node| node["kind"] == "transaction")
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_rejects_effects_through_subflows_and_static_handlers() {
|
||||
let root = project("transaction-effects", "");
|
||||
for body in [
|
||||
"transaction flow waitFor() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |",
|
||||
"flow waitFor() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\ntransaction flow wrapped() ()\n| step | kind | do |\n| - | flow | waitFor() |",
|
||||
"flow waitFor() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\ntransaction flow wrapped(action: handler() ()) ()\n| step | kind | do |\n| - | calc | action() |\nflow start() ()\n| step | kind | do |\n| - | flow | wrapped(waitFor) |",
|
||||
"transaction flow random() (out: Secret)\n| step | kind | do |\n| out | flow | dever.crypto.token(32) |",
|
||||
"transaction flow hash(password: Secret) (out: Text)\n| step | kind | do |\n| out | flow | dever.crypto.passwordHash(password) |",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), body).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
let analysis = program::analyze(&loaded.declarations, &loaded.modules);
|
||||
assert!(
|
||||
analysis
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|error| error.message.contains("transaction flow cannot")),
|
||||
"{:?}",
|
||||
analysis.diagnostics
|
||||
);
|
||||
}
|
||||
for body in [
|
||||
"transaction rule wrong(value: Int) (out: Int)",
|
||||
"transaction plain() () {}",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), body).unwrap();
|
||||
assert!(!Project::load(&root).unwrap().diagnostics.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn batch_upsert_generated_values_and_captured_database_errors_execute() {
|
||||
let root = project(
|
||||
"model-writes-native",
|
||||
r#"
|
||||
flow seed() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.createMany([{ title = " First% ", code = "first" }, { code = "second", title = "Second_" }]) |
|
||||
flow empty() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.createMany([]) |
|
||||
flow batchConflict() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.createMany([{ title = "must roll back", code = "third" }, { title = "duplicate", code = "first" }]) |
|
||||
flow save(code: Text?, title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.upsert({code = code}, {title = title}, {title = title}) |
|
||||
flow keep(code: Text?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.upsert({code = code}, {title = "created"}, {}) |
|
||||
flow find(needle: Text) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(title.contains(needle), order = id.asc) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
type Read { Found(value: data.Article), error Storage(value: dever.database.Error) }
|
||||
rule present(value: Read) (out: Bool) recover("记录不存在时报告查询失败")
|
||||
| value | out |
|
||||
| Found(article) | true |
|
||||
| Storage(error) | false |
|
||||
flow captured(article_id: data.id) (out: Bool)
|
||||
| step | kind | do |
|
||||
| read: Read | data | result(data.get(article_id)) |
|
||||
| out | rule | present(read) |
|
||||
checkedTitle(value:Text) (out:Text) {
|
||||
check length(value) > 0 else Invalid
|
||||
out = value
|
||||
}
|
||||
flow caughtTitle(title: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| saved: Read | data | result(data.create({title = checkedTitle(title)})) |
|
||||
| out | rule | present(saved) |
|
||||
flow caughtSave(code: Text?, title: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| saved: Read | data | result(data.upsert({code = code},{title = title},{})) |
|
||||
| out | rule | present(saved) |
|
||||
flow calendar(code: Text, day: Date, clock: Time, moment: DateTime, tag: Uuid?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = code, code = code, day = day, clock = clock, moment = moment, tag = tag}) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
r#"
|
||||
type Article {
|
||||
title: Text(1, 120)
|
||||
code: Text? unique
|
||||
token: Uuid generated unique
|
||||
day: Date?
|
||||
clock: Time?
|
||||
moment: DateTime?
|
||||
tag: Uuid?
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd seed = app.seed\ncmd empty = app.empty\ncmd batchConflict = app.batchConflict\ncmd save = app.save\ncmd keep = app.keep\ncmd find = app.find\ncmd count = app.count\ncmd captured = app.captured\ncmd calendar = app.calendar\ncmd caughtSave = app.caughtSave\ncmd caughtTitle = app.caughtTitle").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let data = |name: &str, input: serde_json::Value| {
|
||||
let output = success(call(name, input));
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"].clone()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(data("seed", serde_json::json!({})), 2);
|
||||
assert_eq!(data("empty", serde_json::json!({})), 0);
|
||||
assert!(
|
||||
!call("batchConflict", serde_json::json!({}))
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(data("count", serde_json::json!({})), 2);
|
||||
let first = data("find", serde_json::json!({"needle":"%"}));
|
||||
assert_eq!(first["total"], 1);
|
||||
assert_eq!(first["items"][0]["title"], "First%");
|
||||
let first = &first["items"][0];
|
||||
assert_eq!(first["token"].as_str().unwrap().chars().nth(14), Some('7'));
|
||||
let updated = data(
|
||||
"save",
|
||||
serde_json::json!({"code":"first","title":" changed "}),
|
||||
);
|
||||
assert_eq!(updated["id"], first["id"]);
|
||||
assert_eq!(updated["token"], first["token"]);
|
||||
assert_eq!(updated["created_at"], first["created_at"]);
|
||||
assert_eq!(updated["title"], "changed");
|
||||
assert_eq!(data("keep", serde_json::json!({"code":"first"})), updated);
|
||||
let created = data("keep", serde_json::json!({"code":"new"}));
|
||||
assert_eq!(created["title"], "created");
|
||||
assert_ne!(created["token"], updated["token"]);
|
||||
assert!(
|
||||
!call("save", serde_json::json!({"code":null,"title":"invalid"}))
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(data("count", serde_json::json!({})), 3);
|
||||
assert_eq!(
|
||||
data("captured", serde_json::json!({"article_id":9999})),
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
data("captured", serde_json::json!({"article_id":updated["id"]})),
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"caughtSave",
|
||||
serde_json::json!({"code":null,"title":"handled failure"})
|
||||
),
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"caughtSave",
|
||||
serde_json::json!({"code":"first","title":"unchanged"})
|
||||
),
|
||||
true
|
||||
);
|
||||
let invalid = call("caughtTitle", serde_json::json!({"title":""}));
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("Invalid"));
|
||||
assert!(!String::from_utf8_lossy(&invalid.stderr).contains("InvalidData"));
|
||||
assert_eq!(
|
||||
data("caughtTitle", serde_json::json!({"title":"正常实参"})),
|
||||
true
|
||||
);
|
||||
let calendar = data(
|
||||
"calendar",
|
||||
serde_json::json!({"code":"calendar","day":"2026-11-12","clock":"12:34:56","moment":"2026-11-12T12:34:56Z","tag":updated["token"]}),
|
||||
);
|
||||
assert_eq!(calendar["day"], "2026-11-12");
|
||||
assert_eq!(calendar["clock"], "12:34:56");
|
||||
assert_eq!(calendar["moment"], "2026-11-12T12:34:56Z");
|
||||
assert_eq!(calendar["tag"], updated["token"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_rejects_invalid_storage_and_defaults_before_native_compilation() {
|
||||
let root = project(
|
||||
"model-invalid-storage",
|
||||
"copy(value: data.Article) (out: data.Article) { out = value }",
|
||||
);
|
||||
for model in [
|
||||
"type Article { title: Text default -1 }",
|
||||
"type Article { title: Text(2,10) default \" x \" }",
|
||||
"type Article { title: Text(2,10) upper default \"ß\" }", // expands to SS and is valid below
|
||||
"type Article { values: List<Int> }",
|
||||
"type Article { key: Uuid? generated }",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/data/main.dever"), model).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let result = program::check(&loaded.declarations, &loaded.modules);
|
||||
if model.contains("ß") {
|
||||
assert!(result.is_ok());
|
||||
} else {
|
||||
assert!(result.is_err(), "{model}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user