Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.
Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.
Move the configuration to config/common.toml and translate the README
to English.
24 KiB
Conectar una base de datos
Objetivo: conectar la aplicación a PostgreSQL, MySQL o SQLite con pagetop-seaorm, mantener el
esquema con migraciones, consultar los datos con entidades tipadas, relacionar tablas y escribir
SQL cuando haga falta.
El tutorial Guarda las tareas en una base de datos recorre un caso completo paso a paso. Esta guía reúne lo que necesitarás después.
1. Elige el motor
En una aplicación, activa el motor con una feature de pagetop-seaorm. Declararlas como
features propias te permite cambiar de motor al compilar:
[features]
default = ["postgres"]
postgres = ["pagetop-seaorm/postgres"]
mysql = ["pagetop-seaorm/mysql"]
sqlite = ["pagetop-seaorm/sqlite"]
[dependencies]
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop" }
En una extensión, declara la dependencia sin features: el motor lo elige la aplicación que la use, y Cargo lo activa para todo el árbol de dependencias.
2. Configura la conexión
La sección [database] describe la conexión. Lo que cambia entre motores:
# PostgreSQL (port 5432 by default)
[database]
db_type = "postgres"
db_name = "garden"
db_user = "garden"
db_host = "localhost"
# MySQL or MariaDB (port 3306 by default)
[database]
db_type = "mysql"
db_name = "garden"
db_user = "garden"
db_host = "localhost"
# SQLite: db_name is the file; mode=rwc creates it if it does not exist
[database]
db_type = "sqlite"
db_name = "garden.db?mode=rwc"
La contraseña, db_pass, va en config/local.toml, que no se sube al repositorio. db_port fija
otro puerto y max_pool_size el número máximo de conexiones simultáneas (5 por defecto).
Declara la extensión como dependencia de la tuya. Al arrancar, abre el pool de conexiones antes de inicializar tu extensión; si no puede conectar, la aplicación no arranca y explica por qué.
# use pagetop::prelude::*;
pub struct Garden;
#[async_trait]
impl Extension for Garden {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_seaorm::SeaORM]
}
}
3. Escribe las migraciones
Cada migración es un módulo dentro de migration/, con un nombre que empieza por la fecha para que
el orden sea el cronológico:
src/
├── lib.rs
└── migration/
├── m20261015_000001_create_plots.rs
└── m20261101_000002_add_plot_notes.rs
Una crea la tabla y un índice:
// src/migration/m20261015_000001_create_plots.rs
use pagetop_seaorm::migration::*;
pub struct Migration;
#[pagetop::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
table_auto(Plots::Table)
.col(pk_auto(Plots::Id))
.col(string_uniq(Plots::Name))
.col(string(Plots::Holder))
.col(integer(Plots::Area))
.to_owned(),
)
.await?;
manager
.create_index(
Index::create()
.name("idx_plots_holder")
.table(Plots::Table)
.col(Plots::Holder)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Plots::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum Plots {
Table,
Id,
Name,
Holder,
Area,
}
Y otra, más adelante, añade una columna opcional:
// src/migration/m20261101_000002_add_plot_notes.rs
use pagetop_seaorm::migration::*;
pub struct Migration;
#[pagetop::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.alter_table(
Table::alter()
.table(Plots::Table)
.add_column(text_null(Plots::Notes))
.to_owned(),
)
.await
}
}
#[derive(DeriveIden)]
enum Plots {
Table,
Notes,
}
Las funciones de columna siguen un patrón: string(), integer(), boolean(), date()... son
obligatorias; con _null admiten nulos y con _uniq son únicas. table_auto() añade las columnas
created_at y updated_at.
4. Aplícalas al arrancar
En src/lib.rs, declara el módulo y aplica las migraciones en initialize(), en orden:
use pagetop::prelude::*;
use pagetop_seaorm::install_migrations;
mod migration {
pub mod m20261015_000001_create_plots;
pub mod m20261101_000002_add_plot_notes;
}
#[async_trait]
impl Extension for Garden {
// ...
async fn initialize(&self) -> Result<(), BoxError> {
install_migrations!(
m20261015_000001_create_plots,
m20261101_000002_add_plot_notes,
)?;
Ok(())
}
}
Cada migración aplicada queda anotada en la tabla seaql_migrations, así que en los arranques
siguientes sólo se aplican las nuevas. Si una falla, la aplicación no arranca.
5. Define las entidades
Una entidad describe una fila. El struct se llama Model y sus campos son públicos; a partir de
él, DeriveEntityModel genera Entity, Column y ActiveModel:
// src/entity/plot.rs
use pagetop_seaorm::db::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "plots")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
pub holder: String,
pub area: i32,
pub notes: Option<String>,
}
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
Una columna que admite nulos es un Option en la entidad.
6. Consulta los datos
Todas las consultas reciben el pool con dbconn():
# use pagetop_seaorm::db::*;
# mod plot {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "plots")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub name: String,
# pub holder: String,
# pub area: i32,
# pub notes: Option<String>,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {}
# impl ActiveModelBehavior for ActiveModel {}
# }
async fn examples() -> Result<(), DbErr> {
// All of them, ordered.
let plots = plot::Entity::find()
.order_by_asc(plot::Column::Name)
.all(dbconn())
.await?;
// Filtered, and by primary key.
let large = plot::Entity::find()
.filter(plot::Column::Area.gte(20))
.all(dbconn())
.await?;
let first = plot::Entity::find_by_id(1).one(dbconn()).await?;
// Insert.
let added = plot::ActiveModel {
name: Set("C3".into()),
holder: Set("Marta".into()),
area: Set(15),
..Default::default()
}
.insert(dbconn())
.await?;
// Update only some columns.
let mut changed = added.into_active_model();
changed.holder = Set("Luke".into());
changed.update(dbconn()).await?;
// Delete.
plot::Entity::delete_by_id(3).exec(dbconn()).await?;
Ok(())
}
Para un listado paginado, paginate() devuelve la página pedida con el total de elementos y de
páginas, justo lo que necesita un Pager:
# use pagetop_seaorm::db::*;
# mod plot {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "plots")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub name: String,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {}
# impl ActiveModelBehavior for ActiveModel {}
# }
# async fn f(page_number: u64) -> Result<(), DbErr> {
let page = paginate(plot::Entity::find().order_by_asc(plot::Column::Name), page_number, 20).await?;
// page.items, page.total, page.page, page.per_page, page.total_pages
# Ok(())
# }
Y para varias operaciones que deben aplicarse todas o ninguna, una transacción. Si cualquiera de ellas falla, se deshacen todas: el intercambio de titulares nunca se queda a medias:
# use pagetop_seaorm::db::*;
# mod plot {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "plots")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub holder: String,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {}
# impl ActiveModelBehavior for ActiveModel {}
# }
# async fn f() -> Result<(), DbErr> {
// Swaps the holders of two plots.
dbconn()
.transaction::<_, (), DbErr>(|txn| {
Box::pin(async move {
plot::ActiveModel {
id: Unchanged(1),
holder: Set("Luke".into()),
..Default::default()
}
.update(txn)
.await?;
plot::ActiveModel {
id: Unchanged(2),
holder: Set("Ana".into()),
..Default::default()
}
.update(txn)
.await?;
Ok(())
})
})
.await
.map_err(flatten_txn_err)
# }
flatten_txn_err convierte el error de la transacción en un DbErr normal, para seguir usando
?.
7. Relaciona tablas
Cada parcela da varias cosechas. La tabla harvests guarda el id de su parcela en plot_id, con
una clave ajena que impide apuntar a una parcela que no existe y borra sus cosechas si se borra la
parcela:
// src/migration/m20261120_000003_create_harvests.rs
use pagetop_seaorm::migration::*;
pub struct Migration;
#[pagetop::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
table_auto(Harvests::Table)
.col(pk_auto(Harvests::Id))
.col(integer(Harvests::PlotId))
.col(string(Harvests::Crop))
.col(integer(Harvests::Kilos))
.foreign_key(
ForeignKey::create()
.name("fk_harvests_plot")
.from(Harvests::Table, Harvests::PlotId)
.to(Plots::Table, Plots::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await
}
}
#[derive(DeriveIden)]
enum Harvests {
Table,
Id,
PlotId,
Crop,
Kilos,
}
#[derive(DeriveIden)]
enum Plots {
Table,
Id,
}
La relación se declara en las dos entidades. La cosecha pertenece a una parcela (belongs_to),
indicando qué columna apunta a cuál:
# mod harvest {
// src/entity/harvest.rs
use pagetop_seaorm::db::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "harvests")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub plot_id: i32,
pub crop: String,
pub kilos: i32,
}
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::plot::Entity",
from = "Column::PlotId",
to = "super::plot::Column::Id"
)]
Plot,
}
impl Related<super::plot::Entity> for Entity {
fn to() -> RelationDef {
Relation::Plot.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
# }
# mod plot {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "plots")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {}
# impl ActiveModelBehavior for ActiveModel {}
# }
Y la parcela tiene muchas cosechas (has_many). Su Relation, vacía hasta ahora, queda así:
// src/entity/plot.rs
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
pub enum Relation {
#[sea_orm(has_many = "super::harvest::Entity")]
Harvests,
}
impl Related<super::harvest::Entity> for Entity {
fn to() -> RelationDef {
Relation::Harvests.def()
}
}
Con las dos declaradas, puedes ir de una a otra sin escribir el JOIN:
# use pagetop_seaorm::db::*;
# mod plot {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "plots")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub name: String,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {
# #[sea_orm(has_many = "super::harvest::Entity")]
# Harvests,
# }
# impl Related<super::harvest::Entity> for Entity {
# fn to() -> RelationDef {
# Relation::Harvests.def()
# }
# }
# impl ActiveModelBehavior for ActiveModel {}
# }
# mod harvest {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "harvests")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub plot_id: i32,
# pub crop: String,
# pub kilos: i32,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {
# #[sea_orm(
# belongs_to = "super::plot::Entity",
# from = "Column::PlotId",
# to = "super::plot::Column::Id"
# )]
# Plot,
# }
# impl Related<super::plot::Entity> for Entity {
# fn to() -> RelationDef {
# Relation::Plot.def()
# }
# }
# impl ActiveModelBehavior for ActiveModel {}
# }
# async fn f() -> Result<(), DbErr> {
// Each harvest together with its plot, in a single query.
let rows: Vec<(harvest::Model, Option<plot::Model>)> = harvest::Entity::find()
.find_also_related(plot::Entity)
.all(dbconn())
.await?;
// The harvests of one plot.
if let Some(plot) = plot::Entity::find_by_id(1).one(dbconn()).await? {
let harvests = plot.find_related(harvest::Entity).all(dbconn()).await?;
}
# Ok(())
# }
# fn main() {}
La parcela de find_also_related() es un Option porque, en general, la columna podría estar
vacía; con una clave ajena obligatoria como esta, siempre llega.
8. Escribe SQL a mano
Para lo que no encaja en una entidad, como un total por grupos, construye la consulta con
db::query y léela con fetch_all(). Cada fila llega sin tipo, y cada columna se extrae con
try_get():
# use pagetop_seaorm::db::*;
use pagetop_seaorm::db::query::*;
# async fn f() -> Result<(), DbErr> {
// Kilos by crop, the largest first.
let stmt = Query::select()
.column(Alias::new("crop"))
.expr_as(Expr::col(Alias::new("kilos")).sum(), Alias::new("total"))
.from(Alias::new("harvests"))
.group_by_col(Alias::new("crop"))
.order_by(Alias::new("total"), Order::Desc)
.to_owned();
for row in fetch_all(&stmt).await? {
let crop: String = row.try_get("", "crop")?;
let total: i64 = row.try_get("", "total")?;
println!("{crop}: {total} kg");
}
# Ok(())
# }
fetch_one() devuelve sólo la primera fila. Para modificar datos sin entidad, execute() recibe
la sentencia como texto y devuelve cuántas filas ha cambiado:
# use pagetop_seaorm::db::*;
# async fn f() -> Result<(), DbErr> {
let result = execute("DELETE FROM harvests WHERE kilos = 0").await?;
println!("{} empty harvests removed", result.rows_affected());
# Ok(())
# }
execute() envía el texto tal cual: nunca pegues en él datos que vengan del usuario, porque
abrirías la puerta a la inyección de SQL. Con esos datos, usa las entidades o el constructor de
consultas, que los escapan por ti.
Comprueba
Una prueba con SQLite en memoria aplica las migraciones y verifica las consultas, sin tocar tu base de datos (ve Usa otra configuración para las pruebas):
# use pagetop::prelude::*;
# use pagetop_seaorm::db::*;
# use pagetop_seaorm::install_migrations;
# mod migration {
# pub mod m20261015_000001_create_plots {
# use pagetop_seaorm::migration::*;
# pub struct Migration;
# #[pagetop::async_trait]
# impl MigrationTrait for Migration {
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
# manager
# .create_table(
# table_auto(Plots::Table)
# .col(pk_auto(Plots::Id))
# .col(string_uniq(Plots::Name))
# .col(string(Plots::Holder))
# .col(integer(Plots::Area))
# .to_owned(),
# )
# .await
# }
# }
# #[derive(DeriveIden)]
# enum Plots { Table, Id, Name, Holder, Area }
# }
# pub mod m20261101_000002_add_plot_notes {
# use pagetop_seaorm::migration::*;
# pub struct Migration;
# #[pagetop::async_trait]
# impl MigrationTrait for Migration {
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
# manager
# .alter_table(
# Table::alter()
# .table(Plots::Table)
# .add_column(text_null(Plots::Notes))
# .to_owned(),
# )
# .await
# }
# }
# #[derive(DeriveIden)]
# enum Plots { Table, Notes }
# }
# pub mod m20261120_000003_create_harvests {
# use pagetop_seaorm::migration::*;
# pub struct Migration;
# #[pagetop::async_trait]
# impl MigrationTrait for Migration {
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
# manager
# .create_table(
# table_auto(Harvests::Table)
# .col(pk_auto(Harvests::Id))
# .col(integer(Harvests::PlotId))
# .col(string(Harvests::Crop))
# .col(integer(Harvests::Kilos))
# .foreign_key(
# ForeignKey::create()
# .name("fk_harvests_plot")
# .from(Harvests::Table, Harvests::PlotId)
# .to(Plots::Table, Plots::Id)
# .on_delete(ForeignKeyAction::Cascade),
# )
# .to_owned(),
# )
# .await
# }
# }
# #[derive(DeriveIden)]
# enum Harvests { Table, Id, PlotId, Crop, Kilos }
# #[derive(DeriveIden)]
# enum Plots { Table, Id }
# }
# }
# mod plot {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "plots")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub name: String,
# pub holder: String,
# pub area: i32,
# pub notes: Option<String>,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {
# #[sea_orm(has_many = "super::harvest::Entity")]
# Harvests,
# }
# impl Related<super::harvest::Entity> for Entity {
# fn to() -> RelationDef {
# Relation::Harvests.def()
# }
# }
# impl ActiveModelBehavior for ActiveModel {}
# }
# mod harvest {
# use pagetop_seaorm::db::*;
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
# #[sea_orm(table_name = "harvests")]
# pub struct Model {
# #[sea_orm(primary_key)]
# pub id: i32,
# pub plot_id: i32,
# pub crop: String,
# pub kilos: i32,
# }
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
# pub enum Relation {
# #[sea_orm(
# belongs_to = "super::plot::Entity",
# from = "Column::PlotId",
# to = "super::plot::Column::Id"
# )]
# Plot,
# }
# impl Related<super::plot::Entity> for Entity {
# fn to() -> RelationDef {
# Relation::Plot.def()
# }
# }
# impl ActiveModelBehavior for ActiveModel {}
# }
# pub struct Garden;
# #[async_trait]
# impl Extension for Garden {
# fn dependencies(&self) -> Vec<ExtensionRef> {
# vec![&pagetop_seaorm::SeaORM]
# }
# async fn initialize(&self) -> Result<(), BoxError> {
# install_migrations!(
# m20261015_000001_create_plots,
# m20261101_000002_add_plot_notes,
# m20261120_000003_create_harvests,
# )?;
# Ok(())
# }
# }
# fn new_plot(name: &str, holder: &str, area: i32) -> plot::ActiveModel {
# plot::ActiveModel {
# name: Set(name.into()),
# holder: Set(holder.into()),
# area: Set(area),
# ..Default::default()
# }
# }
# fn new_harvest(plot_id: i32, crop: &str, kilos: i32) -> harvest::ActiveModel {
# harvest::ActiveModel {
# plot_id: Set(plot_id),
# crop: Set(crop.into()),
# kilos: Set(kilos),
# ..Default::default()
# }
# }
#[pagetop::test]
async fn plots_and_harvests_are_stored_and_queried() {
Application::prepare(&Garden).await;
for (name, holder, area) in [("A1", "Ana", 25), ("A2", "Luke", 12), ("B1", "Marta", 30)] {
new_plot(name, holder, area).insert(dbconn()).await.unwrap();
}
let large = plot::Entity::find()
.filter(plot::Column::Area.gte(20))
.count(dbconn())
.await
.unwrap();
assert_eq!(large, 2);
let page = paginate(plot::Entity::find().order_by_asc(plot::Column::Name), 2, 2)
.await
.unwrap();
assert_eq!((page.total, page.total_pages), (3, 2));
assert_eq!(page.items[0].name, "B1");
assert_eq!(page.items[0].notes, None);
// Plot 1 (A1) gives two harvests and plot 3 (B1) one.
for (plot_id, crop, kilos) in [(1, "Tomatoes", 12), (1, "Lettuces", 5), (3, "Tomatoes", 9)] {
new_harvest(plot_id, crop, kilos).insert(dbconn()).await.unwrap();
}
let a1 = plot::Entity::find_by_id(1).one(dbconn()).await.unwrap().unwrap();
let harvests = a1.find_related(harvest::Entity).all(dbconn()).await.unwrap();
assert_eq!(harvests.len(), 2);
let rows = harvest::Entity::find()
.find_also_related(plot::Entity)
.all(dbconn())
.await
.unwrap();
assert!(rows.iter().all(|(_, plot)| plot.is_some()));
use pagetop_seaorm::db::query::*;
let stmt = Query::select()
.column(Alias::new("crop"))
.expr_as(Expr::col(Alias::new("kilos")).sum(), Alias::new("total"))
.from(Alias::new("harvests"))
.group_by_col(Alias::new("crop"))
.order_by(Alias::new("total"), Order::Desc)
.to_owned();
let first = &fetch_all(&stmt).await.unwrap()[0];
let crop: String = first.try_get("", "crop").unwrap();
let total: i64 = first.try_get("", "total").unwrap();
assert_eq!((crop.as_str(), total), ("Tomatoes", 21));
}
Siguiente
- Añadir usuarios y permisos:
pagetop-userguarda usuarios y sesiones en esta misma base de datos. - Ordenar y paginar sin recargar: un listado paginado con HTMX.