pub struct Connection { /* private fields */ }
Expand description

A connection to a database.

Implementations§

source§

impl Connection

source

pub fn new(dsn: &str) -> Result<Self>

source

pub fn async(&self) -> Async<'_>

source

pub fn transaction(&self) -> Transaction<'_>

Examples found in repository?
examples/10-transaction.rs (line 21)
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)
        }
source

pub fn from_config(config: &Config) -> Result<Self>

Creates a new connection from Config.

source

pub fn model<M>(&self) -> M
where M: Model,

Examples found in repository?
examples/06-complex.rs (line 34)
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
Hide additional examples
examples/07-relations.rs (line 75)
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(())
}
examples/08-composite.rs (line 64)
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(())
}
examples/10-transaction.rs (line 71)
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(())
}
source

pub fn execute(&self, query: &str) -> Result<Result>

Executes a simple text query, without parameter.

Examples found in repository?
examples/06-complex.rs (line 19)
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
Hide additional examples
examples/04-write.rs (line 22)
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(())
}
examples/03-read.rs (line 22)
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(())
}
examples/05-extra.rs (line 24)
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(())
}
examples/07-relations.rs (line 72)
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(())
}
examples/08-composite.rs (line 61)
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(())
}
source

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?
examples/02-query.rs (line 20)
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
Hide additional examples
examples/08-composite.rs (line 50)
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))
        }
examples/07-relations.rs (line 50)
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))
        }
source

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?
examples/02-query.rs (line 27)
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(())
}
source

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.

Examples found in repository?
examples/03-read.rs (line 36)
33
34
35
36
37
38
39
40
fn find_by_pk(elephantry: &elephantry::Pool) -> elephantry::Result {
    println!("# Find by primary key\n");

    let employee = elephantry.find_by_pk::<employee::Model>(&elephantry::pk!(employee_id => 1))?;
    println!("{employee:?}\n");

    Ok(())
}
source

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?
examples/03-read.rs (line 44)
42
43
44
45
46
47
48
49
50
51
52
fn find_all(elephantry: &elephantry::Pool) -> elephantry::Result {
    println!("# Find all\n");
    let employees = elephantry.find_all::<employee::Model>(Some("order by birth_date desc"))?;

    for employee in employees {
        println!("{} {}", employee.first_name, employee.last_name);
    }
    println!();

    Ok(())
}
More examples
Hide additional examples
examples/05-extra.rs (line 26)
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(())
}
source

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?
examples/03-read.rs (line 57)
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
Hide additional examples
examples/10-transaction.rs (line 32)
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)
        }
source

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.

source

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?
examples/03-read.rs (line 70)
67
68
69
70
71
72
73
74
fn count_where(elephantry: &elephantry::Pool) -> elephantry::Result {
    println!("# Count where\n");

    let n = elephantry.count_where::<employee::Model>("is_manager = $1", &[&true])?;
    println!("{n}\n");

    Ok(())
}
More examples
Hide additional examples
examples/12-copy.rs (line 42)
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(())
}
source

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.

Examples found in repository?
examples/03-read.rs (line 79)
76
77
78
79
80
81
82
83
fn exist_where(elephantry: &elephantry::Pool) -> elephantry::Result {
    println!("# Exist where\n");

    let exist = elephantry.exist_where::<employee::Model>("day_salary < $1", &[&10_000])?;
    println!("{exist}\n");

    Ok(())
}
source

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?
examples/04-write.rs (line 42)
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
Hide additional examples
examples/10-transaction.rs (line 29)
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)
        }
source

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?
examples/04-write.rs (line 46)
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)
}
source

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?
examples/04-write.rs (lines 63-66)
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
Hide additional examples
examples/10-transaction.rs (lines 39-42)
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)
        }
source

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?
examples/04-write.rs (lines 72-75)
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(())
}
source

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?
examples/04-write.rs (line 82)
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(())
}
source

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?
examples/04-write.rs (line 86)
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(())
}
source

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?
examples/04-write.rs (line 89)
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(())
}
source

pub fn has_broken(&self) -> Result<bool>

Determines if the connection is no longer usable.

source

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?
examples/11-notification.rs (line 10)
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(())
}
source

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?
examples/11-notification.rs (line 9)
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(())
}
source

pub fn unlisten(&self, channel: &str) -> Result

Stop to listen on the given channel.

Examples found in repository?
examples/11-notification.rs (line 13)
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(())
}
source

pub fn notifies(&self) -> Result<Option<Notify>>

Check if a notification is pending. If so, the payload is returned. Otherwise, None is returned.

Examples found in repository?
examples/11-notification.rs (line 21)
20
21
22
23
24
25
26
fn listen(elephantry: &elephantry::Connection) -> elephantry::Result {
    while let Some(notify) = elephantry.notifies()? {
        dbg!(notify);
    }

    Ok(())
}
source

pub fn ping(&self) -> Result

Reports the status of the server.

