use laravel::config::database::{ConnectionConfig, Database};
use laravel::db::schema::{Blueprint, Change, Lock, ReferentialAction, TypeKind};
use laravel::db::{self, AnyConnection, DatabaseManager, Driver, col, values};
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 sql(change: &Change<'_>) -> Vec<String> {
change.to_sql().unwrap()
}
#[track_caller]
fn error(change: &Change<'_>) -> String {
change.to_sql().unwrap_err().to_string()
}
fn posts(table: &mut Blueprint) {
table.id();
table.foreign_id("user_id").constrained().cascade_on_delete();
table.string("title");
table.string("slug").length(100).unique();
table.text("body").nullable().comment("The post's body");
table.string("status").default("draft");
table.integer("votes").unsigned().default(0);
table.decimal("price", 8, 2).default(-1.5);
table.boolean("featured").default(false);
table.json("tags").nullable();
table.integer("quantity").default(1);
table.integer("total").stored_as(col("price") * col("quantity"));
table.timestamp("published_at").nullable().use_current();
table.timestamps();
table.soft_deletes();
table.index(["user_id", "published_at"]);
table.check("posts_votes_check", col("votes").ge(0));
table.comment("Blog posts");
}
#[test]
fn borrowed_index_columns_keep_the_conventional_name() {
let columns = vec![String::from("tenant_id"), String::from("email")];
let array = [String::from("status"), String::from("created_at")];
assert_eq!(
sql(&sqlite().schema().alter("users", |table| {
table.drop_unique(&columns);
table.drop_unique(columns.as_slice());
table.drop_index(&array);
})),
[
"drop index `users_tenant_id_email_unique`",
"drop index `users_tenant_id_email_unique`",
"drop index `users_status_created_at_index`",
]
);
assert_eq!(columns, ["tenant_id", "email"]);
}
#[test]
fn creating_a_table_compiles_for_sqlite() {
assert_eq!(
sql(&sqlite().schema().create("posts", posts)),
[
"create table `posts` (`id` integer primary key autoincrement not null, `user_id` integer not null, `title` varchar not null, `slug` varchar not null, `body` text null, `status` varchar not null default 'draft', `votes` integer not null default 0, `price` numeric not null default (-1.5), `featured` tinyint(1) not null default 0, `tags` text null, `quantity` integer not null default 1, `total` integer generated always as (`price` * `quantity`) stored, `published_at` datetime null default current_timestamp, `created_at` datetime null, `updated_at` datetime null, `deleted_at` datetime null, constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade, constraint `posts_votes_check` check (`votes` >= 0))",
"create unique index `posts_slug_unique` on `posts` (`slug`)",
"create index `posts_user_id_published_at_index` on `posts` (`user_id`, `published_at`)",
]
);
}
#[cfg(feature = "database-postgres")]
#[test]
fn creating_a_table_compiles_for_postgres() {
assert_eq!(
sql(&postgres().schema().create("posts", posts)),
[
r#"create table "posts" ("id" bigserial not null primary key, "user_id" bigint not null, "title" varchar(255) not null, "slug" varchar(100) not null, "body" text null, "status" varchar(255) not null default E'draft', "votes" integer not null default 0, "price" decimal(8, 2) not null default (-1.5), "featured" boolean not null default FALSE, "tags" json null, "quantity" integer not null default 1, "total" integer generated always as ("price" * "quantity") stored, "published_at" timestamp(6) without time zone null default current_timestamp, "created_at" timestamp(6) without time zone null, "updated_at" timestamp(6) without time zone null, "deleted_at" timestamp(6) without time zone null, constraint "posts_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade, constraint "posts_votes_check" check ("votes" >= 0))"#,
r#"comment on column "posts"."body" is E'The post''s body'"#,
r#"alter table "posts" add constraint "posts_slug_unique" unique ("slug")"#,
r#"create index "posts_user_id_published_at_index" on "posts" ("user_id", "published_at")"#,
r#"comment on table "posts" is E'Blog posts'"#,
]
);
}
#[cfg(feature = "database-mysql")]
#[test]
fn creating_a_table_compiles_for_mysql_and_mariadb() {
let expected = [
"create table `posts` (`id` bigint unsigned not null auto_increment primary key, `user_id` bigint unsigned not null, `title` varchar(255) not null, `slug` varchar(100) not null, `body` text null comment 'The post''s body', `status` varchar(255) not null default _utf8mb4 X'6472616674', `votes` int unsigned not null default 0, `price` decimal(8, 2) not null default (-1.5), `featured` tinyint(1) not null default 0, `tags` json null, `quantity` int not null default 1, `total` int generated always as (`price` * `quantity`) stored, `published_at` datetime(6) null default current_timestamp(6), `created_at` datetime(6) null, `updated_at` datetime(6) null, `deleted_at` datetime(6) null, constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade, constraint `posts_votes_check` check (`votes` >= 0)) comment = 'Blog posts'",
"alter table `posts` add unique `posts_slug_unique`(`slug`)",
"alter table `posts` add index `posts_user_id_published_at_index`(`user_id`, `published_at`)",
];
assert_eq!(sql(&mysql().schema().create("posts", posts)), expected);
assert_eq!(sql(&mariadb().schema().create("posts", posts)), expected);
}
#[cfg(feature = "database-mysql")]
#[test]
fn mysql_options_apply_to_created_tables() {
let change = |db: AnyConnection| {
sql(&db.schema().create("events", |table| {
table.id();
table.json("payload").default(db::raw!("json_object()"));
table.text("note").default("none");
table.engine("InnoDB");
table.charset("utf8mb4");
table.collation("utf8mb4_unicode_ci");
}))
};
let expected = |note_default: &str| {
vec![format!(
"create table `events` (`id` bigint unsigned not null auto_increment primary key, `payload` json not null default (json_object()), `note` text not null default {note_default}) default character set utf8mb4 collate utf8mb4_unicode_ci engine = InnoDB"
)]
};
assert_eq!(change(mysql()), expected("(_utf8mb4 X'6e6f6e65')"));
assert_eq!(change(mariadb()), expected("'none'"));
}
fn types(table: &mut Blueprint) {
table.increments("a");
table.tiny_integer("b");
table.small_integer("c");
table.medium_integer("d");
table.big_integer("e");
table.float("f");
table.double("g");
table.char("h").length(2);
table.tiny_text("i");
table.medium_text("j");
table.long_text("k");
table.enumeration("l", ["x", "y"]);
table.jsonb("m");
table.date("n");
table.date_time("o").precision(3);
table.timestamp("p");
table.time("q");
table.time_tz("r");
table.timestamp("s");
table.year("t");
table.binary("u");
table.binary("v").length(16);
table.uuid("w");
table.ulid("x");
table.ip_address("y");
table.mac_address("z");
table.foreign_uuid("aa");
table.binary("ab").length(16).fixed();
table.morphs("taggable");
table.remember_token();
}
#[test]
fn column_types_compile_for_sqlite() {
assert_eq!(
sql(&sqlite().schema().create("types", types)),
[
"create table `types` (`a` integer primary key autoincrement not null, `b` integer not null, `c` integer not null, `d` integer not null, `e` integer not null, `f` float not null, `g` double not null, `h` varchar not null, `i` text not null, `j` text not null, `k` text not null, `l` varchar check (`l` in ('x', 'y')) not null, `m` text not null, `n` date not null, `o` datetime not null, `p` datetime not null, `q` time not null, `r` time not null, `s` datetime not null, `t` integer not null, `u` blob not null, `v` blob not null, `w` varchar not null, `x` varchar not null, `y` varchar not null, `z` varchar not null, `aa` varchar not null, `ab` blob not null, `taggable_type` varchar not null, `taggable_id` integer not null, `remember_token` varchar null)",
"create index `types_taggable_type_taggable_id_index` on `types` (`taggable_type`, `taggable_id`)",
]
);
}
#[cfg(feature = "database-postgres")]
#[test]
fn column_types_compile_for_postgres() {
assert_eq!(
sql(&postgres().schema().create("types", types)),
[
r#"create table "types" ("a" serial not null primary key, "b" smallint not null, "c" smallint not null, "d" integer not null, "e" bigint not null, "f" float(53) not null, "g" double precision not null, "h" char(2) not null, "i" text not null, "j" text not null, "k" text not null, "l" varchar(255) check ("l" in (E'x', E'y')) not null, "m" jsonb not null, "n" date not null, "o" timestamp(3) without time zone not null, "p" timestamp(6) without time zone not null, "q" time(6) without time zone not null, "r" time(6) with time zone not null, "s" timestamp(6) without time zone not null, "t" integer not null, "u" bytea not null, "v" bytea not null, "w" uuid not null, "x" char(26) not null, "y" varchar(45) not null, "z" varchar(17) not null, "aa" uuid not null, "ab" bytea not null, "taggable_type" varchar(255) not null, "taggable_id" bigint not null, "remember_token" varchar(100) null)"#,
r#"create index "types_taggable_type_taggable_id_index" on "types" ("taggable_type", "taggable_id")"#,
]
);
}
#[cfg(feature = "database-mysql")]
#[test]
fn column_types_compile_for_mysql_and_mariadb() {
// MariaDB has a `uuid` type, and MySQL stores UUIDs as text.
let expected = |uuid: &str| {
vec![
format!(
"create table `types` (`a` int unsigned not null auto_increment primary key, `b` tinyint not null, `c` smallint not null, `d` mediumint not null, `e` bigint not null, `f` float(53) not null, `g` double not null, `h` char(2) not null, `i` tinytext not null, `j` mediumtext not null, `k` longtext not null, `l` enum('x', 'y') not null, `m` json not null, `n` date not null, `o` datetime(3) not null, `p` datetime(6) not null, `q` time(6) not null, `r` time(6) not null, `s` datetime(6) not null, `t` year not null, `u` blob not null, `v` varbinary(16) not null, `w` {uuid} not null, `x` char(26) not null, `y` varchar(45) not null, `z` varchar(17) not null, `aa` {uuid} not null, `ab` binary(16) not null, `taggable_type` varchar(255) not null, `taggable_id` bigint unsigned not null, `remember_token` varchar(100) null)"
),
"alter table `types` add index `types_taggable_type_taggable_id_index`(`taggable_type`, `taggable_id`)"
.to_owned(),
]
};
assert_eq!(sql(&mysql().schema().create("types", types)), expected("char(36)"));
assert_eq!(sql(&mariadb().schema().create("types", types)), expected("uuid"));
}
fn added_columns(table: &mut Blueprint) {
table
.string("nickname")
.nullable()
.after("name")
.comment("Shown name")
.charset("utf8mb4")
.collation("utf8mb4_bin")
.instant();
table
.timestamp("seen_at")
.precision(6)
.use_current()
.use_current_on_update();
table.integer("score").virtual_as(col("votes") + 1).invisible();
table.string("code").first();
table.integer("legacy_id").default(db::raw!("42")).lock(Lock::None);
}
#[cfg(feature = "database-mysql")]
#[test]
fn column_modifiers_compile_for_mysql_and_mariadb() {
let expected = [
"alter table `users` add `nickname` varchar(255) character set utf8mb4 collate utf8mb4_bin null comment 'Shown name' after `name`, algorithm=instant",
"alter table `users` add `seen_at` datetime(6) not null default current_timestamp(6) on update current_timestamp(6)",
"alter table `users` add `score` int generated always as (`votes` + 1) virtual invisible",
"alter table `users` add `code` varchar(255) not null first",
"alter table `users` add `legacy_id` int not null default (42), lock=none",
];
assert_eq!(sql(&mysql().schema().alter("users", added_columns)), expected);
assert_eq!(sql(&mariadb().schema().alter("users", added_columns)), expected);
}
#[cfg(feature = "database-mysql")]
#[test]
fn grouped_columns_and_keys_compile_for_mysql() {
assert_eq!(
sql(&mysql().schema().alter("users", |table| {
table.after("password", |table| {
table.string("line1");
table.string("line2").nullable();
table.string("city").first();
table.string("zip");
});
table.timestamps().precision(6);
table.foreign_uuid("team_uuid").references("teams").column("uuid");
})),
[
"alter table `users` add `line1` varchar(255) not null after `password`",
"alter table `users` add `line2` varchar(255) null after `line1`",
"alter table `users` add `city` varchar(255) not null first",
"alter table `users` add `zip` varchar(255) not null after `city`",
"alter table `users` add `created_at` datetime(6) null",
"alter table `users` add `updated_at` datetime(6) null",
"alter table `users` add `team_uuid` char(36) not null",
"alter table `users` add constraint `users_team_uuid_foreign` foreign key (`team_uuid`) references `teams` (`uuid`)",
]
);
}
/// PostgreSQL 18 added virtual generated columns, and earlier versions reject them.
#[cfg(feature = "database-postgres")]
#[test]
fn column_modifiers_compile_for_postgres() {
assert_eq!(
sql(&postgres().schema().alter("users", added_columns)),
[
r#"alter table "users" add column "nickname" varchar(255) collate "utf8mb4_bin" null"#,
r#"alter table "users" add column "seen_at" timestamp(6) without time zone not null default current_timestamp"#,
r#"alter table "users" add column "score" integer generated always as ("votes" + 1) virtual"#,
r#"alter table "users" add column "code" varchar(255) not null"#,
r#"alter table "users" add column "legacy_id" integer not null default (42)"#,
r#"comment on column "users"."nickname" is E'Shown name'"#,
]
);
}
fn changed_columns(table: &mut Blueprint) {
table.string("name").length(50).nullable().instant().change();
table.integer("votes").default(5).comment("Up minus down").change();
}
#[cfg(feature = "database-postgres")]
#[test]
fn changing_columns_compiles_for_postgres() {
assert_eq!(
sql(&postgres().schema().alter("users", changed_columns)),
[
r#"alter table "users" alter column "name" type varchar(50), alter column "name" drop not null, alter column "name" drop default"#,
r#"alter table "users" alter column "votes" type integer, alter column "votes" set not null, alter column "votes" set default 5"#,
r#"comment on column "users"."name" is null"#,
r#"comment on column "users"."votes" is E'Up minus down'"#,
]
);
assert_eq!(
sql(&postgres().schema().alter("users", |table| {
table.date("birthday").change().using(db::raw!("birthday::date"));
})),
[
r#"alter table "users" alter column "birthday" type date using birthday::date, alter column "birthday" set not null, alter column "birthday" drop default"#,
r#"comment on column "users"."birthday" is null"#,
]
);
}
/// PostgreSQL creates a serial column's sequence in its table's schema, not on the search path.
#[cfg(feature = "database-postgres")]
#[test]
fn starting_values_restart_the_sequence_in_the_tables_schema() {
assert_eq!(
sql(&postgres().schema().create("billing.invoices", |table| {
table.id().starting_value(1000);
})),
[
r#"create table "billing"."invoices" ("id" bigserial not null primary key)"#,
r#"alter sequence "billing"."invoices_id_seq" restart with 1000"#,
]
);
}
#[cfg(feature = "database-mysql")]
#[test]
fn changing_columns_compiles_for_mysql_and_mariadb() {
let expected = [
"alter table `users` modify `name` varchar(50) null, algorithm=instant",
"alter table `users` modify `votes` int not null default 5 comment 'Up minus down'",
];
assert_eq!(sql(&mysql().schema().alter("users", changed_columns)), expected);
assert_eq!(sql(&mariadb().schema().alter("users", changed_columns)), expected);
}
fn dropped(table: &mut Blueprint) {
table.rename_column("bio", "about");
table
.drop_column(["legacy_flags", "legacy_notes"])
.instant()
.lock(Lock::None);
table.drop_index(["team_id"]);
table.drop_unique("users_slug_unique");
table.drop_full_text(["name", "about"]);
table.rename_index("users_email_index", "users_mail_index");
table.drop_foreign(["team_id"]);
table.drop_check("users_votes_check");
table.drop_primary();
}
/// A column's index exists before the blueprint's other commands run, so they can refer to it.
#[cfg(feature = "database-postgres")]
#[test]
fn column_indexes_come_before_the_blueprints_commands() {
let change = |table: &mut Blueprint| {
table.rename_index("users_email_unique", "users_mail_unique");
table.string("email").unique();
};
assert_eq!(
sql(&postgres().schema().alter("users", change)),
[
r#"alter table "users" add column "email" varchar(255) not null"#,
r#"alter table "users" add constraint "users_email_unique" unique ("email")"#,
r#"alter index "users_email_unique" rename to "users_mail_unique""#,
]
);
}
#[cfg(feature = "database-postgres")]
#[test]
fn dropping_and_renaming_compiles_for_postgres() {
assert_eq!(
sql(&postgres().schema().alter("users", dropped)),
[
r#"alter table "users" rename column "bio" to "about""#,
r#"alter table "users" drop column "legacy_flags", drop column "legacy_notes""#,
r#"drop index "users_team_id_index""#,
r#"alter table "users" drop constraint "users_slug_unique""#,
r#"drop index "users_name_about_fulltext""#,
r#"alter index "users_email_index" rename to "users_mail_index""#,
r#"alter table "users" drop constraint "users_team_id_foreign""#,
r#"alter table "users" drop constraint "users_votes_check""#,
r#"alter table "users" drop constraint "users_pkey""#,
]
);
assert_eq!(
sql(&postgres().schema().alter("analytics.events", |table| {
table.drop_index("events_kind_index");
table.rename_index("events_at_index", "events_seen_at_index");
})),
[
r#"drop index "analytics"."events_kind_index""#,
r#"alter index "analytics"."events_at_index" rename to "events_seen_at_index""#,
]
);
}
#[cfg(feature = "database-mysql")]
#[test]
fn dropping_and_renaming_compiles_for_mysql_and_mariadb() {
let expected = |drop_check: &str| {
vec![
"alter table `users` rename column `bio` to `about`".to_owned(),
"alter table `users` drop `legacy_flags`, drop `legacy_notes`, algorithm=instant, lock=none".to_owned(),
"alter table `users` drop index `users_team_id_index`".to_owned(),
"alter table `users` drop index `users_slug_unique`".to_owned(),
"alter table `users` drop index `users_name_about_fulltext`".to_owned(),
"alter table `users` rename index `users_email_index` to `users_mail_index`".to_owned(),
"alter table `users` drop foreign key `users_team_id_foreign`".to_owned(),
format!("alter table `users` {drop_check} `users_votes_check`"),
"alter table `users` drop primary key".to_owned(),
]
};
assert_eq!(sql(&mysql().schema().alter("users", dropped)), expected("drop check"));
assert_eq!(
sql(&mariadb().schema().alter("users", dropped)),
expected("drop constraint")
);
}
#[test]
fn sqlite_adds_and_renames_columns_in_place() {
assert_eq!(
sql(&sqlite().schema().alter("users", |table| {
table.rename_column("bio", "about");
table.drop_index(["team_id"]);
table.string("nickname").nullable().unique();
})),
[
"alter table `users` add column `nickname` varchar null",
"create unique index `users_nickname_unique` on `users` (`nickname`)",
"alter table `users` rename column `bio` to `about`",
"drop index `users_team_id_index`",
]
);
}
#[test]
fn sqlite_rebuilds_a_table_from_its_definition_when_it_runs() {
assert_eq!(
error(&sqlite().schema().alter("users", |table| {
table.string("name").nullable().change();
})),
"SQLite makes this change from the table's current definition, so it has no SQL until it runs"
);
assert_eq!(
error(&sqlite().schema().alter("users", |table| {
table.drop_column("legacy_flags");
})),
"SQLite makes this change from the table's current definition, so it has no SQL until it runs"
);
}
fn keys(table: &mut Blueprint) {
table
.unique("email")
.name("users_mail_unique")
.online()
.lock(Lock::None);
table.full_text(["name", "bio"]).language("simple");
table.primary(["id", "team_id"]);
table
.foreign(["team_id"])
.references("teams", ["id"])
.null_on_delete()
.cascade_on_update()
.initially_deferred()
.lock(Lock::Shared);
table.check("users_name_check", col("name").ne(""));
table.comment("People");
}
#[cfg(feature = "database-postgres")]
#[test]
fn indexes_and_constraints_compile_for_postgres() {
assert_eq!(
sql(&postgres().schema().alter("users", keys)),
[
r#"create unique index concurrently "users_mail_unique" on "users" ("email")"#,
r#"alter table "users" add constraint "users_mail_unique" unique using index "users_mail_unique""#,
r#"create index "users_name_bio_fulltext" on "users" using gin ((to_tsvector('simple', coalesce("name", '')) || to_tsvector('simple', coalesce("bio", ''))))"#,
r#"alter table "users" add primary key ("id", "team_id")"#,
r#"alter table "users" add constraint "users_team_id_foreign" foreign key ("team_id") references "teams" ("id") on delete set null on update cascade deferrable initially deferred"#,
r#"alter table "users" add constraint "users_name_check" check ("name" <> E'')"#,
r#"comment on table "users" is E'People'"#,
]
);
}
#[cfg(feature = "database-mysql")]
#[test]
fn indexes_and_constraints_compile_for_mysql_and_mariadb() {
let expected = |empty: &str| {
[
"alter table `users` add unique `users_mail_unique`(`email`), lock=none".to_owned(),
"alter table `users` add fulltext `users_name_bio_fulltext`(`name`, `bio`)".to_owned(),
"alter table `users` add primary key (`id`, `team_id`)".to_owned(),
"alter table `users` add constraint `users_team_id_foreign` foreign key (`team_id`) references `teams` (`id`) on delete set null on update cascade, lock=shared".to_owned(),
format!("alter table `users` add constraint `users_name_check` check (`name` <> {empty})"),
"alter table `users` comment = 'People'".to_owned(),
]
};
assert_eq!(sql(&mysql().schema().alter("users", keys)), expected("_utf8mb4 X''"));
assert_eq!(sql(&mariadb().schema().alter("users", keys)), expected("''"));
}
#[cfg(all(feature = "database-postgres", feature = "database-mysql"))]
#[test]
fn index_algorithms_actions_and_constrained_drops_compile_per_driver() {
let change = |table: &mut Blueprint| {
table.index("attributes").algorithm("gin");
table
.foreign_id("plan_id")
.default(1)
.references("plans")
.on_delete(ReferentialAction::SetDefault)
.on_update(ReferentialAction::Cascade);
table.drop_constrained_foreign_id("team_id").instant();
};
assert_eq!(
sql(&postgres().schema().alter("users", change)),
[
r#"alter table "users" add column "plan_id" bigint not null default 1"#,
r#"alter table "users" add constraint "users_plan_id_foreign" foreign key ("plan_id") references "plans" ("id") on delete set default on update cascade"#,
r#"create index "users_attributes_index" on "users" using gin ("attributes")"#,
r#"alter table "users" drop constraint "users_team_id_foreign""#,
r#"alter table "users" drop column "team_id""#,
]
);
assert_eq!(
sql(&mysql().schema().alter("users", change)),
[
"alter table `users` add `plan_id` bigint unsigned not null default 1",
"alter table `users` add constraint `users_plan_id_foreign` foreign key (`plan_id`) references `plans` (`id`) on delete set default on update cascade",
"alter table `users` add index `users_attributes_index`(`attributes`) using gin",
"alter table `users` drop foreign key `users_team_id_foreign`",
"alter table `users` drop `team_id`, algorithm=instant",
]
);
assert_eq!(
error(&postgres().schema().alter("users", |table| {
table.unique("email").algorithm("hash");
})),
"`algorithm` applies only to `index`, not to `users_email_unique`"
);
}
fn documents(table: &mut Blueprint) {
table.id();
table.vector("embedding", 3).index();
table.geography("place").spatial_index();
}
#[cfg(feature = "database-postgres")]
#[test]
fn vectors_compile_for_postgres() {
assert_eq!(
sql(&postgres().schema().ensure_vector_extension()),
["create extension if not exists vector"]
);
assert_eq!(
sql(&postgres().schema().create("documents", documents)),
[
r#"create table "documents" ("id" bigserial not null primary key, "embedding" vector(3) not null, "place" geography(geometry, 4326) not null)"#,
r#"create index "documents_embedding_vectorindex" on "documents" using hnsw ("embedding" vector_cosine_ops)"#,
r#"create index "documents_place_spatialindex" on "documents" using gist ("place")"#,
]
);
}
/// MariaDB 11.7 added vectors. The local MariaDB is 10.11, so only the SQL is checked.
#[cfg(feature = "database-mysql")]
#[test]
fn vectors_compile_for_mariadb_only() {
assert_eq!(
sql(&mariadb().schema().create("documents", documents)),
[
"create table `documents` (`id` bigint unsigned not null auto_increment primary key, `embedding` vector(3) not null, `place` geometry ref_system_id=4326 not null)",
"alter table `documents` add vector index `documents_embedding_vectorindex`(`embedding`) distance=cosine",
"alter table `documents` add spatial index `documents_place_spatialindex`(`place`)",
]
);
assert_eq!(
error(&mysql().schema().create("documents", documents)),
"vector columns run only on PostgreSQL with pgvector and on MariaDB 11.7 or later"
);
assert_eq!(
error(&mariadb().schema().ensure_vector_extension()),
"the vector extension is a PostgreSQL extension"
);
}
#[test]
fn sqlite_has_no_vectors() {
assert_eq!(
error(&sqlite().schema().create("documents", documents)),
"vector columns run only on PostgreSQL with pgvector and on MariaDB 11.7 or later"
);
}
#[test]
fn tables_drop_and_rename() {
let changes = |db: AnyConnection| {
[
sql(&db.schema().drop("flights")),
sql(&db.schema().drop_if_exists("analytics.flights")),
sql(&db.schema().rename("flights", "trips")),
]
.concat()
};
assert_eq!(
changes(sqlite()),
[
"drop table `flights`",
"drop table if exists `analytics`.`flights`",
"alter table `flights` rename to `trips`",
]
);
#[cfg(feature = "database-postgres")]
assert_eq!(
changes(postgres()),
[
r#"drop table "flights""#,
r#"drop table if exists "analytics"."flights""#,
r#"alter table "flights" rename to "trips""#,
r#"alter index if exists "flights_pkey" rename to "trips_pkey""#,
]
);
#[cfg(feature = "database-mysql")]
assert_eq!(
changes(mysql()),
[
"drop table `flights`",
"drop table if exists `analytics`.`flights`",
"rename table `flights` to `trips`",
]
);
}
#[test]
fn misused_blueprints_fail_with_the_fix() {
let db = sqlite();
assert_eq!(
error(&db.schema().create("users", |table| {
table.string("name").unsigned();
})),
"`unsigned` doesn't apply to the string column `name`"
);
assert_eq!(
error(&db.schema().create("users", |table| {
table.drop_column("name");
})),
"`drop_column` can't run in `create`; use `alter`"
);
assert_eq!(
error(&db.schema().create("users", |table| {
table.string("name").change();
})),
"`change` can't run in `create`, as on column `name`"
);
assert_eq!(
error(&db.schema().alter("users", |table| {
table.engine("InnoDB");
})),
"`temporary`, `engine`, `charset`, and `collation` apply only to `create`"
);
assert_eq!(
error(&db.schema().create("users", |table| {
table.full_text("bio");
})),
"full-text indexes run on PostgreSQL, MySQL, and MariaDB, not SQLite"
);
assert_eq!(
error(&db.schema().alter("users", |table| {
table.date("birthday").using(db::raw!("birthday::date"));
})),
"`using` converts the values of a column that `change` changes; add `change` to column `birthday`"
);
assert_eq!(
error(&db.schema().create("users", |table| {
table.integer("number").starting_value(1000);
})),
"`starting_value` needs an auto-incrementing column; add `auto_increment` to column `number`"
);
let numbered = db.schema().create("invoices", |table| {
table.integer("number").starting_value(1000).auto_increment();
});
assert!(numbered.to_sql().is_ok(), "the modifiers' order doesn't matter");
}
#[cfg(feature = "database-mysql")]
#[test]
fn mysql_comments_and_mariadb_expressions_reject_backslashes() {
assert_eq!(
error(&mysql().schema().create("files", |table| {
table.string("path").comment(r"C:\files");
})),
r"MySQL and MariaDB comments and enumeration values can't contain `\` or NUL, as in `C:\files`"
);
assert_eq!(
error(&mariadb().schema().create("files", |table| {
table.text("path").default(r"C:\files");
})),
r"MariaDB stores checks, generated columns, and the defaults of text and JSON columns as expressions, which can't contain text with `\` or NUL, as in `C:\files`"
);
}
/// Create, change, inspect, and drop tables on a real database. The tables start with `sb_`, and
/// the contract drops them first, so it can run again on the same database.
async fn execution_contract(db: AnyConnection) -> laravel::Result<()> {
let driver = db.driver();
for table in ["sb_comments", "sb_articles", "sb_posts", "sb_users"] {
db.schema().drop_if_exists(table).await?;
}
db.schema()
.create("sb_users", |table| {
table.id();
table.string("name").comment("Shown on posts");
table.string("email").unique();
table.string("motto").default("a, (b");
table.text("bio").default("it's \"mine\"");
table.enumeration("role", ["admin", "member"]).default("member");
table.integer("votes").default(0);
table.boolean("admin").default(false);
table.json("settings").nullable();
table.timestamps();
table.check("sb_users_votes_check", col("votes").ge(0));
table.check("sb_users_name_check", col("name").ne("it's nobody"));
})
.await?;
assert!(db.schema().has_table("sb_users").await?);
assert!(!db.schema().has_table("sb_missing").await?);
assert!(db.schema().has_column("sb_users", "EMAIL").await?);
assert!(db.schema().has_index("sb_users", "sb_users_email_unique").await?);
let columns = db.schema().columns("sb_users").await?;
let names: Vec<&str> = columns.iter().map(|column| column.name.as_str()).collect();
assert_eq!(
names,
[
"id",
"name",
"email",
"motto",
"bio",
"role",
"votes",
"admin",
"settings",
"created_at",
"updated_at"
]
);
assert!(columns[0].auto_increment);
assert!(!columns[1].nullable && columns[8].nullable);
assert!(columns[3].default.is_some() && columns[1].default.is_none());
let tables: Vec<String> = db
.schema()
.tables()
.await?
.into_iter()
.map(|table| table.name)
.collect();
assert!(tables.iter().any(|name| name == "sb_users"), "{tables:?}");
let users = || db.table("sb_users");
users()
.insert(values! { name: "Taylor", email: "taylor@example.com" })
.await?;
let (motto, bio, role, votes): (String, String, String, i64) =
users().select(["motto", "bio", "role", "votes"]).sole().await?;
assert_eq!(
(motto.as_str(), bio.as_str(), role.as_str(), votes),
("a, (b", "it's \"mine\"", "member", 0)
);
assert!(
users()
.insert(values! { name: "Negative", email: "n@example.com", votes: -1 })
.await
.is_err()
);
assert!(
users()
.insert(values! { name: "it's nobody", email: "nobody@example.com" })
.await
.is_err()
);
db.schema()
.create("sb_posts", |table| {
table.id();
table
.foreign_id("user_id")
.references("sb_users")
.cascade_on_delete()
.deferrable();
table.string("title");
table.text("body").nullable();
table.integer("price");
table.integer("quantity").default(1);
table.integer("total").stored_as(col("price") * col("quantity"));
table.timestamps();
table.index(["user_id", "created_at"]).online();
if driver != Driver::Sqlite {
table.full_text(["title", "body"]);
}
})
.await?;
let posts = || db.table("sb_posts");
posts()
.insert(values! { user_id: 1, title: "Hello", price: 3, quantity: 4 })
.await?;
assert_eq!(posts().value::<i64>("total").await?, Some(12));
let indexes = db.schema().indexes("sb_posts").await?;
let index = indexes
.iter()
.find(|index| index.name == "sb_posts_user_id_created_at_index")
.unwrap();
assert_eq!(index.columns, ["user_id", "created_at"]);
assert!(!index.unique && !index.primary);
assert!(indexes.iter().any(|index| index.primary), "{indexes:?}");
let keys = db.schema().foreign_keys("sb_posts").await?;
let [key] = keys.as_slice() else {
panic!("one foreign key: {keys:?}")
};
assert_eq!(
(
key.columns.as_slice(),
key.foreign_table.as_str(),
key.foreign_columns.as_slice()
),
(&["user_id".to_owned()][..], "sb_users", &["id".to_owned()][..])
);
assert_eq!(key.on_delete, ReferentialAction::Cascade);
// MySQL and MariaDB restrict by default, and PostgreSQL and SQLite take no action.
assert!(
matches!(key.on_update, ReferentialAction::NoAction | ReferentialAction::Restrict),
"{key:?}"
);
let expected_name = (driver != Driver::Sqlite).then(|| "sb_posts_user_id_foreign".to_owned());
assert_eq!(key.name, expected_name);
assert!(db.schema().has_columns("sb_posts", ["TITLE", "body"]).await?);
assert!(!db.schema().has_columns("sb_posts", ["title", "subtitle"]).await?);
db.query("create view sb_titles as select title from sb_posts")
.statement()
.await?;
let views = db.schema().views().await?;
assert!(
views
.iter()
.any(|view| view.name == "sb_titles" && view.definition.contains("title")),
"{views:?}"
);
assert!(db.schema().has_view("SB_TITLES").await?);
assert!(!db.schema().has_view("sb_posts").await?);
db.query("drop view sb_titles").statement().await?;
match driver {
Driver::Postgres => {
db.query("create type sb_mood as enum ('happy', 'sad')")
.statement()
.await?;
let types = db.schema().types().await?;
db.query("drop type sb_mood").statement().await?;
let mood = types.iter().find(|kind| kind.name == "sb_mood");
assert_eq!(mood.map(|mood| mood.kind), Some(TypeKind::Enum), "{types:?}");
assert!(
!types.iter().any(|kind| kind.name == "_sb_mood"),
"array types are left out"
);
}
_ => assert_eq!(
db.schema().types().await.unwrap_err().to_string(),
"only PostgreSQL has user-defined types"
),
}
// Child rows can come before their parents, and the checks are back on afterwards.
if driver != Driver::Postgres {
db.schema()
.without_foreign_key_constraints(async |_| {
db.table("sb_posts")
.insert(values! { user_id: 900, title: "Early", price: 1 })
.await?;
db.table("sb_users")
.insert(values! { id: 900, name: "Late", email: "late@example.com" })
.await?;
Ok(())
})
.await?;
assert_eq!(posts().filter(col("user_id").eq(900)).count().await?, 1);
}
assert!(
posts()
.insert(values! { user_id: 901, title: "Orphan", price: 1 })
.await
.is_err(),
"foreign key checks are on again"
);
// Inside a transaction, such as a seeder's, the callback runs in a savepoint, and PostgreSQL
// checks the references it deferred when it ends.
{
db.transaction(async |_| {
db.schema()
.without_foreign_key_constraints(async |_| {
db.table("sb_posts")
.insert(values! { user_id: 903, title: "Seeded", price: 1 })
.await?;
db.table("sb_users")
.insert(values! { id: 903, name: "Seeder", email: "seeder@example.com" })
.await?;
Ok(())
})
.await?;
let orphan = db
.transaction(async |_| {
posts()
.insert(values! { user_id: 904, title: "Orphan", price: 1 })
.await
})
.await;
assert!(
orphan.is_err(),
"foreign key checks are on again inside the transaction"
);
Ok(())
})
.await?;
assert_eq!(posts().filter(col("user_id").eq(903)).count().await?, 1);
posts().filter(col("user_id").eq(903)).delete().await?;
db.table("sb_users").filter(col("id").eq(903)).delete().await?;
}
if driver == Driver::Sqlite {
let broken = db
.schema()
.without_foreign_key_constraints(async |_| {
db.table("sb_posts")
.insert(values! { user_id: 902, title: "Orphan", price: 1 })
.await
})
.await;
assert!(broken.is_err(), "SQLite checks every reference before it commits");
assert_eq!(posts().filter(col("user_id").eq(902)).count().await?, 0);
}
posts().filter(col("user_id").eq(900)).delete().await?;
db.table("sb_users").filter(col("id").eq(900)).delete().await?;
// SQLite rebuilds `sb_users` to change a column. Dropping the old table mustn't cascade to the post.
db.schema()
.alter("sb_users", |table| {
table.string("name").length(100).nullable().change();
})
.await?;
assert_eq!(posts().count().await?, 1);
assert!(
posts()
.insert(values! { user_id: 404, title: "Orphan", price: 1 })
.await
.is_err(),
"foreign keys are enforced again after the change"
);
if driver == Driver::Sqlite {
let refused = db
.transaction(async |tx| {
tx.schema()
.alter("sb_users", |table| {
table.string("name").length(120).nullable().change();
})
.await
})
.await
.unwrap_err()
.to_string();
assert!(
refused.starts_with(
"SQLite can't rebuild table `sb_users` inside a transaction while rows in `sb_posts` reference it"
),
"{refused}"
);
assert_eq!(posts().count().await?, 1);
}
let name = &db.schema().columns("sb_users").await?[1];
assert!(name.nullable);
assert_eq!(name.comment, None, "the changed column keeps no comment");
assert_eq!(users().value::<String>("motto").await?.as_deref(), Some("a, (b"));
assert!(db.schema().has_index("sb_users", "sb_users_email_unique").await?);
assert!(
users()
.insert(values! { name: "Negative", email: "n@example.com", votes: -1 })
.await
.is_err()
);
users()
.insert(values! { name: None::<String>, email: "nameless@example.com" })
.await?;
db.schema()
.alter("sb_users", |table| {
table.string("nickname").nullable().instant();
table.rename_column("motto", "tagline");
table.rename_index("sb_users_email_unique", "sb_users_mail_unique");
})
.await?;
assert!(db.schema().has_column("sb_users", "tagline").await?);
assert!(db.schema().has_index("sb_users", "sb_users_mail_unique").await?);
assert!(!db.schema().has_index("sb_users", "sb_users_email_unique").await?);
db.schema()
.alter("sb_users", |table| {
table.timestamp("seen_at").nullable().use_current();
table.integer("double_votes").stored_as(col("votes") * 2);
table.string("source").default(db::raw!("lower('WEB')"));
table.string("code").nullable().unique();
table.index(["name", "code"]).lock(Lock::None);
})
.await?;
assert!(db.schema().has_index("sb_users", ["name", "code"]).await?);
assert!(!db.schema().has_index("sb_users", ["code", "name"]).await?);
assert!(db.schema().has_unique("sb_users", ["code"]).await?);
assert!(!db.schema().has_unique("sb_users", ["name", "code"]).await?);
let (source, double_votes): (String, i64) = users()
.select(["source", "double_votes"])
.filter(col("email").eq("taylor@example.com"))
.sole()
.await?;
assert_eq!((source.as_str(), double_votes), ("web", 0));
db.schema()
.alter("sb_users", |table| {
table.drop_column(["seen_at", "double_votes", "source", "code"]);
})
.await?;
assert!(!db.schema().has_column("sb_users", "code").await?);
db.schema()
.alter("sb_users", |table| {
table.drop_unique("sb_users_mail_unique");
table.drop_column("nickname");
table.drop_check("sb_users_votes_check");
})
.await?;
assert!(!db.schema().has_column("sb_users", "nickname").await?);
users()
.insert(values! { name: "Negative", email: "n@example.com", votes: -1 })
.await?;
db.schema()
.alter("sb_posts", |table| {
table.drop_foreign(["user_id"]);
})
.await?;
posts()
.insert(values! { user_id: 404, title: "Orphan", price: 1 })
.await?;
let constrain = db
.schema()
.alter("sb_posts", |table| {
table.foreign(["user_id"]).references("sb_users", ["id"]);
})
.await;
assert!(constrain.is_err(), "the orphan fails the new foreign key");
assert_eq!(posts().filter(col("user_id").eq(404)).count().await?, 1);
db.schema().rename("sb_posts", "sb_articles").await?;
assert!(db.schema().has_table("sb_articles").await?);
assert!(!db.schema().has_table("sb_posts").await?);
if driver != Driver::Sqlite {
db.schema()
.alter("sb_articles", |table| {
table.big_integer("id").change();
table.drop_primary();
})
.await?;
assert!(
!db.schema()
.indexes("sb_articles")
.await?
.iter()
.any(|index| index.primary)
);
}
// Adding an enumeration value and widening an auto-incrementing key are common changes.
db.schema().drop_if_exists("sb_tickets").await?;
db.schema()
.create("sb_tickets", |table| {
table.increments("id");
table.enumeration("status", ["open", "closed"]).default("open");
})
.await?;
let tickets = || db.table("sb_tickets");
tickets().insert(values! { status: "closed" }).await?;
db.schema()
.alter("sb_tickets", |table| {
table.big_increments("id").change();
table
.enumeration("status", ["open", "closed", "archived"])
.default("open")
.change();
})
.await?;
tickets().insert(values! { status: "archived" }).await?;
assert!(
tickets().insert(values! { status: "lost" }).await.is_err(),
"the new values are still checked"
);
assert_eq!(tickets().pluck::<i64>("id").await?, [1, 2]);
db.schema()
.alter("sb_tickets", |table| {
table.foreign_id("owner_id").nullable().references("sb_users");
table.index("owner_id").algorithm("btree");
})
.await?;
assert!(db.schema().has_index("sb_tickets", ["owner_id"]).await?);
db.schema()
.alter("sb_tickets", |table| {
table.drop_constrained_foreign_id("owner_id");
})
.await?;
assert!(!db.schema().has_column("sb_tickets", "owner_id").await?);
assert!(!db.schema().has_index("sb_tickets", ["owner_id"]).await?);
assert!(db.schema().foreign_keys("sb_tickets").await?.is_empty());
db.schema().drop("sb_tickets").await?;
db.schema().drop("sb_articles").await?;
db.schema().drop("sb_users").await?;
assert!(!db.schema().has_table("sb_users").await?);
Ok(())
}
/// Changes in a transaction roll back with it on PostgreSQL and SQLite.
async fn transaction_contract(db: AnyConnection) -> laravel::Result<()> {
db.schema().drop_if_exists("sb_tags").await?;
let failed = db
.transaction(async |tx| {
tx.schema()
.create("sb_tags", |table| {
table.id();
table.string("name");
})
.await?;
tx.query("insert into sb_tags (name) values ('rust')").insert().await?;
tx.schema()
.alter("sb_tags", |table| {
table.string("name").nullable().change();
})
.await?;
assert!(tx.schema().has_table("sb_tags").await?);
Err::<(), _>(laravel::abort_with(500, "roll back"))
})
.await;
assert_eq!(failed.unwrap_err().to_string(), "roll back");
assert!(!db.schema().has_table("sb_tags").await?);
Ok(())
}
#[tokio::test]
async fn schema_builder_runs_on_sqlite() -> laravel::Result<()> {
let directory = tempfile::tempdir()?;
let url = format!("sqlite://{}?mode=rwc", directory.path().join("schema.sqlite").display());
execution_contract(connect(&url)).await?;
transaction_contract(connect(&url)).await
}
#[tokio::test]
async fn sqlite_can_truncate_related_tables_with_foreign_key_checks_off() -> laravel::Result<()> {
let db = sqlite();
db.schema()
.create("users", |table| {
table.id();
})
.await?;
db.schema()
.create("posts", |table| {
table.id();
table.foreign_id("user_id").constrained();
})
.await?;
db.table("users").insert(values! { id: 41 }).await?;
db.table("posts").insert(values! { id: 17, user_id: 41 }).await?;
db.schema()
.without_foreign_key_constraints(async |_| {
db.table("users").truncate().await?;
db.table("posts").truncate().await
})
.await?;
assert_eq!(db.table("users").count().await?, 0);
assert_eq!(db.table("posts").count().await?, 0);
assert!(db.table("posts").insert(values! { user_id: 41 }).await.is_err());
let user = db
.table("users")
.insert_get_id(values! { id: None::<i64> }, "id")
.await?;
assert_eq!(user, 1);
assert_eq!(
db.table("posts").insert_get_id(values! { user_id: user }, "id").await?,
1
);
Ok(())
}
/// A virtual table is one table to an application. SQLite keeps its data in shadow tables.
#[tokio::test]
async fn sqlite_lists_a_virtual_table_without_its_shadow_tables() -> laravel::Result<()> {
let directory = tempfile::tempdir()?;
let db = connect(&format!(
"sqlite://{}?mode=rwc",
directory.path().join("schema.sqlite").display()
));
db.query("create table users (id integer primary key); create virtual table users_search using fts5(email)")
.unprepared()
.await?;
let tables: Vec<String> = db
.schema()
.tables()
.await?
.into_iter()
.map(|table| table.name)
.collect();
assert_eq!(tables, ["users", "users_search"]);
Ok(())
}
/// A rebuild keeps what the table had besides its definition: the views that select from it, the
/// keys its `autoincrement` sequence handed out, and a primary key on the column it changes.
#[tokio::test]
async fn sqlite_rebuilds_keep_views_sequences_and_keys() -> laravel::Result<()> {
let directory = tempfile::tempdir()?;
let db = connect(&format!(
"sqlite://{}?mode=rwc",
directory.path().join("rebuild.sqlite").display()
));
db.schema()
.create("receipts", |table| {
table.id();
table.string("number");
})
.await?;
db.query("create view receipt_numbers as select number from receipts")
.statement()
.await?;
db.table("receipts")
.insert([
values! { number: "1" },
values! { number: "2" },
values! { number: "3" },
])
.await?;
db.table("receipts").filter(col("id").eq(3)).delete().await?;
db.schema()
.alter("receipts", |table| {
table.string("number").length(20).change();
})
.await?;
assert_eq!(db.table("receipt_numbers").count().await?, 2);
assert_eq!(
db.table("receipts")
.insert_get_id(values! { number: "4" }, "id")
.await?,
4
);
db.schema()
.alter("receipts", |table| {
table.big_integer("id").change();
})
.await?;
let primary: Vec<Vec<String>> = db
.schema()
.indexes("receipts")
.await?
.into_iter()
.filter(|index| index.primary)
.map(|index| index.columns)
.collect();
assert_eq!(primary, [["id"]]);
Ok(())
}
/// Each SQLite connection caches the schema. A connection that last read it before another
/// connection changed a table still finds the columns that change added.
#[tokio::test]
async fn sqlite_changes_see_columns_another_connection_added() -> laravel::Result<()> {
let directory = tempfile::tempdir()?;
let url = format!("sqlite://{}?mode=rwc", directory.path().join("shared.sqlite").display());
let single = || {
let mut config = ConnectionConfig::new(&url);
config.max_connections = 1;
DatabaseManager::new(&Database::default(), "/tmp")
.connect(config)
.unwrap()
};
let (first, second) = (single(), single());
first
.schema()
.create("visits", |table| {
table.id();
})
.await?;
assert_eq!(second.table("visits").count().await?, 0);
first
.schema()
.alter("visits", |table| {
table.string("path").nullable();
table.string("referrer").nullable();
})
.await?;
second
.schema()
.alter("visits", |table| {
table.rename_column("path", "url");
})
.await?;
second
.schema()
.alter("visits", |table| {
table.drop_column("referrer");
})
.await?;
let columns: Vec<String> = second
.schema()
.columns("visits")
.await?
.into_iter()
.map(|column| column.name)
.collect();
assert_eq!(columns, ["id", "url"]);
Ok(())
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn schema_builder_runs_on_postgres() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_POSTGRES_URL")?;
execution_contract(connect(&url)).await?;
transaction_contract(connect(&url)).await
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable MySQL or MariaDB database"]
async fn schema_builder_runs_on_mysql() -> laravel::Result<()> {
execution_contract(connect(&crate::support::mysql_or_mariadb_url().await?)).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 vector_columns_run_on_postgres_with_pgvector() -> laravel::Result<()> {
let config =
crate::support::fresh_database(&std::env::var("LARAVEL_TEST_POSTGRES_URL")?, "laravel_schema_vector").await?;
let db = DatabaseManager::new(&Database::default(), "/tmp").connect(config)?;
db.schema().ensure_vector_extension().await?;
db.schema()
.create("sb_documents", |table| {
table.id();
table.vector("embedding", 3).index();
})
.await?;
db.table("sb_documents")
.insert([
values! { embedding: db::vector(&[1.0, 0.0, 0.0]) },
values! { embedding: db::vector(&[0.0, 1.0, 0.0]) },
])
.await?;
let nearest: Vec<i64> = db
.table("sb_documents")
.similar_to("embedding", &[0.9, 0.1, 0.0], 0.5)
.pluck("id")
.await?;
assert_eq!(nearest, [1]);
assert!(
db.schema()
.has_index("sb_documents", "sb_documents_embedding_vectorindex")
.await?
);
Ok(())
}
/// Each column type reads back as its Rust type on every database. Timestamps read as both
/// `Timestamp` and `DateTime`, whether or not the column stores a time zone.
async fn column_values_round_trip(db: AnyConnection) -> laravel::Result<()> {
use laravel::numeric::Decimal;
use laravel::time::Timestamp;
use laravel::time::civil::DateTime;
use std::net::IpAddr;
db.schema().drop_if_exists("sb_values").await?;
db.schema()
.create("sb_values", |table| {
table.decimal("price", 8, 2);
table.date_time("starts_at");
table.timestamp("ends_at");
table.timestamps();
table.uuid("token");
table.ip_address("ip");
table.mac_address("mac");
})
.await?;
let at: Timestamp = "2026-11-02T13:45:10Z".parse()?;
db.table("sb_values")
.insert(values! {
price: "19.99".parse::<Decimal>()?,
starts_at: at,
ends_at: at,
created_at: at,
updated_at: at,
token: "67e55044-10b1-426f-9247-bb680e5fe0c8".parse::<uuid::Uuid>()?,
ip: "192.168.1.1".parse::<IpAddr>()?,
mac: "00:1b:44:11:3a:b7",
})
.await?;
let row = || db.table("sb_values");
let civil: DateTime = "2026-11-02T13:45:10".parse()?;
assert_eq!(row().value::<Decimal>("price").await?, Some("19.99".parse()?));
for column in ["starts_at", "ends_at", "created_at", "updated_at"] {
assert_eq!(row().value::<Timestamp>(column).await?, Some(at), "{column}");
assert_eq!(row().value::<DateTime>(column).await?, Some(civil), "{column}");
}
assert_eq!(
row().value::<String>("token").await?.as_deref(),
Some("67e55044-10b1-426f-9247-bb680e5fe0c8")
);
assert_eq!(row().value::<IpAddr>("ip").await?, Some("192.168.1.1".parse()?));
assert_eq!(row().value::<String>("ip").await?.as_deref(), Some("192.168.1.1"));
assert_eq!(
row().value::<String>("mac").await?.as_deref(),
Some("00:1b:44:11:3a:b7")
);
db.schema().drop("sb_values").await
}
#[tokio::test]
async fn column_values_round_trip_on_sqlite() -> laravel::Result<()> {
let directory = tempfile::tempdir()?;
let url = format!("sqlite://{}?mode=rwc", directory.path().join("values.sqlite").display());
column_values_round_trip(connect(&url)).await
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn column_values_round_trip_on_postgres() -> laravel::Result<()> {
column_values_round_trip(connect(&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 column_values_round_trip_on_mysql() -> laravel::Result<()> {
column_values_round_trip(connect(&crate::support::mysql_or_mariadb_url().await?)).await
}