Struct elephantry::connection::Connection
source · pub struct Connection { /* private fields */ }
Expand description
A connection to a database.
Implementations§
source§impl Connection
impl Connection
pub fn new(dsn: &str) -> Result<Self>
pub fn async(&self) -> Async<'_> ⓘ
sourcepub fn transaction(&self) -> Transaction<'_>
pub fn transaction(&self) -> Transaction<'_>
Examples found in repository?
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
pub fn new_employee(
&self,
employee: &Entity,
department: &str,
) -> elephantry::Result<Entity> {
let transaction = self.connection.transaction();
transaction.start()?;
transaction.set_deferrable(
Some(vec!["employee_department_id_fkey"]),
elephantry::transaction::Constraints::Deferred,
)?;
let mut employee = self.connection.insert_one::<Self>(employee)?;
let department = self
.connection
.find_where::<super::department::Model>("name = $*", &[&department], None)?
.nth(0)
.unwrap();
employee.department_id = department.department_id;
let employee = self
.connection
.update_one::<Self>(
&elephantry::pk! { employee_id => employee.employee_id },
&employee,
)?
.unwrap();
transaction.commit()?;
Ok(employee)
}
sourcepub fn from_config(config: &Config) -> Result<Self>
pub fn from_config(config: &Config) -> Result<Self>
Creates a new connection from Config
.
sourcepub fn model<M>(&self) -> Mwhere
M: Model,
pub fn model<M>(&self) -> Mwhere
M: Model,
Examples found in repository?
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let model = elephantry.model::<employee::Model>();
let managers_salary = model.managers_salary()?;
dbg!(managers_salary);
Ok(())
}
More examples
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employee_with_department = elephantry
.model::<employee::Model>()
.employee_with_department(1)?;
dbg!(employee_with_department);
Ok(())
}
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employee_with_department = elephantry
.model::<employee::Model>()
.employee_with_department(1)?;
dbg!(employee_with_department);
Ok(())
}
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employee = elephantry.model::<employee::Model>().new_employee(
&employee::Entity {
employee_id: None,
first_name: "First name".to_string(),
last_name: "Last name".to_string(),
birth_date: chrono::NaiveDate::from_ymd_opt(1990, 1, 1).unwrap(),
is_manager: true,
day_salary: 1_000.into(),
department_id: -1,
},
"Direction",
)?;
dbg!(employee);
Ok(())
}
sourcepub fn execute(&self, query: &str) -> Result<Result>
pub fn execute(&self, query: &str) -> Result<Result>
Executes a simple text query, without parameter.
Examples found in repository?
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
pub fn managers_salary(&self) -> elephantry::Result<f32> {
let query = "select sum(day_salary) from employee where is_manager";
let result = self.connection.execute(query)?.get(0).get("sum");
Ok(result)
}
}
}
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let model = elephantry.model::<employee::Model>();
let managers_salary = model.managers_salary()?;
dbg!(managers_salary);
Ok(())
}
More examples
16 17 18 19 20 21 22 23 24 25 26 27 28 29
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let entity = insert(&elephantry)?;
update(&elephantry, &entity)?;
delete(&elephantry, &entity)?;
Ok(())
}
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
find_by_pk(&elephantry)?;
find_all(&elephantry)?;
find_where(&elephantry)?;
count_where(&elephantry)?;
exist_where(&elephantry)?;
Ok(())
}
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employees = elephantry.find_all::<employee::Model>(Some("order by age desc"))?;
for employee in employees {
dbg!(employee);
}
Ok(())
}
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employee_with_department = elephantry
.model::<employee::Model>()
.employee_with_department(1)?;
dbg!(employee_with_department);
Ok(())
}
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employee_with_department = elephantry
.model::<employee::Model>()
.employee_with_department(1)?;
dbg!(employee_with_department);
Ok(())
}
sourcepub fn query<E: Entity>(
&self,
query: &str,
params: &[&dyn ToSql]
) -> Result<Rows<E>>
pub fn query<E: Entity>( &self, query: &str, params: &[&dyn ToSql] ) -> Result<Rows<E>>
Executes a simple query, can have parameters.
Examples found in repository?
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
fn main() -> elephantry::Result {
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employees = elephantry.query::<employee::Entity>("select * from employee", &[])?;
for employee in employees {
dbg!(employee);
}
let total_salary = elephantry
.query_one::<bigdecimal::BigDecimal>("select sum(day_salary) from employee", &[])?;
dbg!(total_salary);
Ok(())
}
More examples
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
pub fn employee_with_department(&self, id: i32) -> elephantry::Result<Entity> {
use elephantry::{Model, Projectable};
let employee_projection = Self::create_projection()
.unset_field("department_id")
.add_field("departments", "array_agg(depts)")
.alias("e")
.to_string();
let employee = <Self as elephantry::Model>::Structure::relation();
let sql = format!(
r#"
with recursive
depts (department_id, name, parent_id) as (
select d.department_id, d.name, d.parent_id from department d join {employee} e using(department_id) where e.employee_id = $1
union all
select d.department_id, d.name, d.parent_id from depts parent join department d on parent.parent_id = d.department_id
)
select {employee_projection}
from {employee} e, depts
where e.employee_id = $1
group by e.employee_id
"#
);
Ok(self.connection.query::<Entity>(&sql, &[&id])?.get(0))
}
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
pub fn employee_with_department(&self, id: i32) -> elephantry::Result<Entity> {
use elephantry::{Model, Projectable};
let employee_projection = Self::create_projection()
.unset_field("department_id")
.add_field("departments", "array_agg(depts)")
.alias("e")
.to_string();
let employee = <Self as elephantry::Model>::Structure::relation();
let department_projection = super::department::Model::create_projection()
.alias("d")
.unset_field("parent")
.to_string();
let department = super::department::Structure::relation();
let sql = format!(
r#"
with recursive
depts (department_id, name, parent_id) as (
select {department_projection} from {department} d join {employee} e using(department_id) where e.employee_id = $1
union all
select {department_projection} from depts parent join {department} d on parent.parent_id = d.department_id
)
select {employee_projection}
from {employee} e, depts
where e.employee_id = $1
group by e.employee_id
"#
);
Ok(self.connection.query::<Entity>(&sql, &[&id])?.get(0))
}
sourcepub fn query_one<E: Entity>(
&self,
query: &str,
params: &[&dyn ToSql]
) -> Result<E>
pub fn query_one<E: Entity>( &self, query: &str, params: &[&dyn ToSql] ) -> Result<E>
Likes query
but peaks only the first result.
Examples found in repository?
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
fn main() -> elephantry::Result {
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employees = elephantry.query::<employee::Entity>("select * from employee", &[])?;
for employee in employees {
dbg!(employee);
}
let total_salary = elephantry
.query_one::<bigdecimal::BigDecimal>("select sum(day_salary) from employee", &[])?;
dbg!(total_salary);
Ok(())
}
sourcepub fn find_by_pk<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>
) -> Result<Option<M::Entity>>where
M: Model,
pub fn find_by_pk<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>
) -> Result<Option<M::Entity>>where
M: Model,
Return an entity upon its primary key. If no entities are found, None
is returned.
sourcepub fn find_all<M>(&self, suffix: Option<&str>) -> Result<Rows<M::Entity>>where
M: Model,
pub fn find_all<M>(&self, suffix: Option<&str>) -> Result<Rows<M::Entity>>where
M: Model,
Return all elements from a relation. If a suffix is given, it is append to the query. This is mainly useful for “order by” statements.
NOTE: suffix is inserted as is with NO ESCAPING. DO NOT use it to place “where” condition nor any untrusted params.
Examples found in repository?
More examples
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employees = elephantry.find_all::<employee::Model>(Some("order by age desc"))?;
for employee in employees {
dbg!(employee);
}
Ok(())
}
sourcepub fn find_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql],
suffix: Option<&str>
) -> Result<Rows<M::Entity>>where
M: Model,
pub fn find_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql],
suffix: Option<&str>
) -> Result<Rows<M::Entity>>where
M: Model,
Perform a simple select on a given condition
NOTE: suffix is inserted as is with NO ESCAPING. DO NOT use it to place “where” condition nor any untrusted params.
Examples found in repository?
54 55 56 57 58 59 60 61 62 63 64 65
fn find_where(elephantry: &elephantry::Pool) -> elephantry::Result {
println!("# Find where\n");
let managers = elephantry.find_where::<employee::Model>("is_manager = $1", &[&true], None)?;
for manager in managers {
println!("{} {}", manager.first_name, manager.last_name);
}
println!();
Ok(())
}
More examples
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
pub fn new_employee(
&self,
employee: &Entity,
department: &str,
) -> elephantry::Result<Entity> {
let transaction = self.connection.transaction();
transaction.start()?;
transaction.set_deferrable(
Some(vec!["employee_department_id_fkey"]),
elephantry::transaction::Constraints::Deferred,
)?;
let mut employee = self.connection.insert_one::<Self>(employee)?;
let department = self
.connection
.find_where::<super::department::Model>("name = $*", &[&department], None)?
.nth(0)
.unwrap();
employee.department_id = department.department_id;
let employee = self
.connection
.update_one::<Self>(
&elephantry::pk! { employee_id => employee.employee_id },
&employee,
)?
.unwrap();
transaction.commit()?;
Ok(employee)
}
sourcepub fn paginate_find_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql],
max_per_page: usize,
page: usize,
suffix: Option<&str>
) -> Result<Pager<M::Entity>>where
M: Model,
pub fn paginate_find_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql],
max_per_page: usize,
page: usize,
suffix: Option<&str>
) -> Result<Pager<M::Entity>>where
M: Model,
Paginate a query.
This is done with limit/offset, read why it’s probably not a good idea to use it: https://use-the-index-luke.com/no-offset.
sourcepub fn count_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql]
) -> Result<usize>where
M: Model,
pub fn count_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql]
) -> Result<usize>where
M: Model,
Return the number of records matching a condition.
Examples found in repository?
More examples
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employees = (15..10_000).into_iter().map(employee::Entity::new);
elephantry.copy::<employee::Model, _>(employees)?;
let count = elephantry.count_where::<employee::Model>("true = true", &[])?;
dbg!(count);
Ok(())
}
sourcepub fn exist_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql]
) -> Result<bool>where
M: Model,
pub fn exist_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql]
) -> Result<bool>where
M: Model,
Check if rows matching the given condition do exist or not.
sourcepub fn insert_one<M>(&self, entity: &M::Entity) -> Result<M::Entity>where
M: Model,
pub fn insert_one<M>(&self, entity: &M::Entity) -> Result<M::Entity>where
M: Model,
Insert a new entity in the database.
Returns the entity with values from database (ie: default values).
Examples found in repository?
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
fn insert(elephantry: &elephantry::Pool) -> elephantry::Result<employee::Entity> {
let employee = employee::Entity {
employee_id: None,
first_name: "First name".to_string(),
last_name: "Last name".to_string(),
birth_date: chrono::NaiveDate::from_ymd_opt(1952, 03, 21).unwrap(),
is_manager: false,
day_salary: 10_000.into(),
department_id: 3,
};
let inserted_entity = elephantry.insert_one::<employee::Model>(&employee)?;
dbg!(&inserted_entity);
let upsert_nothing =
elephantry.upsert_one::<employee::Model>(&inserted_entity, "(employee_id)", "nothing")?;
dbg!(&upsert_nothing);
let upsert_update = elephantry.upsert_one::<employee::Model>(
&inserted_entity,
"(employee_id)",
"update set employee_id = default",
)?;
dbg!(&upsert_update);
Ok(inserted_entity)
}
More examples
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
pub fn new_employee(
&self,
employee: &Entity,
department: &str,
) -> elephantry::Result<Entity> {
let transaction = self.connection.transaction();
transaction.start()?;
transaction.set_deferrable(
Some(vec!["employee_department_id_fkey"]),
elephantry::transaction::Constraints::Deferred,
)?;
let mut employee = self.connection.insert_one::<Self>(employee)?;
let department = self
.connection
.find_where::<super::department::Model>("name = $*", &[&department], None)?
.nth(0)
.unwrap();
employee.department_id = department.department_id;
let employee = self
.connection
.update_one::<Self>(
&elephantry::pk! { employee_id => employee.employee_id },
&employee,
)?
.unwrap();
transaction.commit()?;
Ok(employee)
}
sourcepub fn upsert_one<M>(
&self,
entity: &M::Entity,
target: &str,
action: &str
) -> Result<Option<M::Entity>>where
M: Model,
pub fn upsert_one<M>(
&self,
entity: &M::Entity,
target: &str,
action: &str
) -> Result<Option<M::Entity>>where
M: Model,
Try to insert a new entity in the database. On constraint violation error
on target
you can do an alternative action action
.
See ON CONFLICT clause.
Returns the entity with values from database (ie: default values).
Examples found in repository?
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
fn insert(elephantry: &elephantry::Pool) -> elephantry::Result<employee::Entity> {
let employee = employee::Entity {
employee_id: None,
first_name: "First name".to_string(),
last_name: "Last name".to_string(),
birth_date: chrono::NaiveDate::from_ymd_opt(1952, 03, 21).unwrap(),
is_manager: false,
day_salary: 10_000.into(),
department_id: 3,
};
let inserted_entity = elephantry.insert_one::<employee::Model>(&employee)?;
dbg!(&inserted_entity);
let upsert_nothing =
elephantry.upsert_one::<employee::Model>(&inserted_entity, "(employee_id)", "nothing")?;
dbg!(&upsert_nothing);
let upsert_update = elephantry.upsert_one::<employee::Model>(
&inserted_entity,
"(employee_id)",
"update set employee_id = default",
)?;
dbg!(&upsert_update);
Ok(inserted_entity)
}
sourcepub fn update_one<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>,
entity: &M::Entity
) -> Result<Option<M::Entity>>where
M: Model,
pub fn update_one<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>,
entity: &M::Entity
) -> Result<Option<M::Entity>>where
M: Model,
Update the entity.
Returns the entity with values from database.
Examples found in repository?
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
fn update(elephantry: &elephantry::Pool, entity: &employee::Entity) -> elephantry::Result {
let mut entity = entity.clone();
entity.day_salary = 20_000.into();
let updated_entity = elephantry.update_one::<employee::Model>(
&elephantry::pk!(employee_id => entity.employee_id),
&entity,
)?;
dbg!(updated_entity);
let mut data = std::collections::HashMap::new();
data.insert("is_manager".to_string(), &true as &dyn elephantry::ToSql);
let updated_entity = elephantry.update_by_pk::<employee::Model>(
&elephantry::pk!(employee_id => entity.employee_id),
&data,
)?;
dbg!(updated_entity);
Ok(())
}
More examples
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
pub fn new_employee(
&self,
employee: &Entity,
department: &str,
) -> elephantry::Result<Entity> {
let transaction = self.connection.transaction();
transaction.start()?;
transaction.set_deferrable(
Some(vec!["employee_department_id_fkey"]),
elephantry::transaction::Constraints::Deferred,
)?;
let mut employee = self.connection.insert_one::<Self>(employee)?;
let department = self
.connection
.find_where::<super::department::Model>("name = $*", &[&department], None)?
.nth(0)
.unwrap();
employee.department_id = department.department_id;
let employee = self
.connection
.update_one::<Self>(
&elephantry::pk! { employee_id => employee.employee_id },
&employee,
)?
.unwrap();
transaction.commit()?;
Ok(employee)
}
sourcepub fn update_by_pk<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>,
data: &HashMap<String, &dyn ToSql>
) -> Result<Option<M::Entity>>where
M: Model,
pub fn update_by_pk<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>,
data: &HashMap<String, &dyn ToSql>
) -> Result<Option<M::Entity>>where
M: Model,
Update a record and fetch it with its new values. If no records match
the given key, None
is returned.
Examples found in repository?
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
fn update(elephantry: &elephantry::Pool, entity: &employee::Entity) -> elephantry::Result {
let mut entity = entity.clone();
entity.day_salary = 20_000.into();
let updated_entity = elephantry.update_one::<employee::Model>(
&elephantry::pk!(employee_id => entity.employee_id),
&entity,
)?;
dbg!(updated_entity);
let mut data = std::collections::HashMap::new();
data.insert("is_manager".to_string(), &true as &dyn elephantry::ToSql);
let updated_entity = elephantry.update_by_pk::<employee::Model>(
&elephantry::pk!(employee_id => entity.employee_id),
&data,
)?;
dbg!(updated_entity);
Ok(())
}
sourcepub fn delete_one<M>(&self, entity: &M::Entity) -> Result<Option<M::Entity>>where
M: Model,
pub fn delete_one<M>(&self, entity: &M::Entity) -> Result<Option<M::Entity>>where
M: Model,
Delete an entity from a table.
Returns the entity fetched from the deleted record.
Examples found in repository?
81 82 83 84 85 86 87 88 89 90 91 92
fn delete(elephantry: &elephantry::Pool, entity: &employee::Entity) -> elephantry::Result {
let deleted_entity = elephantry.delete_one::<employee::Model>(&entity)?;
dbg!(deleted_entity);
let deleted_entity = elephantry
.delete_by_pk::<employee::Model>(&elephantry::pk!(employee_id => entity.employee_id))?;
dbg!(deleted_entity);
elephantry.delete_where::<employee::Model>("employee_id = $1", &[&entity.employee_id])?;
Ok(())
}
sourcepub fn delete_by_pk<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>
) -> Result<Option<M::Entity>>where
M: Model,
pub fn delete_by_pk<M>(
&self,
pk: &HashMap<&str, &dyn ToSql>
) -> Result<Option<M::Entity>>where
M: Model,
Delete a record from its primary key. The deleted entity is returned or
None
if not found.
Examples found in repository?
81 82 83 84 85 86 87 88 89 90 91 92
fn delete(elephantry: &elephantry::Pool, entity: &employee::Entity) -> elephantry::Result {
let deleted_entity = elephantry.delete_one::<employee::Model>(&entity)?;
dbg!(deleted_entity);
let deleted_entity = elephantry
.delete_by_pk::<employee::Model>(&elephantry::pk!(employee_id => entity.employee_id))?;
dbg!(deleted_entity);
elephantry.delete_where::<employee::Model>("employee_id = $1", &[&entity.employee_id])?;
Ok(())
}
sourcepub fn delete_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql]
) -> Result<Rows<M::Entity>>where
M: Model,
pub fn delete_where<M>(
&self,
clause: &str,
params: &[&dyn ToSql]
) -> Result<Rows<M::Entity>>where
M: Model,
Delete records by a given condition. A collection of all deleted entries is returned.
Examples found in repository?
81 82 83 84 85 86 87 88 89 90 91 92
fn delete(elephantry: &elephantry::Pool, entity: &employee::Entity) -> elephantry::Result {
let deleted_entity = elephantry.delete_one::<employee::Model>(&entity)?;
dbg!(deleted_entity);
let deleted_entity = elephantry
.delete_by_pk::<employee::Model>(&elephantry::pk!(employee_id => entity.employee_id))?;
dbg!(deleted_entity);
elephantry.delete_where::<employee::Model>("employee_id = $1", &[&entity.employee_id])?;
Ok(())
}
sourcepub fn has_broken(&self) -> Result<bool>
pub fn has_broken(&self) -> Result<bool>
Determines if the connection is no longer usable.
sourcepub fn notify(&self, channel: &str, data: Option<&str>) -> Result
pub fn notify(&self, channel: &str, data: Option<&str>) -> Result
Send a NOTIFY event to the database server. An optional data can be sent with the notification.
Examples found in repository?
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() -> elephantry::Result {
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
elephantry.listen(CHANNEL_NAME)?;
elephantry.notify(CHANNEL_NAME, Some("payload"))?;
listen(&elephantry)?;
elephantry.unlisten(CHANNEL_NAME)?;
elephantry.notify(CHANNEL_NAME, Some("payload"))?;
listen(&elephantry)?;
Ok(())
}
sourcepub fn listen(&self, channel: &str) -> Result
pub fn listen(&self, channel: &str) -> Result
Start to listen on the given channel.
Note: when listen is issued in a transaction it is unlisten when the transaction is committed or rollback.
Examples found in repository?
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() -> elephantry::Result {
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
elephantry.listen(CHANNEL_NAME)?;
elephantry.notify(CHANNEL_NAME, Some("payload"))?;
listen(&elephantry)?;
elephantry.unlisten(CHANNEL_NAME)?;
elephantry.notify(CHANNEL_NAME, Some("payload"))?;
listen(&elephantry)?;
Ok(())
}
sourcepub fn unlisten(&self, channel: &str) -> Result
pub fn unlisten(&self, channel: &str) -> Result
Stop to listen on the given channel.
Examples found in repository?
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() -> elephantry::Result {
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
elephantry.listen(CHANNEL_NAME)?;
elephantry.notify(CHANNEL_NAME, Some("payload"))?;
listen(&elephantry)?;
elephantry.unlisten(CHANNEL_NAME)?;
elephantry.notify(CHANNEL_NAME, Some("payload"))?;
listen(&elephantry)?;
Ok(())
}
sourcepub fn notifies(&self) -> Result<Option<Notify>>
pub fn notifies(&self) -> Result<Option<Notify>>
Check if a notification is pending. If so, the payload is returned.
Otherwise, None
is returned.
sourcepub fn copy<M, I>(&self, entities: I) -> Result
pub fn copy<M, I>(&self, entities: I) -> Result
Bulk insert entities via COPY mode.
Examples found in repository?
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() -> elephantry::Result {
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
let elephantry = elephantry::Pool::new(&database_url)?;
elephantry.execute(include_str!("structure.sql"))?;
let employees = (15..10_000).into_iter().map(employee::Entity::new);
elephantry.copy::<employee::Model, _>(employees)?;
let count = elephantry.count_where::<employee::Model>("true = true", &[])?;
dbg!(count);
Ok(())
}
Trait Implementations§
source§impl Clone for Connection
impl Clone for Connection
source§fn clone(&self) -> Connection
fn clone(&self) -> Connection
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl Debug for Connection
impl Debug for Connection
source§impl Poolable for Connection
Available on crate feature rocket
only.
impl Poolable for Connection
rocket
only.Auto Trait Implementations§
impl Freeze for Connection
impl RefUnwindSafe for Connection
impl Send for Connection
impl Sync for Connection
impl Unpin for Connection
impl UnwindSafe for Connection
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
source§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the foreground set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red()
and
green()
, which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg()
:
use yansi::{Paint, Color};
painted.fg(Color::White);
Set foreground color to white using white()
.
use yansi::Paint;
painted.white();
source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.bright_black());
source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.bright_green());
source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.bright_yellow());
source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.bright_magenta());
source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.bright_white());
source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the background set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red()
and
on_green()
, which have the same functionality but
are pithier.
§Example
Set background color to red using fg()
:
use yansi::{Paint, Color};
painted.bg(Color::Red);
Set background color to red using on_red()
.
use yansi::Paint;
painted.on_red();
source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.on_bright_black());
source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.on_bright_green());
source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.on_bright_yellow());
source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlue
.
§Example
println!("{}", value.on_bright_blue());
source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.on_bright_magenta());
source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightCyan
.
§Example
println!("{}", value.on_bright_cyan());
source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.on_bright_white());
source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute
value
.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold()
and
underline()
, which have the same functionality
but are pithier.
§Example
Make text bold using attr()
:
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);
Make text bold using using bold()
.
use yansi::Paint;
painted.bold();
source§fn underline(&self) -> Painted<&T>
fn underline(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::Underline
.
§Example
println!("{}", value.underline());
source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::RapidBlink
.
§Example
println!("{}", value.rapid_blink());
source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi
Quirk
value
.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask()
and
wrap()
, which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk()
:
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);
Enable wrapping using wrap()
.
use yansi::Paint;
painted.wrap();
source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition
value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted
only when both stdout
and stderr
are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);