Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ insta-cmd = "0.7"
ipnet = { version = "2", features = ["serde"] }
is_terminal_polyfill = "1.70"
lettre = { version = "0.11.23", default-features = false }
linkme = "0.3"
libtest-mimic = "0.8"
matchit = "0.9.2"
mime = "0.3"
Expand Down
69 changes: 69 additions & 0 deletions cot-macros/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,14 @@ struct ModelBuilder {
fields_as_update_from_db: Vec<TokenStream>,
fields_as_get_values: Vec<TokenStream>,
fields_as_field_refs: Vec<TokenStream>,
fields_as_migration_fields: Vec<TokenStream>,
}

impl ToTokens for ModelBuilder {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.append_all(self.build_model_impl());
tokens.append_all(self.build_fields_struct());
tokens.append_all(self.build_model_registration());
}
}

Expand Down Expand Up @@ -118,6 +120,7 @@ impl ModelBuilder {
fields_as_update_from_db: Vec::with_capacity(field_count),
fields_as_get_values: Vec::with_capacity(field_count),
fields_as_field_refs: Vec::with_capacity(field_count),
fields_as_migration_fields: Vec::with_capacity(field_count),
};
for field in &model.fields {
model_builder.push_field(field);
Expand Down Expand Up @@ -153,13 +156,50 @@ impl ModelBuilder {
#index => &self.#name as &dyn #orm_ident::ToDbFieldValue
));

self.fields_as_migration_fields
.push(Self::migration_field(field));

self.fields_as_field_refs.push(quote!(
#[doc = concat!("Field reference to [`", stringify!(#name), "::", stringify!(#column_name), "`].")]
pub const #name: #orm_ident::query::expr::FieldRef<#ty> =
#orm_ident::query::expr::FieldRef::<#ty>::new(#orm_ident::Identifier::new(#column_name));
));
}

/// Builds the `cot::db::migrations::Field` for given field.
#[must_use]
fn migration_field(field: &Field) -> TokenStream {
let orm_ident = orm_ident();
let column_name = &field.column_name;
let ty = &field.ty;
let as_db_field = quote!(<#ty as #orm_ident::DatabaseField>);
let fk_spec = field.foreign_key.as_ref();
let on_delete = fk_spec.and_then(|fk| fk.on_delete).unwrap_or_default();
let on_update = fk_spec.and_then(|fk| fk.on_update).unwrap_or_default();

let mut tokens = quote! {
let field = #orm_ident::migrations::Field::new(
#orm_ident::Identifier::new(#column_name),
#as_db_field::TYPE,
)
.set_null(#as_db_field::NULLABLE);
let field = if #as_db_field::AUTO { field.auto() } else { field };
let field = match #as_db_field::FOREIGN_KEY {
Some((table_name, column_name)) => {
field.foreign_key(table_name, column_name, #on_delete, #on_update)
}
None => field,
};
};
if field.primary_key {
tokens.extend(quote!(let field = field.primary_key();));
}
if field.unique {
tokens.extend(quote!(let field = field.unique();));
}
quote!({ #tokens field })
}

#[must_use]
fn build_model_impl(&self) -> TokenStream {
let crate_ident = cot_ident();
Expand All @@ -181,6 +221,7 @@ impl ModelBuilder {
let fields_as_from_db = &self.fields_as_from_db;
let fields_as_update_from_db = &self.fields_as_update_from_db;
let fields_as_get_values = &self.fields_as_get_values;
let fields_as_migration_fields = &self.fields_as_migration_fields;

quote! {
#[#crate_ident::__private::async_trait]
Expand All @@ -192,6 +233,9 @@ impl ModelBuilder {
const COLUMNS: &'static [#orm_ident::Column] = &[
#(#fields_as_columns,)*
];
const MIGRATION_FIELDS: &'static [#orm_ident::migrations::Field] = &[
#(#fields_as_migration_fields,)*
];
const MODEL_TYPE: #orm_ident::ModelType = #model_type;
const APP_NAME: &'static str = #app_name;
const TABLE_NAME: #orm_ident::Identifier = #orm_ident::Identifier::new(#table_name);
Expand Down Expand Up @@ -244,6 +288,31 @@ impl ModelBuilder {
}
}

/// Registers application models globally, so that the CLI can generate
/// migrations for them.
#[must_use]
fn build_model_registration(&self) -> TokenStream {
if self.model_type != ModelType::Application {
return TokenStream::new();
}

let crate_ident = cot_ident();
let orm_ident = orm_ident();
let name = &self.name;
let linkme = quote!(#crate_ident::__private::linkme);
let schema = quote!(#orm_ident::migrations::schema);

quote! {
// `distributed_slice` uses `#[link_section]`, which counts as unsafe code
#[allow(unsafe_code)]
const _: () = {
#[#linkme::distributed_slice(#schema::MODELS)]
#[linkme(crate = #linkme)]
static MODEL: #schema::ModelSchema = #schema::ModelSchema::of::<#name>();
};
}
}

#[must_use]
fn build_fields_struct(&self) -> TokenStream {
let name = &self.name;
Expand Down
3 changes: 2 additions & 1 deletion cot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ hyper = { workspace = true, features = ["http1", "server"] }
hyper-util = { workspace = true, features = ["http1", "server-graceful", "tokio"] }
idna = { workspace = true, optional = true }
indexmap.workspace = true
linkme = { workspace = true, optional = true }
ipnet.workspace = true
is_terminal_polyfill.workspace = true
lettre = { workspace = true, features = ["builder", "sendmail-transport", "smtp-transport", "tokio1", "tokio1-rustls", "ring", "rustls-platform-verifier"], optional = true }
Expand Down Expand Up @@ -111,7 +112,7 @@ ignored = [
default = ["sqlite", "postgres", "mysql", "json"]
full = ["default", "fake", "live-reload", "test", "cache", "redis", "email"]
fake = ["dep:fake"]
db = ["dep:sea-query", "dep:sea-query-sqlx", "dep:sqlx"]
db = ["dep:linkme", "dep:sea-query", "dep:sea-query-sqlx", "dep:sqlx"]
email = ["dep:lettre", "dep:idna"]
sqlite = ["db", "sea-query/backend-sqlite", "sea-query-sqlx/sqlx-sqlite", "sqlx/sqlite"]
postgres = ["db", "sea-query/backend-postgres", "sea-query-sqlx/sqlx-postgres", "sqlx/postgres"]
Expand Down
9 changes: 8 additions & 1 deletion cot/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,11 @@ pub trait Model: Sized + Send + 'static {
/// The columns of the model.
const COLUMNS: &'static [Column];

/// The schema of the model's columns, as used in migrations.
///
/// This is used by the Cot CLI to generate migrations.
const MIGRATION_FIELDS: &'static [migrations::Field];

#[expect(missing_docs)]
const MODEL_TYPE: ModelType = ModelType::Application;

Expand Down Expand Up @@ -3836,7 +3841,9 @@ impl<const LIMIT: u32> fake::Dummy<fake::Faker> for LimitedString<LIMIT> {
/// const TYPE: ColumnType = ColumnType::Text;
/// }
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(
Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[non_exhaustive]
pub enum ColumnType {
/// A boolean column type.
Expand Down
3 changes: 3 additions & 0 deletions cot/src/db/migrations.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Database migrations.

mod graph_export;
// not part of the public API; used in cot-cli
#[doc(hidden)]
pub mod schema;
mod sorter;

use std::collections::{HashSet, VecDeque};
Expand Down
Loading
Loading