Examples found in repository?
examples/00-config.rs (line 8)
1
2
3
4
5
6
7
8
9
fn main() -> elephantry::Result {
    let config = config::Config::builder()
        .add_source(config::Environment::with_prefix("DATABASE"))
        .build()?;

    let elephantry = elephantry::Pool::from_config(&config.try_deserialize()?)?;

    elephantry.ping()
}
source

pub fn config(&self) -> Result<Config>

Retreives connection configuration.

source

pub fn copy<M, I>(&self, entities: I) -> Result
where I: Iterator<Item = M::Entity>, M: Model,

Bulk insert entities via COPY mode.

Examples found in repository?
examples/12-copy.rs (line 40)
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

source§

fn clone(&self) -> Connection

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Connection

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Poolable for Connection

Available on crate feature rocket only.
§

type Error = Error

The associated error type in the event that constructing the connection manager and/or the connection pool fails.
§

type Manager = ConnectionManager

The associated connection manager for the given connection type.
source§

fn pool(db_name: &str, rocket: &Rocket<Build>) -> PoolResult<Self>

Creates an r2d2 connection pool for Manager::Connection, returning the pool on success.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoCollection<T> for T

source§

fn into_collection<A>(self) -> SmallVec<A>
where A: Array<Item = T>,

Converts self into a collection.
source§

fn mapped<U, F, A>(self, f: F) -> SmallVec<A>
where F: FnMut(T) -> U, A: Array<Item = U>,

source§

impl<T> Paint for T
where T: ?Sized,

source§

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 primary(&self) -> Painted<&T>

Returns self with the fg() set to Color::Primary.

§Example
println!("{}", value.primary());
source§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to Color::Fixed.

§Example
println!("{}", value.fixed(color));
source§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to Color::Rgb.

§Example
println!("{}", value.rgb(r, g, b));
source§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to Color::Black.

§Example
println!("{}", value.black());
source§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to Color::Red.

§Example
println!("{}", value.red());
source§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to Color::Green.

§Example
println!("{}", value.green());
source§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::Yellow.

§Example
println!("{}", value.yellow());
source§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::Blue.

§Example
println!("{}", value.blue());
source§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::Magenta.

§Example
println!("{}", value.magenta());
source§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::Cyan.

§Example
println!("{}", value.cyan());
source§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to Color::White.

§Example
println!("{}", value.white());
source§

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>

Returns self with the fg() set to Color::BrightRed.

§Example
println!("{}", value.bright_red());
source§

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>

Returns self with the fg() set to Color::BrightYellow.

§Example
println!("{}", value.bright_yellow());
source§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlue.

§Example
println!("{}", value.bright_blue());
source§

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>

Returns self with the fg() set to Color::BrightCyan.

§Example
println!("{}", value.bright_cyan());
source§

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>

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>

Returns self with the bg() set to Color::Primary.

§Example
println!("{}", value.on_primary());
source§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to Color::Fixed.

§Example
println!("{}", value.on_fixed(color));
source§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to Color::Rgb.

§Example
println!("{}", value.on_rgb(r, g, b));
source§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::Black.

§Example
println!("{}", value.on_black());
source§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::Red.

§Example
println!("{}", value.on_red());
source§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::Green.

§Example
println!("{}", value.on_green());
source§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::Yellow.

§Example
println!("{}", value.on_yellow());
source§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::Blue.

§Example
println!("{}", value.on_blue());
source§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::Magenta.

§Example
println!("{}", value.on_magenta());
source§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::Cyan.

§Example
println!("{}", value.on_cyan());
source§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::White.

§Example
println!("{}", value.on_white());
source§

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>

Returns self with the bg() set to Color::BrightRed.

§Example
println!("{}", value.on_bright_red());
source§

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>

Returns self with the bg() set to Color::BrightYellow.

§Example
println!("{}", value.on_bright_yellow());
source§

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>

Returns self with the bg() set to Color::BrightMagenta.

§Example
println!("{}", value.on_bright_magenta());
source§

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>

Returns self with the bg() set to Color::BrightWhite.

§Example
println!("{}", value.on_bright_white());
source§

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 bold(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Bold.

§Example
println!("{}", value.bold());
source§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Dim.

§Example
println!("{}", value.dim());
source§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Italic.

§Example
println!("{}", value.italic());
source§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Underline.

§Example
println!("{}", value.underline());

Returns self with the attr() set to Attribute::Blink.

§Example
println!("{}", value.blink());

Returns self with the attr() set to Attribute::RapidBlink.

§Example
println!("{}", value.rapid_blink());
source§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Invert.

§Example
println!("{}", value.invert());
source§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Conceal.

§Example
println!("{}", value.conceal());
source§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Strike.

§Example
println!("{}", value.strike());
source§

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 mask(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Mask.

§Example
println!("{}", value.mask());
source§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Wrap.

§Example
println!("{}", value.wrap());
source§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Linger.

§Example
println!("{}", value.linger());
source§

fn clear(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Clear.

§Example
println!("{}", value.clear());
source§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Bright.

§Example
println!("{}", value.bright());
source§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::OnBright.

§Example
println!("{}", value.on_bright());
source§

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);
source§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new Painted with a default Style. Read more
source§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. Read more
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more