Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -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"));
|
||||
}
|
||||
Reference in new issue
Block a user