use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use futures_util::TryStreamExt;
use laravel::Application;
use laravel::config::Env;
use laravel::config::database::{ConnectionConfig, Database};
use laravel::db::sqlx::AssertSqlSafe;
use laravel::db::{self, AnyConnection, Builder, DatabaseManager, Direction, Driver, Value, col, values};
use laravel::numeric::Decimal;
use serde_json::json;
fn connect(url: &str) -> AnyConnection {
DatabaseManager::new(&Database::default(), "/tmp")
.connect(ConnectionConfig::new(url))
.unwrap()
}
fn sqlite() -> AnyConnection {
connect("sqlite::memory:")
}
#[cfg(feature = "database-postgres")]
fn postgres() -> AnyConnection {
connect("postgres://localhost/laravel")
}
#[cfg(feature = "database-mysql")]
fn mysql() -> AnyConnection {
connect("mysql://localhost/laravel")
}
#[cfg(feature = "database-mysql")]
fn mariadb() -> AnyConnection {
connect("mariadb://localhost/laravel")
}
#[track_caller]
fn assert_sql(query: &Builder, sql: &str, bindings: &[Value<'static>]) {
let compiled = query.to_sql().unwrap();
assert_eq!(compiled.text(), sql);
assert_eq!(compiled.bindings(), bindings);
}
#[track_caller]
fn assert_error(query: &Builder, message: &str) {
assert_eq!(query.to_sql().unwrap_err().to_string(), message);
}
async fn written_sql<T>(
connection: &AnyConnection,
write: impl AsyncFnOnce(&AnyConnection) -> laravel::Result<T>,
) -> Vec<String> {
let statements = Arc::new(Mutex::new(Vec::new()));
let captured = Arc::clone(&statements);
connection.before_executing(move |query| {
captured.lock().unwrap().push(query.sql.clone());
Err(laravel::abort_with(500, "captured"))
});
assert!(write(connection).await.is_err());
statements.lock().unwrap().clone()
}
fn value(value: impl Into<Value<'static>>) -> Value<'static> {
value.into()
}
fn text(text: &str) -> Value<'static> {
value(text.to_owned())
}
#[test]
fn borrowed_select_lists_keep_names_aliases_and_expressions() {
let names = vec![String::from("id"), String::from("users.name as author")];
let expressions = [col("votes").sum().alias("total")];
let extra = [String::from("email")];
for query in [
sqlite().table("users").select(&names),
sqlite().table("users").select(names.as_slice()),
] {
assert_sql(
&query.add_select(&extra).add_select(&expressions),
"select `id`, `users`.`name` as `author`, `email`, sum(`votes`) as `total` from `users`",
&[],
);
}
assert_eq!(names, ["id", "users.name as author"]);
}
#[test]
fn filters_order_and_limit_compile_for_sqlite() {
let query = sqlite()
.table("users")
.filter(col("active").eq(true) & col("votes").gt(100))
.order_by(col("created_at").desc())
.order_by("name")
.limit(10);
assert_sql(
&query,
r#"select * from `users` where `active` = ? and `votes` > ? order by `created_at` desc, `name` asc limit 10"#,
&[value(true), value(100)],
);
assert_sql(
&sqlite()
.table("orders")
.order_by(db::raw!("total - discount").desc())
.order_by(db::raw!("id").asc()),
r#"select * from `orders` order by total - discount desc, id asc"#,
&[],
);
assert_sql(
&sqlite()
.table("threads")
.latest(db::raw!("coalesce(last_reply_at, created_at)"))
.oldest(col("id")),
r#"select * from `threads` order by coalesce(last_reply_at, created_at) desc, `id` asc"#,
&[],
);
assert_sql(
&sqlite()
.table("users")
.order_by(col("created_at").desc())
.unordered()
.order_by(db::random()),
r#"select * from `users` order by random() asc"#,
&[],
);
}
#[test]
fn in_order_of_orders_by_each_values_position_for_sqlite() {
assert_sql(
&sqlite()
.table("issues")
.filter(col("votes").gt(1))
.in_order_of("status", ["open", "closed"])
.order_by("id"),
"select * from `issues` where `votes` > ? order by case when `status` = ? then 0 when `status` = ? then 1 \
else 2 end asc, `id` asc",
&[value(1), text("open"), text("closed")],
);
assert_sql(
&sqlite().table("issues").in_order_of("status", Vec::<&str>::new()),
"select * from `issues`",
&[],
);
assert_sql(
&sqlite()
.table("issues")
.in_order_of("status", ["open"])
.unordered()
.order_by(db::random()),
"select * from `issues` order by random() asc",
&[],
);
assert_sql(
&sqlite().table("issues").in_order_of("assignee_id", [None, Some(7)]),
"select * from `issues` order by case when `assignee_id` is null then 0 when `assignee_id` = ? then 1 else 2 end \
asc",
&[value(7)],
);
}
#[test]
fn conditions_group_with_sql_precedence() {
let a = || col("a").eq(1);
let b = || col("b").eq(2);
let c = || col("c").eq(3);
let users = || sqlite().table("users");
assert_sql(
&users().filter(a() & b() | c()),
r#"select * from `users` where (`a` = ? and `b` = ?) or `c` = ?"#,
&[value(1), value(2), value(3)],
);
assert_sql(
&users().filter(a() & (b() | c())),
r#"select * from `users` where `a` = ? and (`b` = ? or `c` = ?)"#,
&[value(1), value(2), value(3)],
);
assert_sql(
&users().filter(a() | b()).filter(c()),
r#"select * from `users` where (`a` = ? or `b` = ?) and `c` = ?"#,
&[value(1), value(2), value(3)],
);
assert_sql(
&users().filter(!(a() | b())),
r#"select * from `users` where not (`a` = ? or `b` = ?)"#,
&[value(1), value(2)],
);
assert_sql(
&users().filter(!!a()),
r#"select * from `users` where `a` = ?"#,
&[value(1)],
);
assert_sql(
&users().filter(a() | (b() & !c())),
r#"select * from `users` where `a` = ? or (`b` = ? and not (`c` = ?))"#,
&[value(1), value(2), value(3)],
);
let views = 5_i64;
assert_sql(
&users().filter((db::raw!("views > {views}") | !db::raw!("hidden")) & a()),
r#"select * from `users` where ((views > ?) or not (hidden)) and `a` = ?"#,
&[value(5_i64), value(1)],
);
let mut combined = a() | db::raw!("b = 2");
combined &= col("active");
combined |= db::raw!("c = 3");
assert_sql(
&users().filter(combined),
r#"select * from `users` where ((`a` = ? or (b = 2)) and `active`) or (c = 3)"#,
&[value(1)],
);
assert_sql(
&users().filter(db::raw!("a = 1 or b = 2")).filter(c()),
r#"select * from `users` where (a = 1 or b = 2) and `c` = ?"#,
&[value(3)],
);
assert_sql(
&users().filter(db::any(Vec::<db::Condition>::new())),
r#"select * from `users` where 0 = 1"#,
&[],
);
assert_sql(
&users().filter(db::all([a(), b()]) | db::any([c()])),
r#"select * from `users` where (`a` = ? and `b` = ?) or `c` = ?"#,
&[value(1), value(2), value(3)],
);
assert_sql(
&users().filter(db::any([Some(a()), None, Some(c())])),
r#"select * from `users` where `a` = ? or `c` = ?"#,
&[value(1), value(3)],
);
assert_sql(
&users()
.filter(None::<db::Condition>)
.filter(db::all([None::<db::Condition>])),
r#"select * from `users` where 1 = 1"#,
&[],
);
}
#[test]
fn null_values_compare_with_is_null() {
let users = || sqlite().table("users");
assert_sql(
&users().filter(col("deleted_at").eq(None::<i64>)),
r#"select * from `users` where `deleted_at` is null"#,
&[],
);
assert_sql(
&users().filter(col("deleted_at").ne(None::<String>)),
r#"select * from `users` where `deleted_at` is not null"#,
&[],
);
assert_sql(
&users().filter(!col("deleted_at").eq(None::<i64>) & !col("verified_at").is_null()),
r#"select * from `users` where `deleted_at` is not null and `verified_at` is not null"#,
&[],
);
let team: Option<i64> = Some(4);
assert_sql(
&users().filter(col("team_id").eq(team)),
r#"select * from `users` where `team_id` = ?"#,
&[value(4_i64)],
);
}
#[test]
fn in_lists_handle_empty_negated_and_borrowed_lists() {
let users = || sqlite().table("users");
let ids = vec![3_i64, 7];
let none: [i64; 0] = [];
assert_sql(
&users().filter(col("id").is_in(&ids)),
r#"select * from `users` where `id` in (?, ?)"#,
&[value(3_i64), value(7_i64)],
);
assert_sql(
&users().filter(!col("id").is_in(["a", "b"])),
r#"select * from `users` where `id` not in (?, ?)"#,
&[text("a"), text("b")],
);
assert_sql(
&users().filter(col("id").is_in(none)),
r#"select * from `users` where 0 = 1"#,
&[],
);
assert_sql(
&users().filter(!col("id").is_in(none) & col("active").eq(true)),
r#"select * from `users` where 1 = 1 and `active` = ?"#,
&[value(true)],
);
assert_eq!(ids, [3, 7]);
}
#[test]
fn between_like_dates_and_arithmetic_compile_for_sqlite() {
let users = || sqlite().table("users");
assert_sql(
&users().filter(col("votes").between(1, col("max_votes")) & !col("age").between(18, 65)),
r#"select * from `users` where `votes` between ? and `max_votes` and `age` not between ? and ?"#,
&[value(1), value(18), value(65)],
);
assert_sql(
&users().filter(col("name").like("%tay%") & !col("email").like("%@spam%")),
r#"select * from `users` where `name` like ? and `email` not like ?"#,
&[text("%tay%"), text("%@spam%")],
);
assert_sql(
&users().filter(col("created_at").date().eq("2024-02-29") & col("created_at").day().eq(5)),
r#"select * from `users` where strftime('%Y-%m-%d', `created_at`) = ? and cast(strftime('%d', `created_at`) as integer) = ?"#,
&[text("2024-02-29"), value(5)],
);
assert_sql(
&users().filter(((col("price") + 1) * col("quantity") - (col("tax") - 2)).gt(0)),
r#"select * from `users` where (`price` + ?) * `quantity` - (`tax` - ?) > ?"#,
&[value(1), value(2), value(0)],
);
let rate = 0.2;
assert_sql(
&users().select([(col("total") * db::raw!("1 - {rate}")).alias("net")]),
r#"select `total` * (1 - ?) as `net` from `users`"#,
&[value(0.2)],
);
let plan = db::table("plans")
.select(["name"])
.filter(col("plans.id").eq(col("users.plan_id")));
assert_sql(
&users().filter(db::expr(plan).eq("Pro") & db::expr(100).between(col("min_price"), col("max_price"))),
r#"select * from `users` where (select `name` from `plans` where `plans`.`id` = `users`.`plan_id`) = ? and ? between `min_price` and `max_price`"#,
&[text("Pro"), value(100)],
);
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn like_and_date_parts_follow_each_dialect() {
let build = |connection: AnyConnection| {
connection.table("users").filter(
col("name").like("%tay%") & col("created_at").date().eq("2024-02-29") & col("created_at").day().eq(5_i64),
)
};
let bindings = [text("%tay%"), text("2024-02-29"), value(5_i64)];
assert_sql(
&build(postgres()),
r#"select * from "users" where "name"::text ilike $1 and "created_at"::date = $2 and extract(day from "created_at")::integer = $3"#,
&bindings,
);
assert_sql(
&build(mysql()),
"select * from `users` where `name` like ? and date(`created_at`) = ? and day(`created_at`) = ?",
&bindings,
);
}
#[test]
fn case_sensitive_like_on_sqlite_needs_a_text_pattern() {
assert_error(
&sqlite()
.table("coupons")
.filter(col("code").like_case_sensitive(col("prefix"))),
"a case-sensitive `like` on SQLite needs a text pattern, not a column or SQL",
);
}
#[cfg(feature = "database-postgres")]
#[test]
fn subquery_bindings_follow_their_placeholders_across_clauses() {
let following = db::table("follows")
.select(["followed_id"])
.filter(col("follower_id").eq(7_i64));
let comments = db::table("comments").select(["post_id"]).filter(col("spam").eq(false));
let posts = postgres()
.table("posts")
.join(
"users",
col("users.id").eq(col("posts.user_id")) & col("users.kind").eq("author"),
)
.join(db::sub(comments, "c"), col("c.post_id").eq(col("posts.id")))
.filter(col("posts.user_id").is_in(following))
.filter(col("posts.votes").gt(10_i64))
.group_by(["posts.id"])
.having(col("*").count().gt(2_i64));
let query = db::union([posts, db::table("archived_posts").filter(col("year").eq(2020_i64))])
.order_by(col("votes").desc())
.limit(5);
assert_sql(
&query,
concat!(
r#"(select * from "posts" inner join "users" on "users"."id" = "posts"."user_id" and "users"."kind" = $1 "#,
r#"inner join (select "post_id" from "comments" where "spam" = $2) as "c" on "c"."post_id" = "posts"."id" "#,
r#"where "posts"."user_id" in (select "followed_id" from "follows" where "follower_id" = $3) and "posts"."votes" > $4 "#,
r#"group by "posts"."id" having count(*) > $5) "#,
r#"union (select * from "archived_posts" where "year" = $6) order by "votes" desc limit 5"#,
),
&[
text("author"),
value(false),
value(7_i64),
value(10_i64),
value(2_i64),
value(2020_i64),
],
);
assert_sql(
&postgres()
.table(db::sub(db::table("users").filter(col("id").eq(1_i64)), "u"))
.filter(
db::exists(db::table("posts").filter(col("posts.user_id").eq(col("u.id")))) & col("u.votes").gt(2_i64),
),
r#"select * from (select * from "users" where "id" = $1) as "u" where exists (select * from "posts" where "posts"."user_id" = "u"."id") and "u"."votes" > $2"#,
&[value(1_i64), value(2_i64)],
);
}
#[cfg(feature = "database-postgres")]
#[test]
fn raw_fragments_number_postgres_placeholders_in_order() {
let (factor, minimum, statuses) = (2_i64, 100_i64, ["paid", "shipped"]);
let query = postgres()
.table("orders")
.select((col("id"), db::raw!("total * {factor}").alias("doubled")))
.filter(col("region").eq("eu"))
.filter(db::raw!("total * {factor} > {minimum} and status in ({...statuses})"))
.filter(db::raw!(AssertSqlSafe("tags ? 'gift'")));
assert_sql(
&query,
r#"select "id", total * $1 as "doubled" from "orders" where "region" = $2 and (total * $3 > $4 and status in ($5, $6)) and (tags ? 'gift')"#,
&[
value(2_i64),
text("eu"),
value(2_i64),
value(100_i64),
text("paid"),
text("shipped"),
],
);
let none: [&str; 0] = [];
assert_error(
&postgres().table("orders").filter(db::raw!("status in ({...none})")),
"a `{...values}` list in `db::raw!` is empty",
);
}
#[test]
fn offsets_without_limits_and_pages_compile_for_sqlite() {
assert_sql(
&sqlite().table("users").offset(5),
r#"select * from `users` limit -1 offset 5"#,
&[],
);
assert_sql(
&sqlite().table("users").for_page(3, 15),
r#"select * from `users` limit 15 offset 30"#,
&[],
);
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn offsets_without_limits_follow_each_dialect() {
assert_sql(
&postgres().table("users").offset(5),
r#"select * from "users" offset 5"#,
&[],
);
assert_sql(
&mysql().table("users").offset(5),
"select * from `users` limit 18446744073709551615 offset 5",
&[],
);
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn locks_follow_each_dialect_and_sqlite_omits_them() {
let accounts = |connection: AnyConnection| connection.table("accounts").filter(col("id").eq(1_i64));
assert_sql(
&accounts(postgres()).lock_for_update(),
r#"select * from "accounts" where "id" = $1 for update"#,
&[value(1_i64)],
);
assert_sql(
&accounts(postgres()).shared_lock(),
r#"select * from "accounts" where "id" = $1 for share"#,
&[value(1_i64)],
);
assert_sql(
&accounts(mysql()).lock_for_update(),
"select * from `accounts` where `id` = ? for update",
&[value(1_i64)],
);
assert_sql(
&accounts(mysql()).shared_lock(),
"select * from `accounts` where `id` = ? lock in share mode",
&[value(1_i64)],
);
assert_sql(
&accounts(sqlite()).lock_for_update(),
r#"select * from `accounts` where `id` = ?"#,
&[value(1_i64)],
);
for (connection, sql) in [
(
postgres(),
r#"select * from "accounts" where "id" = $1 for update skip locked"#,
),
(
mysql(),
"select * from `accounts` where `id` = ? for update skip locked",
),
(sqlite(), "select * from `accounts` where `id` = ?"),
] {
assert_sql(&accounts(connection).skip_locked(), sql, &[value(1_i64)]);
}
assert_sql(
&accounts(postgres()).shared_lock().no_wait(),
r#"select * from "accounts" where "id" = $1 for share nowait"#,
&[value(1_i64)],
);
assert_sql(
&accounts(mysql()).shared_lock().skip_locked(),
"select * from `accounts` where `id` = ? for share skip locked",
&[value(1_i64)],
);
assert_sql(
&accounts(mariadb()).shared_lock().skip_locked(),
"select * from `accounts` where `id` = ? lock in share mode skip locked",
&[value(1_i64)],
);
assert_error(
&db::union([accounts(postgres()), db::table("accounts")]).lock_for_update(),
"a query with a `union` can't lock rows",
);
}
#[test]
fn sqlite_unions_select_from_each_member() {
let names = |id: i64| db::table("users").select(["name"]).filter(col("id").eq(id));
assert_sql(
&db::union([
sqlite().table("users").select(["name"]).filter(col("id").eq(1_i64)),
names(2),
]),
r#"select * from (select `name` from `users` where `id` = ?) union select * from (select `name` from `users` where `id` = ?)"#,
&[value(1_i64), value(2_i64)],
);
assert_sql(
&db::union_all([
sqlite().table("users").select(["name"]).order_by("id").limit(2),
names(2),
])
.order_by("name")
.limit(5),
r#"select * from (select `name` from `users` order by `id` asc limit 2) union all select * from (select `name` from `users` where `id` = ?) order by `name` asc limit 5"#,
&[value(2_i64)],
);
assert_sql(
&db::union([
sqlite().table("users").select(["name"]).filter(col("id").eq(1_i64)),
names(2),
])
.filter(col("users.name").ne("Taylor")),
concat!(
r#"select * from (select * from (select `name` from `users` where `id` = ?) "#,
r#"union select * from (select `name` from `users` where `id` = ?)) as `users` where `users`.`name` <> ?"#,
),
&[value(1_i64), value(2_i64), text("Taylor")],
);
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn unions_parenthesize_members_on_postgres_and_mysql() {
let build = |connection: AnyConnection| {
db::union_all([
connection.table("users").select(["name"]).filter(col("id").eq(1_i64)),
db::table("admins").select(["name"]).limit(3),
])
.order_by("name")
.limit(5)
};
assert_sql(
&build(postgres()),
r#"(select "name" from "users" where "id" = $1) union all (select "name" from "admins" limit 3) order by "name" asc limit 5"#,
&[value(1_i64)],
);
assert_sql(
&build(mysql()),
"(select `name` from `users` where `id` = ?) union all (select `name` from `admins` limit 3) order by `name` asc limit 5",
&[value(1_i64)],
);
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn full_text_searches_follow_each_dialect() {
let search = |connection: AnyConnection, search: db::Search| connection.table("posts").filter(search);
assert_sql(
&search(
postgres(),
db::search(["body"], "rust -java").websearch().language("simple"),
),
r#"select * from "posts" where (to_tsvector('simple', coalesce("body", ''))) @@ websearch_to_tsquery('simple', $1)"#,
&[text("rust -java")],
);
assert_sql(
&search(
mysql(),
db::search(["title", "body"], "web developer").language("german"),
),
"select * from `posts` where match (`title`, `body`) against (? in natural language mode)",
&[text("web developer")],
);
assert_sql(
&mysql()
.table("posts")
.filter(col("draft").eq(false) & !db::Condition::from(db::search(["body"], "database").expanded())),
"select * from `posts` where `draft` = ? and not (match (`body`) against (? in natural language mode with query expansion))",
&[value(false), text("database")],
);
assert_sql(
&mysql()
.table("posts")
.filter(db::search(["body"], "rust") & col("draft").eq(false) | !db::search(["title"], "java")),
concat!(
"select * from `posts` where (match (`body`) against (? in natural language mode) and `draft` = ?) ",
"or not (match (`title`) against (? in natural language mode))",
),
&[text("rust"), value(false), text("java")],
);
assert_error(
&search(postgres(), db::search(["body"], "+rust").boolean()),
"`boolean` full-text search runs only on MySQL",
);
assert_error(
&search(mysql(), db::search(["body"], "rust").websearch()),
"`websearch` full-text search runs only on PostgreSQL",
);
assert_error(
&search(postgres(), db::search(["body"], "rust").language("english') or ('1")),
"`english') or ('1` must contain only letters, digits, and `_`",
);
assert_error(
&search(postgres(), db::search(Vec::<&str>::new(), "rust")),
"`db::search` needs at least one column",
);
assert_error(
&search(sqlite(), db::search(["body"], "rust")),
"full-text search runs only on PostgreSQL and MySQL, not SQLite",
);
}
#[cfg(feature = "database-mysql")]
#[test]
fn vector_distances_follow_each_dialect() {
let embedding = vec![0.5_f32, -1.0, 0.25];
let documents = |connection: AnyConnection| {
let distance = col("embedding").cosine_distance(&embedding);
connection
.table("documents")
.select(("title", distance.clone().alias("distance")))
.filter(distance.le(0.3))
};
let vector = text("[0.5,-1,0.25]");
assert_sql(
&documents(mariadb()),
"select `title`, vec_distance_cosine(`embedding`, vec_fromtext(?)) as `distance` from `documents` where vec_distance_cosine(`embedding`, vec_fromtext(?)) <= ?",
&[vector.clone(), vector, value(0.3)],
);
let nearest = |connection: AnyConnection| {
connection
.table("documents")
.order_by(col("embedding").cosine_distance(&[1.0, 0.0]).desc())
};
assert_sql(
&nearest(mariadb()),
"select * from `documents` order by vec_distance_cosine(`embedding`, vec_fromtext(?)) is null, vec_distance_cosine(`embedding`, vec_fromtext(?)) desc",
&[text("[1,0]"), text("[1,0]")],
);
assert_sql(
&mariadb()
.table("documents")
.filter(col("embedding").eq(db::vector(&[1.0, 0.0]))),
"select * from `documents` where `embedding` = vec_fromtext(?)",
&[text("[1,0]")],
);
for connection in [mysql(), sqlite()] {
assert_error(
&connection
.table("documents")
.order_by(col("embedding").cosine_distance(&embedding)),
"vectors run only on PostgreSQL with pgvector and on MariaDB 11.7 or later",
);
assert_error(
&connection
.table("documents")
.filter(col("embedding").eq(db::vector(&[1.0, 0.0]))),
"vectors run only on PostgreSQL with pgvector and on MariaDB 11.7 or later",
);
}
}
#[test]
fn json_path_keys_outside_the_safe_characters_fail() {
for key in ["a'b", r#"a"))#"#, "a b", ""] {
assert_error(
&sqlite().table("users").filter(col(format!("options->{key}")).eq(1)),
&format!("JSON path key `{key}` must contain only letters, digits, `_`, and `-`"),
);
}
assert_error(
&sqlite().table("users").filter(col("options").json_has_key()),
r#"`json_has_key` needs a column with a JSON path, such as `col("options->theme")`"#,
);
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn identifiers_escape_quote_characters() {
assert_sql(
&postgres().table(r#"we"ird"#).select([r#"a"b as c"d"#]),
r#"select "a""b" as "c""d" from "we""ird""#,
&[],
);
assert_sql(
&mysql().table("we`ird").select(["a`b as c`d"]),
"select `a``b` as `c``d` from `we``ird`",
&[],
);
assert_sql(
&sqlite().table("users").order_by(r#"name` desc; drop table users; --"#),
r#"select * from `users` order by `name`` desc; drop table users; --` asc"#,
&[],
);
}
#[test]
fn directions_parse_from_text_in_any_case() {
assert_eq!("DESC".parse::<Direction>().unwrap(), Direction::Desc);
assert_eq!("asc".parse::<Direction>().unwrap(), Direction::Asc);
assert_eq!(
"sideways".parse::<Direction>().unwrap_err().to_string(),
"The sort direction must be asc or desc."
);
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
async fn mariadb_upserts_read_the_new_values_with_values() {
let upsert = async |connection: &AnyConnection| {
connection
.table("users")
.upsert(values! { email: "a@example.com", name: "A" }, ["email"], ["name"])
.await
};
assert_eq!(
written_sql(&mariadb(), upsert).await,
["insert into `users` (`email`, `name`) values (?, ?) on duplicate key update `name` = values(`name`)"]
);
}
#[tokio::test]
async fn reads_that_need_one_query_shape_fail_before_running() {
assert_eq!(
sqlite()
.table("a")
.group_by(["team"])
.sum::<i64>("x")
.await
.unwrap_err()
.to_string(),
"`sum` can't aggregate a grouped query; select the aggregate and `get` each group instead"
);
}
#[tokio::test]
async fn invalid_writes_fail_before_running() {
let users = sqlite().table("users");
let error = |result: laravel::Result<u64>| {
let error = result.unwrap_err();
assert_eq!(error.location().map(|location| location.file()), Some(file!()));
error.to_string()
};
assert_eq!(
error(users.insert([values! { email: "a" }, values! { name: "b" }]).await),
"row 2 of the insert has different columns than row 1"
);
assert_eq!(
error(
users
.upsert(values! { email: "a" }, Vec::<&str>::new(), ["email"])
.await
),
"`upsert` needs at least one `unique_by` column"
);
assert_eq!(
error(users.upsert(values! { email: "a" }, ["email"], db::Values::new()).await),
"`upsert` needs at least one column to update"
);
assert_eq!(
error(users.clone().limit(1).update(values! { name: "b" }).await),
"`update` can't use `limit`; filter with a subquery instead"
);
assert_eq!(
error(
users
.clone()
.join("posts", col("posts.user_id").eq(col("users.id")))
.delete()
.await
),
"`delete` can't use a join; filter with a subquery instead"
);
assert_eq!(
error(
users
.clone()
.group_by(["team_id"])
.having(col("*").count().gt(1_i64))
.delete()
.await
),
"`delete` can't use `having`; filter with a subquery instead"
);
assert_eq!(
error(
db::union([users.clone(), db::table("admins")])
.update(values! { name: "b" })
.await
),
"`update` needs a table, not a subquery, a union, or raw SQL"
);
assert_eq!(
error(users.insert_using([db::raw!("upper(name)")], db::table("people")).await),
"`insert_using` columns must be column names"
);
assert_eq!(users.insert(Vec::new()).await.unwrap(), 0);
}
#[derive(Debug, PartialEq, db::FromRow)]
struct User {
id: i64,
name: String,
email: String,
votes: i64,
active: bool,
}
#[derive(Debug, PartialEq, db::FromRow)]
struct Authored {
title: String,
author: String,
}
fn is_send_and_static<T: Send + 'static>(value: T) -> T {
value
}
fn is_send<T: Send>(value: T) -> T {
value
}
fn definition(url: impl Into<String>) -> ConnectionConfig {
let mut config = ConnectionConfig::new(url);
config.max_connections = 1;
config
}
async fn execution_contract(definition: ConnectionConfig) -> laravel::Result<()> {
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.connections.insert("primary".into(), definition);
})
.create();
app.scope(async || {
create_tables().await?;
writes_and_retrieval().await?;
inserts_from_queries().await?;
rows_as_tuples().await?;
null_safe_comparisons().await?;
case_sensitive_matches().await?;
dates_against_the_clock(&app).await?;
json_paths().await?;
json_checks().await?;
joins_and_unions().await?;
chunks_and_cursors().await?;
custom_column_types().await?;
full_text_search().await?;
transactions_and_truncation().await
})
.await
}
#[derive(Debug, PartialEq)]
struct Email(String);
impl db::Decode for Email {
fn decode(row: &db::AnyRow, index: usize) -> laravel::Result<Self> {
let email = String::decode(row, index)?;
let (local, _) = email
.split_once('@')
.ok_or_else(|| laravel::abort_with(500, "missing `@`"))?;
Ok(Email(local.to_owned()))
}
}
impl From<&Email> for Value<'_> {
fn from(email: &Email) -> Self {
format!("{}@example.com", email.0).into()
}
}
impl db::Nullable for Email {
fn null() -> Value<'static> {
Value::Text(None)
}
}
#[derive(Debug, PartialEq, db::FromRow)]
struct Contact {
name: String,
email: Email,
}
async fn custom_column_types() -> laravel::Result<()> {
let users = || db::table("qb_users");
let year: Option<i64> = users().value(db::Expr::from(db::raw!("current_date")).year()).await?;
assert!(year.is_some_and(|year| year >= 2026), "{year:?}");
assert_eq!(
db::table("qb_posts as p")
.filter(col("p.title").eq("nothing"))
.delete()
.await?,
0
);
let taylor = Email("taylor".into());
let contact: Option<Contact> = users()
.select(["name", "email"])
.filter(col("email").eq(&taylor))
.first()
.await?;
assert_eq!(
contact,
Some(Contact {
name: "Taylor Otwell".into(),
email: Email("taylor".into())
})
);
let emails: Vec<Email> = users().filter(col("name").eq("Abigail")).pluck("email").await?;
assert_eq!(emails, [Email("abigail".into())]);
let nobody: Option<&Email> = None;
assert_eq!(users().filter(col("email").eq(nobody)).count().await?, 0);
let distinct_votes: Option<i64> = users()
.select([col("votes").count_distinct().alias("different")])
.value("different")
.await?;
let expected = users().select(["votes"]).distinct().count().await?;
assert_eq!(distinct_votes.map(i64::cast_unsigned), Some(expected));
assert!(expected > 1, "the users have different votes");
let error = users().pluck::<Email>("name").await.unwrap_err();
assert_eq!(
error.to_string(),
"error occurred while decoding column name: missing `@`"
);
Ok(())
}
async fn create_tables() -> laravel::Result<()> {
let connection = db::default_connection()?;
let (id, json, timestamp) = match connection.driver() {
Driver::Postgres => ("BIGSERIAL PRIMARY KEY", "JSONB", "TIMESTAMP(0) WITHOUT TIME ZONE"),
Driver::MySql | Driver::MariaDb => ("BIGINT AUTO_INCREMENT PRIMARY KEY", "JSON", "TIMESTAMP"),
Driver::Sqlite => ("INTEGER PRIMARY KEY AUTOINCREMENT", "TEXT", "DATETIME"),
};
for sql in [
format!(
"CREATE TEMPORARY TABLE qb_users (id {id}, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, votes BIGINT NOT NULL DEFAULT 0, active BOOLEAN NOT NULL DEFAULT TRUE, options {json})"
),
format!("CREATE TEMPORARY TABLE qb_posts (id {id}, user_id BIGINT NOT NULL, title VARCHAR(255) NOT NULL)"),
"CREATE TEMPORARY TABLE qb_names (name VARCHAR(255) NOT NULL, votes BIGINT NOT NULL)".into(),
format!("CREATE TEMPORARY TABLE qb_tags (position BIGINT NOT NULL, tag_id {id}, name VARCHAR(255) NOT NULL)"),
format!("CREATE TEMPORARY TABLE qb_codes (id {id}, code VARCHAR(255) NOT NULL)"),
format!(
"CREATE TEMPORARY TABLE qb_events (id {id}, name VARCHAR(255) NOT NULL, starts_at {timestamp} NULL, due_on DATE NULL)"
),
] {
connection.query(AssertSqlSafe(sql)).statement().await?;
}
Ok(())
}
async fn writes_and_retrieval() -> laravel::Result<()> {
let users = || db::table("qb_users");
let taylor = users()
.insert_get_id(values! { name: "Taylor", email: "taylor@example.com", votes: 10 }, "id")
.await?;
assert_eq!(taylor, 1);
let tags = || db::table("qb_tags");
assert_eq!(
tags()
.insert_get_id(values! { position: 50, name: "rust" }, "tag_id")
.await?,
1
);
assert_eq!(
tags()
.insert_get_id(values! { position: 60, name: "sql" }, "tag_id")
.await?,
2
);
assert_eq!(
tags().filter(col("tag_id").eq(2)).value::<String>("name").await?,
Some("sql".into())
);
let inserted = users()
.insert([
values! { name: "Abigail", email: "abigail@example.com", votes: 3, active: true },
values! { email: "james@example.com", votes: 7, name: "James", active: false },
])
.await?;
assert_eq!(inserted, 2);
assert_eq!(
users()
.insert_or_ignore(values! { name: "Copy", email: "taylor@example.com" })
.await?,
0
);
assert_eq!(
users()
.insert_or_ignore(values! { name: "Mohamed", email: "mohamed@example.com" })
.await?,
1
);
let active: Vec<User> = users()
.filter(col("active").eq(true) & col("votes").ge(0))
.order_by(col("votes").desc())
.get()
.await?;
assert_eq!(
active.iter().map(|user| user.name.as_str()).collect::<Vec<_>>(),
["Taylor", "Abigail", "Mohamed"]
);
assert_eq!(
users().find::<User>(taylor).await?,
Some(User {
id: 1,
name: "Taylor".into(),
email: "taylor@example.com".into(),
votes: 10,
active: true,
})
);
assert_eq!(users().find::<User>(99).await?, None);
let first: Option<User> = users().order_by(col("votes").desc()).first().await?;
assert_eq!(first.map(|user| user.name), Some("Taylor".into()));
let james: User = users().filter(col("name").eq("James")).sole().await?;
assert!(!james.active);
let missing = users()
.filter(col("name").eq("Nobody"))
.sole::<User>()
.await
.unwrap_err();
assert_eq!(missing.status().as_u16(), 404);
assert!(missing.is::<db::RecordNotFound>());
let several = users().sole::<User>().await.unwrap_err();
assert_eq!(several.status().as_u16(), 500);
assert!(several.is::<db::MultipleRecordsFound>());
assert_eq!(several.to_string(), "several records match the query");
assert_eq!(
users().filter(col("id").eq(taylor)).value::<String>("email").await?,
Some("taylor@example.com".into())
);
assert_eq!(users().filter(col("id").eq(99)).value::<String>("email").await?, None);
assert_eq!(
users().order_by("name").pluck::<String>("name").await?,
["Abigail", "James", "Mohamed", "Taylor"]
);
let mut shuffled: Vec<String> = users()
.order_by("name")
.unordered()
.order_by(db::random())
.pluck("name")
.await?;
shuffled.sort();
assert_eq!(shuffled, ["Abigail", "James", "Mohamed", "Taylor"]);
let pending = {
let query = users();
is_send_and_static(query.count())
};
assert_eq!(pending.await?, 4);
assert_eq!(users().filter(col("active").eq(false)).count().await?, 1);
assert_eq!(users().group_by(["active"]).count().await?, 2);
assert!(users().filter(col("email").like("%@EXAMPLE.com")).exists().await?);
assert!(!users().filter(col("votes").gt(100)).exists().await?);
assert_eq!(users().min::<i64>("votes").await?, Some(0));
assert_eq!(users().max::<i64>("votes").await?, Some(10));
assert_eq!(users().filter(col("votes").gt(100)).max::<i64>("votes").await?, None);
assert_eq!(users().sum::<i64>("votes").await?, Some(20));
assert_eq!(users().sum::<Decimal>("votes").await?, Some(Decimal::from(20)));
let average = users().filter(col("votes").gt(0)).avg("votes").await?.unwrap();
assert!((average - 20.0 / 3.0).abs() < 1e-9, "{average}");
assert_eq!(users().filter(col("votes").gt(100)).avg("votes").await?, None);
let loud = || users().select([db::raw!("upper(name)").alias("loud")]);
assert_eq!(
loud().order_by("name").pluck::<String>("loud").await?,
["ABIGAIL", "JAMES", "MOHAMED", "TAYLOR"]
);
assert_eq!(
loud().filter(col("id").eq(taylor)).value::<String>("loud").await?,
Some("TAYLOR".into())
);
let misspelled = users().filter(col("nmae").eq("Taylor")).count().await;
assert!(misspelled.is_err(), "a misspelled column must fail, not match nothing");
let undecodable = users().value::<i64>("email").await.unwrap_err();
assert_eq!(undecodable.location().map(|location| location.file()), Some(file!()));
let taylor_row = users().filter(col("id").eq(taylor));
assert_eq!(taylor_row.increment("votes", 5).await?, 1);
assert_eq!(taylor_row.decrement("votes", 2).await?, 1);
assert_eq!(
taylor_row
.update(values! { name: "Taylor Otwell", votes: col("votes") * 2 })
.await?,
1
);
assert_eq!(taylor_row.value::<i64>("votes").await?, Some(26));
users()
.update_or_insert(values! { email: "james@example.com" }, values! { votes: 8 })
.await?;
users()
.update_or_insert(
values! { email: "nuno@example.com" },
values! { email: "nuno@example.com", name: "Nuno", votes: 1 },
)
.await?;
assert_eq!(
users()
.filter(col("email").is_in(["james@example.com", "nuno@example.com"]))
.order_by("email")
.pluck::<i64>("votes")
.await?,
[8, 1]
);
users()
.upsert(
[
values! { name: "Abigail", email: "abigail@example.com", votes: 30 },
values! { name: "Jess", email: "jess@example.com", votes: 2 },
],
["email"],
["votes"],
)
.await?;
assert_eq!(
users()
.filter(col("email").is_in(["abigail@example.com", "jess@example.com"]))
.order_by("email")
.pluck::<i64>("votes")
.await?,
[30, 2]
);
assert_eq!(users().filter(col("name").eq("Jess")).delete().await?, 1);
assert_eq!(users().count().await?, 5);
Ok(())
}
async fn inserts_from_queries() -> laravel::Result<()> {
let names = || db::table("qb_names");
let popular = db::table("qb_users")
.select(["name", "votes"])
.filter(col("votes").gt(5) & col("name").ne("James"));
assert_eq!(names().insert_using(["name", "votes"], popular).await?, 2);
let nuno = db::table("qb_users")
.select(["votes", "name"])
.filter(col("email").eq("nuno@example.com"));
assert_eq!(names().insert_using(["votes", "name"], nuno).await?, 1);
let mohamed = db::table("qb_users")
.select(["name", "votes"])
.filter(col("name").eq("Mohamed"));
assert_eq!(names().insert_using(Vec::<&str>::new(), mohamed).await?, 1);
let nobody = db::table("qb_users")
.select(["name", "votes"])
.filter(col("votes").gt(100));
assert_eq!(names().insert_using(["name", "votes"], nobody).await?, 0);
assert_eq!(
names().order_by("name").pluck::<String>("name").await?,
["Abigail", "Mohamed", "Nuno", "Taylor Otwell"]
);
assert_eq!(names().order_by("name").pluck::<i64>("votes").await?, [30, 0, 1, 26]);
Ok(())
}
async fn case_sensitive_matches() -> laravel::Result<()> {
let codes = || db::table("qb_codes").order_by("id");
codes()
.insert(
[
"SUMMER25",
"summer25",
"Summer_Sale",
"SummerXSale",
"Été",
"été",
"50*OFF",
"[VIP]",
]
.map(|code| values! { code: code }),
)
.await?;
let matching = async |condition: db::Condition| codes().filter(condition).pluck::<String>("code").await;
assert_eq!(
matching(col("code").like_case_sensitive("SUMMER%")).await?,
["SUMMER25"]
);
assert_eq!(
matching(col("code").like("SUMMER%")).await?,
["SUMMER25", "summer25", "Summer_Sale", "SummerXSale"],
"`like` ignores case with each database's defaults"
);
assert_eq!(
matching(!col("code").like_case_sensitive("%summer%")).await?,
[
"SUMMER25",
"Summer_Sale",
"SummerXSale",
"Été",
"été",
"50*OFF",
"[VIP]"
]
);
assert_eq!(
matching(col("code").like_case_sensitive("Summer_Sale")).await?,
["Summer_Sale", "SummerXSale"],
"`_` matches any one character"
);
assert_eq!(matching(col("code").like_case_sensitive("Été")).await?, ["Été"]);
assert_eq!(matching(col("code").like_case_sensitive("50*%")).await?, ["50*OFF"]);
assert!(matching(col("code").like_case_sensitive("5*")).await?.is_empty());
assert_eq!(matching(col("code").like_case_sensitive("[V%")).await?, ["[VIP]"]);
assert!(matching(col("code").like_case_sensitive("_VIP?")).await?.is_empty());
Ok(())
}
async fn dates_against_the_clock(app: &Application) -> laravel::Result<()> {
use laravel::time::civil::Date;
use laravel::time::{Timestamp, ToSpan};
let at = |time: &str| time.parse::<Timestamp>().unwrap();
let day = |date: &str| date.parse::<Date>().unwrap();
let events = || db::table("qb_events").order_by("id");
events()
.insert([
values! { name: "yesterday", starts_at: at("2026-11-14T23:59:59Z"), due_on: day("2026-11-14") },
values! { name: "now", starts_at: at("2026-11-15T00:30:00Z"), due_on: day("2026-11-15") },
values! { name: "tonight", starts_at: at("2026-11-15T23:59:59Z"), due_on: None::<Date> },
values! { name: "tomorrow", starts_at: at("2026-11-16T00:00:00Z"), due_on: day("2026-11-16") },
values! { name: "unscheduled", starts_at: None::<Timestamp>, due_on: None::<Date> },
])
.await?;
let names = async |condition: db::Condition| events().filter(condition).pluck::<String>("name").await;
app.travel_to(at("2026-11-15T00:30:00Z"));
assert_eq!(names(col("starts_at").is_past()).await?, ["yesterday"]);
assert_eq!(names(!col("starts_at").is_future()).await?, ["yesterday", "now"]);
assert_eq!(names(col("starts_at").is_future()).await?, ["tonight", "tomorrow"]);
assert_eq!(
names(!col("starts_at").is_past()).await?,
["now", "tonight", "tomorrow"]
);
assert_eq!(names(col("starts_at").is_today()).await?, ["now", "tonight"]);
assert_eq!(names(col("starts_at").is_before_today()).await?, ["yesterday"]);
assert_eq!(names(col("starts_at").is_after_today()).await?, ["tomorrow"]);
assert_eq!(
names(!col("starts_at").is_after_today()).await?,
["yesterday", "now", "tonight"]
);
assert_eq!(names(col("due_on").is_today()).await?, ["now"]);
assert_eq!(names(!col("due_on").is_before_today()).await?, ["now", "tomorrow"]);
app.travel(1.day());
assert_eq!(names(col("starts_at").is_today()).await?, ["tomorrow"]);
assert_eq!(
names(col("starts_at").is_past()).await?,
["yesterday", "now", "tonight", "tomorrow"]
);
app.travel_back();
Ok(())
}
async fn null_safe_comparisons() -> laravel::Result<()> {
db::query!("CREATE TEMPORARY TABLE qb_pairs (id BIGINT NOT NULL, a BIGINT NULL, b BIGINT NULL)")
.statement()
.await?;
db::query!("INSERT INTO qb_pairs (id, a, b) VALUES (1, 1, 1), (2, 1, 2), (3, 1, NULL), (4, NULL, NULL)")
.statement()
.await?;
let ids = |condition: db::Condition| {
db::table("qb_pairs")
.filter(condition)
.order_by("id")
.pluck::<i64>("id")
};
assert_eq!(ids(col("a").is_distinct_from(col("b"))).await?, [2, 3]);
assert_eq!(ids(!col("a").is_distinct_from(col("b"))).await?, [1, 4]);
assert_eq!(ids(col("b").is_distinct_from(2_i64)).await?, [1, 3, 4]);
assert_eq!(ids(col("b").ne(2_i64)).await?, [1]);
assert_eq!(ids(!col("b").is_distinct_from(None::<i64>)).await?, [3, 4]);
Ok(())
}
async fn rows_as_tuples() -> laravel::Result<()> {
let names = || db::table("qb_names").select(["name", "votes"]).order_by("name");
assert_eq!(
names().get::<(String, i64)>().await?,
[
("Abigail".to_owned(), 30),
("Mohamed".to_owned(), 0),
("Nuno".to_owned(), 1),
("Taylor Otwell".to_owned(), 26),
]
);
let votes: HashMap<String, i64> = names().get::<(String, i64)>().await?.into_iter().collect();
assert_eq!(votes.len(), 4);
assert_eq!(votes["Nuno"], 1);
let first: Option<(i64, Option<String>, String)> = db::table("qb_names")
.select(("votes", db::raw!("null").alias("missing"), "name"))
.order_by("name")
.first()
.await?;
assert_eq!(first, Some((30, None, "Abigail".to_owned())));
let one: Option<(String,)> = names().select(["name"]).first().await?;
assert_eq!(one, Some(("Abigail".to_owned(),)));
let error = names().get::<(String,)>().await.unwrap_err();
assert_eq!(error.status().as_u16(), 500);
assert_eq!(
error.to_string(),
"a database query mapped to a tuple must return one column per element, 1 expected and 2 returned"
);
let error = names().get::<(String, i64, i64)>().await.unwrap_err();
assert_eq!(
error.to_string(),
"a database query mapped to a tuple must return one column per element, 3 expected and 2 returned"
);
Ok(())
}
async fn json_paths() -> laravel::Result<()> {
let users = || db::table("qb_users");
let options = json!({ "theme": "light", "size": 3, "enabled": true, "tags": ["a"] });
let id = users()
.insert_get_id(
values! { name: "Json", email: "json@example.com", options: &options },
"id",
)
.await?;
let json_user = users().filter(col("email").eq("json@example.com"));
assert_eq!(
users()
.filter(col("options->theme").eq("light") & col("options->size").gt(2) & col("options->enabled").eq(true))
.pluck::<i64>("id")
.await?,
[id]
);
assert_eq!(users().filter(col("options->size").is_in([3, 4])).count().await?, 1);
assert_eq!(json_user.value::<String>("options->tags[0]").await?, Some("a".into()));
json_user
.update(values! {
"options->theme": "dark",
"options->size": 5,
})
.await?;
json_user.update(values! { "options->enabled": false }).await?;
json_user.update(values! { "options->tags": json!(["b", "c"]) }).await?;
assert_eq!(json_user.value::<String>("options->theme").await?, Some("dark".into()));
assert_eq!(json_user.value::<String>("options->tags[1]").await?, Some("c".into()));
assert_eq!(
users()
.filter(col("options->size").eq(5) & col("options->enabled").eq(false) & col("options->theme").ne("light"))
.count()
.await?,
1
);
assert!(
users()
.filter(col("options->the'me").eq("dark"))
.count()
.await
.unwrap_err()
.to_string()
.contains("JSON path key")
);
json_user.delete().await?;
Ok(())
}
async fn json_checks() -> laravel::Result<()> {
db::table("qb_users")
.insert([
values! { name: "Ada", email: "ada@json.test", options: json!({ "languages": ["en", "de"], "theme": null }) },
values! { name: "Bo", email: "bo@json.test", options: json!({ "languages": ["fr"], "size": 2 }) },
values! { name: "Cy", email: "cy@json.test", options: json!({ "languages": [], "theme": "dark" }) },
values! { name: "Di", email: "di@json.test", options: json!({ "theme": "light" }) },
])
.await?;
let users = || {
db::table("qb_users")
.filter(col("email").like("%@json.test"))
.order_by("name")
};
let names = async |condition: db::Condition| users().filter(condition).pluck::<String>("name").await;
assert_eq!(names(col("options->languages").json_contains("en")).await?, ["Ada"]);
assert_eq!(
names(col("options->languages").json_contains(["de", "en"])).await?,
["Ada"]
);
assert!(
names(col("options->languages").json_contains(["en", "fr"]))
.await?
.is_empty()
);
assert_eq!(
names(col("options->languages").json_contains(Vec::<&str>::new())).await?,
["Ada", "Bo", "Cy"]
);
assert_eq!(
names(!col("options->languages").json_contains(Vec::<&str>::new())).await?,
["Di"]
);
assert_eq!(
names(!col("options->languages").json_contains("en")).await?,
["Bo", "Cy", "Di"]
);
assert_eq!(names(col("options->size").json_contains(2)).await?, ["Bo"]);
let dark = col("options").json_contains(json!({ "theme": "dark" }));
let nested = col("options").json_contains(json!({ "languages": ["fr"] }));
if db::default_connection()?.driver() == Driver::Sqlite {
for condition in [dark, nested] {
assert_eq!(
users().filter(condition).count().await.unwrap_err().to_string(),
"`json_contains` on SQLite checks only scalars and arrays of scalars"
);
}
} else {
assert_eq!(names(dark).await?, ["Cy"]);
assert_eq!(names(nested).await?, ["Bo"]);
}
assert_eq!(names(col("options->theme").json_has_key()).await?, ["Ada", "Cy", "Di"]);
assert_eq!(names(!col("options->theme").json_has_key()).await?, ["Bo"]);
assert_eq!(names(col("options->languages[1]").json_has_key()).await?, ["Ada"]);
assert_eq!(names(col("options->theme").is_null()).await?, ["Ada", "Bo"]);
assert_eq!(names(col("options->theme").eq(None::<&str>)).await?, ["Ada", "Bo"]);
assert_eq!(names(!col("options->theme").is_null()).await?, ["Cy", "Di"]);
assert_eq!(names(col("options->theme").like("DARK")).await?, ["Cy"]);
assert_eq!(
names(col("options->theme").like_case_sensitive("DARK")).await?,
Vec::<String>::new()
);
assert_eq!(
names(col("options->theme").is_distinct_from(None::<&str>)).await?,
["Cy", "Di"]
);
assert_eq!(
names(!col("options->theme").is_distinct_from(None::<&str>)).await?,
["Ada", "Bo"]
);
assert_eq!(
names(col("options->languages").json_length().ge(1)).await?,
["Ada", "Bo"]
);
assert_eq!(
users()
.select(("name", col("options->languages").json_length().alias("languages")))
.get::<(String, Option<i64>)>()
.await?,
[
("Ada".to_owned(), Some(2)),
("Bo".to_owned(), Some(1)),
("Cy".to_owned(), Some(0)),
("Di".to_owned(), None),
]
);
assert_eq!(
db::table("qb_users")
.filter(col("email").like("%@json.test"))
.delete()
.await?,
4
);
Ok(())
}
#[derive(Debug, PartialEq, db::FromRow)]
struct PostsCount {
name: String,
posts_count: i64,
}
async fn joins_and_unions() -> laravel::Result<()> {
let posts = || db::table("qb_posts");
posts()
.insert([
values! { user_id: 1, title: "Laravel" },
values! { user_id: 2, title: "Queues" },
values! { user_id: 1, title: "Builders" },
])
.await?;
let joined = posts()
.join("qb_users as u", col("u.id").eq(col("qb_posts.user_id")))
.order_by("qb_posts.id");
#[derive(db::FromRow)]
struct Title {
title: String,
}
let pages = joined
.chunk_by_id::<Title>(1, col("qb_posts.id").desc())
.try_collect::<Vec<_>>()
.await?;
let titles: Vec<_> = pages.into_iter().flatten().map(|row| row.title).collect();
assert_eq!(titles, ["Builders", "Queues", "Laravel"]);
let missing = joined
.clone()
.select(["u.*"])
.chunk_by_id::<User>(1, "qb_posts.id")
.try_next()
.await;
assert!(missing.unwrap_err().to_string().contains("qb_posts.id"));
let newest = posts()
.join("qb_users as u", col("u.id").eq(col("qb_posts.user_id")))
.select(["qb_posts.title", "qb_posts.id", "u.*"])
.order_by(col("qb_posts.id").desc());
let first = newest.cursor_paginate::<Title>(1).await?;
let next = newest
.cursor_paginate::<Title>(1)
.cursor(first.next_cursor().unwrap())
.await?;
assert_eq!(
next.items().iter().map(|row| row.title.as_str()).collect::<Vec<_>>(),
["Queues"]
);
let previous = newest
.cursor_paginate::<Title>(1)
.cursor(next.previous_cursor().unwrap())
.await?;
assert_eq!(previous.items()[0].title, "Builders");
let users = joined.clone().select(["u.id"]);
assert_eq!(users.pluck::<i64>("qb_posts.id").await?, [1, 2, 3]);
let expanded = joined.clone().select(["u.*", "qb_posts.id", "u.id"]);
assert_eq!(expanded.pluck::<i64>("qb_posts.id").await?, [1, 2, 3]);
let both = joined.select(["qb_posts.id", "u.id"]).distinct();
assert_eq!(both.pluck::<i64>("u.id").await?, [1, 2, 1]);
assert_eq!(both.pluck::<i64>("qb_posts.id").await?, [1, 2, 3]);
let authored: Vec<Authored> = posts()
.join("qb_users as u", col("u.id").eq(col("qb_posts.user_id")))
.select(["qb_posts.title", "u.name as author"])
.filter(col("u.name").like("taylor%"))
.order_by("title")
.get()
.await?;
assert_eq!(
authored,
[
Authored {
title: "Builders".into(),
author: "Taylor Otwell".into()
},
Authored {
title: "Laravel".into(),
author: "Taylor Otwell".into()
},
]
);
let without_posts = db::table("qb_users")
.left_join("qb_posts", col("qb_posts.user_id").eq(col("qb_users.id")))
.filter(col("qb_posts.id").eq(None::<i64>))
.order_by("qb_users.name")
.pluck::<String>("qb_users.name")
.await?;
assert_eq!(without_posts, ["James", "Mohamed", "Nuno"]);
let posts_count = posts()
.select([col("*").count()])
.filter(col("qb_posts.user_id").eq(col("qb_users.id")));
let counts = db::table("qb_users")
.select(("name", posts_count.alias("posts_count")))
.order_by("id")
.pluck::<i64>("posts_count")
.await?;
assert_eq!(counts, [2, 1, 0, 0, 0]);
let counted: Vec<PostsCount> = db::table("qb_users")
.add_select([posts()
.select([col("*").count()])
.filter(col("qb_posts.user_id").eq(col("qb_users.id")))
.alias("posts_count")])
.order_by("id")
.limit(2)
.get()
.await?;
let names: Vec<String> = db::table("qb_users").order_by("id").limit(2).pluck("name").await?;
assert_eq!(
counted,
[
PostsCount {
name: names[0].clone(),
posts_count: 2
},
PostsCount {
name: names[1].clone(),
posts_count: 1
},
]
);
let authors = db::table("qb_users")
.filter(col("id").is_in(db::table("qb_posts").select(["user_id"])))
.pluck::<String>("name")
.await?;
assert_eq!(authors.len(), 2);
let names = db::union([
db::table("qb_users").select(["name"]).filter(col("votes").gt(20)),
db::table("qb_posts")
.select(["title as name"])
.filter(col("user_id").eq(2)),
])
.order_by("name");
assert_eq!(names.get::<String>().await?, ["Abigail", "Queues", "Taylor Otwell"]);
assert_eq!(
names.pluck::<String>("name").await?,
["Abigail", "Queues", "Taylor Otwell"]
);
assert_eq!(names.count().await?, 3);
let most_votes = db::table("qb_users")
.select(["name"])
.order_by(col("votes").desc())
.order_by("id")
.limit(1);
let first_post = db::table("qb_posts").select(["title as name"]).order_by("id").limit(1);
let mut expected = most_votes.pluck::<String>("name").await?;
expected.extend(first_post.pluck::<String>("name").await?);
expected.sort();
let extremes = db::union_all([most_votes, first_post]).order_by("name");
assert_eq!(extremes.pluck::<String>("name").await?, expected);
assert_eq!(expected.len(), 2);
assert_eq!(
names
.clone()
.filter(col("qb_users.name").like("%a%"))
.pluck::<String>("name")
.await?,
["Abigail", "Taylor Otwell"]
);
let union = db::union(Vec::<db::Builder>::new());
assert_eq!(
union.count().await.unwrap_err().to_string(),
"a `union` needs at least one query"
);
let top_two = db::table("qb_users").order_by(col("qb_users.votes").desc()).limit(2);
let votes: Vec<i64> = top_two.pluck("votes").await?;
assert_eq!(top_two.min::<i64>("qb_users.votes").await?, votes.last().copied());
Ok(())
}
async fn chunks_and_cursors() -> laravel::Result<()> {
let users = || db::table("qb_users").order_by("id");
let sizes = is_send(async {
let mut sizes = Vec::new();
let mut pages = users().select(["name"]).chunk::<String>(2);
while let Some(names) = pages.try_next().await? {
sizes.push(names.len());
}
Ok::<_, laravel::Error>(sizes)
})
.await?;
assert_eq!(sizes, [2, 2, 1]);
let mut seen = Vec::new();
let mut pages = db::table("qb_users")
.filter(col("active").eq(true))
.chunk_by_id::<User>(2, "id");
while let Some(page) = pages.try_next().await? {
let ids: Vec<i64> = page.iter().map(|user| user.id).collect();
db::table("qb_users")
.filter(col("id").is_in(&ids))
.update(values! { active: false })
.await?;
seen.extend(ids);
}
assert_eq!(seen.len(), 4);
assert_eq!(db::table("qb_users").filter(col("active").eq(true)).count().await?, 0);
let unordered = db::table("qb_users").chunk::<User>(2).try_next().await.unwrap_err();
assert!(unordered.to_string().contains("`chunk` needs an `order_by`"));
let names: Vec<String> = users().select(["name"]).cursor::<String>().try_collect().await?;
assert_eq!(names.len(), 5);
let ids: Vec<i64> = users().pluck("id").await?;
let pages: Vec<Vec<User>> = users().offset(1).limit(3).chunk_by_id(2, "id").try_collect().await?;
assert_eq!(
pages.iter().flatten().map(|user| user.id).collect::<Vec<_>>(),
ids[1..4]
);
let pages: Vec<Vec<User>> = users().limit(3).chunk(2).try_collect().await?;
assert_eq!(pages.iter().map(Vec::len).collect::<Vec<_>>(), [2, 1]);
let descending: Vec<i64> = ids.iter().rev().copied().collect();
let pages: Vec<Vec<User>> = users().chunk_by_id(2, col("id").desc()).try_collect().await?;
assert_eq!(pages.iter().map(Vec::len).collect::<Vec<_>>(), [2, 2, 1]);
assert_eq!(
pages.iter().flatten().map(|user| user.id).collect::<Vec<_>>(),
descending
);
let lazy: Vec<User> = users().lazy_by_id(2, "qb_users.id").try_collect().await?;
assert_eq!(lazy.iter().map(|user| user.id).collect::<Vec<_>>(), ids);
let mut deleted = Vec::new();
let mut newest_first = users().lazy_by_id::<User>(2, col("id").desc());
while let Some(user) = newest_first.try_next().await? {
if deleted.len() < 2 {
db::table("qb_users").filter(col("id").eq(user.id)).delete().await?;
}
deleted.push(user.id);
}
assert_eq!(deleted, descending);
let not_a_column = users()
.chunk_by_id::<User>(2, db::random())
.try_next()
.await
.unwrap_err();
assert_eq!(
not_a_column.to_string(),
"the `chunk_by_id` key must be a column name, such as `\"id\"`"
);
assert_eq!(not_a_column.location().map(|location| location.file()), Some(file!()));
Ok(())
}
async fn transactions_and_truncation() -> laravel::Result<()> {
let users = || db::table("qb_users");
let before = users().count().await?;
let result: laravel::Result<()> = db::transaction(async |_tx| {
db::table("qb_users")
.insert(values! { name: "Rolled", email: "rolled@example.com" })
.await?;
assert_eq!(db::table("qb_users").count().await?, before + 1);
Err(laravel::abort_with(500, "roll back"))
})
.await;
assert!(result.is_err());
assert_eq!(users().count().await?, before);
let names: Vec<String> = users().order_by("id").pluck("name").await?;
let locked = db::transaction(async |_tx| {
let skipping: Vec<String> = users().order_by("id").skip_locked().pluck("name").await?;
let not_waiting: Vec<String> = users().order_by("id").shared_lock().no_wait().pluck("name").await?;
Ok((skipping, not_waiting))
})
.await?;
assert_eq!(locked, (names.clone(), names));
users().truncate().await?;
assert_eq!(users().count().await?, 0);
assert_eq!(
users()
.insert_get_id(values! { name: "Fresh", email: "fresh@example.com" }, "id")
.await?,
1
);
Ok(())
}
#[tokio::test]
async fn query_builder_runs_on_sqlite() -> laravel::Result<()> {
execution_contract(definition("sqlite::memory:")).await
}
#[tokio::test]
async fn sqlite_truncation_resets_only_the_target_tables_sequence() -> laravel::Result<()> {
let db = sqlite();
db.schema()
.create("visits", |table| {
table.id();
})
.await?;
db.table("visits").insert(values! { id: 41 }).await?;
db.table("visits").delete().await?;
db.transaction(async |tx| {
tx.schema()
.create("visits", |table| {
table.temporary();
table.id();
})
.await?;
for (name, next_main_id) in [("visits", 42), ("VISITS", 43)] {
db.table("temp.visits").insert(values! { id: 17 }).await?;
db.table(name).truncate().await?;
assert_eq!(db.table("temp.visits").count().await?, 0);
assert_eq!(
db.table("temp.visits")
.insert_get_id(values! { id: None::<i64> }, "id")
.await?,
1
);
assert_eq!(
db.table("main.visits")
.insert_get_id(values! { id: None::<i64> }, "id")
.await?,
next_main_id
);
}
Ok(())
})
.await
}
#[tokio::test]
async fn sqlite_truncation_rolls_back_if_the_counter_cannot_reset() -> laravel::Result<()> {
let db = sqlite();
db.schema()
.create("visits", |table| {
table.id();
})
.await?;
db.table("visits").insert(values! { id: 10 }).await?;
db.before_executing(|query| {
if query.sql.contains(".sqlite_sequence") && query.sql.starts_with("delete") {
return Err(laravel::abort_with(500, "reset interrupted"));
}
Ok(())
});
let error = db.table("visits").truncate().await.unwrap_err();
assert!(error.to_string().contains("reset interrupted"));
assert_eq!(db.table("visits").pluck::<i64>("id").await?, [10]);
Ok(())
}
#[tokio::test]
async fn queries_resolve_a_named_connection_when_they_run() -> laravel::Result<()> {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), definition("sqlite::memory:"));
config
.database
.connections
.insert("reporting".into(), definition("sqlite::memory:"));
})
.create();
app.scope(async || {
let events = || db::table("events").connection("reporting");
db::connection("reporting")?
.query("CREATE TABLE events (kind TEXT NOT NULL)")
.statement()
.await?;
events().insert(values! { kind: "signup" }).await?;
assert_eq!(events().count().await?, 1);
assert!(
db::table("events").count().await.is_err(),
"the default connection has no events table"
);
let missing = db::table("events").connection("archive").count().await.unwrap_err();
assert!(missing.to_string().contains("archive"), "{missing}");
Ok(())
})
.await
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn query_builder_runs_on_postgres() -> laravel::Result<()> {
execution_contract(definition(std::env::var("LARAVEL_TEST_POSTGRES_URL")?)).await
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable MySQL or MariaDB database"]
async fn query_builder_runs_on_mysql() -> laravel::Result<()> {
execution_contract(definition(crate::support::mysql_or_mariadb_url().await?)).await
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable MySQL 8 or later database"]
async fn json_null_checks_work_with_a_binary_mysql_connection_collation() -> laravel::Result<()> {
let connection = DatabaseManager::new(&Database::default(), "/tmp")
.connect(definition(crate::support::mysql_or_mariadb_url().await?))?;
if connection.driver() != Driver::MySql
|| connection
.query("SHOW COLLATION WHERE Collation = 'utf8mb4_0900_bin'")
.select_one()
.await?
.is_none()
{
return Ok(());
}
connection
.query("SET NAMES utf8mb4 COLLATE utf8mb4_0900_bin")
.statement()
.await?;
connection
.query("CREATE TEMPORARY TABLE qb_json_nulls (id BIGINT PRIMARY KEY, options JSON)")
.statement()
.await?;
connection
.query(
r#"INSERT INTO qb_json_nulls VALUES (1, '{"theme":null}'), (2, '{}'), (3, '{"theme":"null"}'), (4, NULL)"#,
)
.statement()
.await?;
let rows = || connection.table("qb_json_nulls").order_by("id");
let null = || col("options->theme").is_null();
assert_eq!(rows().filter(null()).pluck::<i64>("id").await?, [1, 2, 4]);
assert_eq!(rows().filter(!null()).pluck::<i64>("id").await?, [3]);
Ok(())
}
async fn full_text_search() -> laravel::Result<()> {
let connection = db::default_connection()?;
connection.query("DROP TABLE IF EXISTS qb_articles").statement().await?;
let create = match connection.driver() {
Driver::Postgres => "CREATE TABLE qb_articles (id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, body TEXT)",
Driver::MySql | Driver::MariaDb => {
"CREATE TABLE qb_articles (id BIGINT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, body TEXT, FULLTEXT (title, body)) ENGINE = InnoDB"
}
Driver::Sqlite => return Ok(()),
};
connection.query(create).statement().await?;
let articles = || db::table("qb_articles").order_by("id");
articles()
.insert([
values! { title: "Rust databases", body: "Building a query builder in Rust" },
values! { title: "Java databases", body: "Connection pools in Java and Rust" },
values! { title: "Gardening", body: "Growing tomatoes in summer" },
values! { title: "Rust tips", body: "Rust ownership, Rust lifetimes, and Rust traits" },
values! { title: "Weekly digest", body: None::<String> },
])
.await?;
let titles = async |search: db::Search| articles().filter(search).pluck::<String>("title").await;
assert_eq!(
titles(db::search(["title", "body"], "databases")).await?,
["Rust databases", "Java databases"]
);
assert_eq!(titles(db::search(["title", "body"], "tomatoes")).await?, ["Gardening"]);
assert_eq!(
titles(db::search(["title", "body"], "digest")).await?,
["Weekly digest"]
);
let rust_without_java = match connection.driver() {
Driver::Postgres => db::search(["title", "body"], "rust -java").websearch(),
_ => db::search(["title", "body"], "+rust -java").boolean(),
};
assert_eq!(titles(rust_without_java).await?, ["Rust databases", "Rust tips"]);
let rust = db::search(["title", "body"], "rust");
let ranked = db::table("qb_articles")
.filter(rust.clone())
.order_by(rust.clone())
.pluck::<String>("title")
.await?;
assert_eq!(ranked, ["Rust tips", "Rust databases", "Java databases"]);
let scores: Vec<f64> = db::table("qb_articles")
.select([rust.relevance().alias("score")])
.filter(rust.clone())
.order_by(rust)
.get()
.await?;
assert!(scores.windows(2).all(|pair| pair[0] > pair[1]), "{scores:?}");
if connection.driver() == Driver::Postgres {
assert_eq!(
titles(db::search(["body"], "query builder").phrase()).await?,
["Rust databases"]
);
assert!(titles(db::search(["body"], "builder query").phrase()).await?.is_empty());
}
connection.query("DROP TABLE qb_articles").statement().await?;
Ok(())
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MARIADB_URL pointing to a disposable MariaDB 11.7 or later database"]
async fn vectors_run_on_mariadb() -> laravel::Result<()> {
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.connections.insert(
"primary".into(),
definition(std::env::var("LARAVEL_TEST_MARIADB_URL").unwrap()),
);
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
assert_eq!(connection.driver(), Driver::MariaDb);
connection
.query("CREATE TEMPORARY TABLE qb_documents (id BIGINT AUTO_INCREMENT PRIMARY KEY, title TEXT NOT NULL, embedding VECTOR(3) NULL)")
.statement()
.await?;
let documents = || db::table("qb_documents");
documents()
.insert([
values! { title: "same", embedding: db::vector(&[1.0, 0.0, 0.0]) },
values! { title: "close", embedding: db::vector(&[1.0, 1.0, 0.0]) },
values! { title: "opposite", embedding: db::vector(&[-1.0, 0.0, 0.0]) },
])
.await?;
let similar = documents().similar_to("embedding", &[1.0, 0.0, 0.0], 0.5).pluck::<String>("title").await?;
assert_eq!(similar, ["same", "close"]);
let close: Option<db::Vector> = documents().filter(col("title").eq("close")).value("embedding").await?;
let close = close.unwrap();
assert_eq!(*close, [1.0, 1.0, 0.0]);
let missing: Option<db::Vector> = None;
documents()
.insert(values! { title: "copy", embedding: close.clone() })
.await?;
documents()
.insert(values! { title: "unembedded", embedding: missing })
.await?;
let copied: Vec<Option<db::Vector>> = documents()
.filter(col("title").is_in(["copy", "unembedded"]))
.order_by("title")
.pluck("embedding")
.await?;
assert_eq!(copied, [Some(close), None]);
let raw: db::Vector = vec![0.0, 0.5, 1.0].into();
connection
.query("INSERT INTO qb_documents (title, embedding) VALUES (?, ?)")
.bind("raw")
.bind(&raw)
.insert()
.await?;
let stored: Option<db::Vector> = documents().filter(col("title").eq("raw")).value("embedding").await?;
assert_eq!(stored, Some(raw));
let near = connection
.query("SELECT title FROM qb_documents WHERE VEC_DISTANCE_COSINE(embedding, ?) < 0.5")
.bind(db::Vector::from(vec![0.0, 0.0, 1.0]))
.scalar::<String>()
.await?;
assert_eq!(near.as_deref(), Some("raw"));
Ok(())
})
.await
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database with the pgvector extension available"]
async fn vectors_run_on_postgres_with_pgvector() -> laravel::Result<()> {
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.connections.insert(
"primary".into(),
definition(std::env::var("LARAVEL_TEST_POSTGRES_URL").unwrap()),
);
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
connection.query("CREATE EXTENSION IF NOT EXISTS vector").statement().await?;
connection
.query("CREATE TEMPORARY TABLE qb_documents (id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, embedding vector(3))")
.statement()
.await?;
let documents = || db::table("qb_documents");
documents()
.insert([
values! { title: "same", embedding: db::vector(&[1.0, 0.0, 0.0]) },
values! { title: "close", embedding: db::vector(&[1.0, 1.0, 0.0]) },
values! { title: "unrelated", embedding: db::vector(&[0.0, 0.0, 1.0]) },
values! { title: "opposite", embedding: db::vector(&[-1.0, 0.0, 0.0]) },
values! { title: "unembedded", embedding: db::vector(&[0.0, 1.0, 0.0]) },
])
.await?;
let missing: Option<&[f32]> = None;
documents()
.filter(col("title").eq("unembedded"))
.update(values! { embedding: missing.map(db::vector) })
.await?;
let query = [1.0_f32, 0.0, 0.0];
let nearest = documents()
.order_by(col("embedding").cosine_distance(&query))
.pluck::<String>("title")
.await?;
assert_eq!(nearest, ["same", "close", "unrelated", "opposite", "unembedded"]);
let farthest = documents()
.order_by(col("embedding").cosine_distance(&query).desc())
.pluck::<String>("title")
.await?;
assert_eq!(farthest, ["opposite", "unrelated", "close", "same", "unembedded"]);
let similar = documents().similar_to("embedding", &query, 0.5).pluck::<String>("title").await?;
assert_eq!(similar, ["same", "close"]);
let close: Option<db::Vector> = documents().filter(col("title").eq("close")).value("embedding").await?;
let close = close.unwrap();
assert_eq!(*close, [1.0, 1.0, 0.0]);
let unembedded: Option<db::Vector> =
documents().filter(col("title").eq("unembedded")).value("embedding").await?;
assert_eq!(unembedded, None);
let optional = Some(close.clone());
documents().insert([
values! { title: "copy", embedding: &close },
values! { title: "copy-optional", embedding: &optional },
values! { title: "copy-null", embedding: &unembedded },
]).await?;
let copies = ["copy", "copy-optional", "copy-null"];
let copied: Vec<Option<db::Vector>> = documents()
.filter(col("title").is_in(copies))
.order_by("title")
.pluck("embedding")
.await?;
assert_eq!(copied, [Some(close), None, optional]);
documents().filter(col("title").is_in(copies)).delete().await?;
let raw: db::Vector = vec![0.0, 0.5, 1.0].into();
connection
.query("INSERT INTO qb_documents (title, embedding) VALUES ($1, $2)")
.bind("raw")
.bind(&raw)
.insert()
.await?;
let stored: Option<db::Vector> = documents().filter(col("title").eq("raw")).value("embedding").await?;
assert_eq!(stored, Some(raw));
let near = connection
.query("SELECT string_agg(title, ',' ORDER BY embedding <=> $1) FROM qb_documents WHERE embedding <=> $1 < 0.5")
.bind(db::Vector::from(vec![0.0, 0.0, 1.0]))
.scalar::<String>()
.await?;
assert_eq!(near.as_deref(), Some("unrelated,raw"));
documents().filter(col("title").eq("raw")).delete().await?;
let distance = col("embedding").cosine_distance(&query);
let ranked: Vec<(String, f64)> = documents()
.select(("title", distance.clone().alias("distance")))
.filter(!col("embedding").is_null())
.order_by(distance.clone().desc())
.get()
.await?;
let rounded: Vec<(&str, f64)> = ranked
.iter()
.map(|(title, distance)| (title.as_str(), (distance * 1000.0).round() / 1000.0))
.collect();
assert_eq!(
rounded,
[("opposite", 2.0), ("unrelated", 1.0), ("close", 0.293), ("same", 0.0)]
);
assert_eq!(documents().filter(distance.le(1.0)).count().await?, 3);
Ok(())
})
.await
}
#[cfg(feature = "database-postgres")]
#[test]
fn postgres_binds_every_integer_as_bigint() {
assert_sql(
&postgres()
.table("users")
.filter(col("id").eq(1_i16) | col("id").eq(2_i32) | col("ratio").gt(0.5_f32)),
r#"select * from "users" where "id" = $1 or "id" = $2 or "ratio" > $3"#,
&[value(1_i64), value(2_i64), value(0.5_f64)],
);
}