Struct PostgresBase

Source
pub struct PostgresBase { /* private fields */ }
Expand description

Represents a connection config to a PostgreSQL database.

§Example

use safety_postgres::access::postgres_base::PostgresBase;
use safety_postgres::access::sql_base::QueryColumns;

async fn postgres_query() {
    let mut postgres = PostgresBase::new("table_name")
        .expect("postgres base init failed");
    postgres.connect().await.expect("connect failed");

    let query_columns = QueryColumns::new(true);

    postgres.query_raw(&query_columns).await.expect("query failed");
}

Implementations§

Source§

impl PostgresBase

Source

pub fn new(table_name: &str) -> Result<Self, PostgresBaseError>

Creates a new instance of PostgresBase for interacting with a PostgreSQL database.

§Arguments
  • table_name - The name of the table to interact with.
§Returns

Returns a Result containing the new PostgresBase instance if successful, or a PostgresBaseError if an error occurs.

§Example
use safety_postgres::access::postgres_base::PostgresBase;

let mut postgres = PostgresBase::new("table_name").expect("PostgresBase init failed");
Source

pub async fn connect(&mut self) -> Result<(), PGError>

Connects to a PostgreSQL database using the provided configuration.

§Returns

Returns a result indicating whether the connection was successful or an error occurred. If the connection is successful, Ok(()) is returned. If an error occurs, Err(PGError) is returned.

§Example
use safety_postgres::access::postgres_base::PostgresBase;

async fn postgres_connect() {
    let mut postgres = PostgresBase::new("your_table_name").expect("PostgresBase struct return error");
    let _ = postgres.connect().await.expect("connect failed");
}
Source

pub async fn query_raw( &self, query_columns: &QueryColumns, ) -> Result<Vec<Row>, PostgresBaseError>

Executes a raw query on the database and returns the result.

§Arguments
  • query_columns - A QueryColumns struct reference specifying the columns to query.
§Returns
  • Ok(Vec<Row>) - Get the values if the query was successful.
  • Err(PostgresBaseError) - If an error occurred during the query process.
§Errors

Returns a PostgresBaseError if there was an error executing the query.

Source

pub async fn query_condition_raw( &self, query_column: &QueryColumns, conditions: &Conditions, ) -> Result<Vec<Row>, PostgresBaseError>

Queries the database for data based on the provided query column and conditions.

§Arguments
  • query_column - The columns using reference of the QueryColumns struct to query.
  • conditions - The conditions using reference of the Conditions to apply to the query.
§Returns
  • Ok(Vec<Row>) - Get the values if the query was successful.
  • Err(PostgresBaseError) - If an error occurred during the query process.
§Errors

Returns a PostgresBaseError if there was an error querying the database.

Source

pub async fn query_inner_join_conditions( &self, query_columns: &QueryColumns, join_tables: &JoinTables, conditions: &Conditions, ) -> Result<Vec<Row>, PostgresBaseError>

Queries the database with inner join and conditions.

§Arguments
  • query_columns - The columns using reference of the QueryColumns struct to query.
  • join_tables - The tables collection using reference of the JoinTables to join.
  • conditions - The conditions using reference of the Conditions to apply to the query.
§Returns
  • Ok(Vec<Row>) - Get the values if the query was successful
  • Err(PostgresBaseError) - If an error occurred during the query process.
§Examples
use safety_postgres::access::conditions::Conditions;
use safety_postgres::access::join_tables::JoinTables;
use safety_postgres::access::postgres_base::PostgresBase;
use safety_postgres::access::sql_base::QueryColumns;

async fn postgres_query() {
    let mut db = PostgresBase::new("table_name").unwrap();
    db.connect().await.expect("connection failed");

    let query_column = QueryColumns::new(true);
    let join_tables = JoinTables::new();
    let conditions = Conditions::new();

    /**
    * Your code....
    */

    let result = db.query_condition_raw(&query_column, &conditions).await;
    match result {
        Ok(rows) => {
            for row in rows {
                // Do something with the row
            }
        }
        Err(error) => {
            // Handle the error
        }
    }
}
Source

pub async fn insert( &self, insert_records: &InsertRecords, ) -> Result<(), PostgresBaseError>

Inserts records into the database table.

§Arguments
  • insert_records - An InsertRecords object reference containing the records to be inserted.
§Returns
  • Ok(()) - If the records were inserted successfully.
  • Err(PostgresBaseError) - If an error occurred during the insertion process.
§Examples
use safety_postgres::access::postgres_base::PostgresBase;
use safety_postgres::access::sql_base::InsertRecords;

async fn postgres_insert() {
    let mut db = PostgresBase::new("my_table").expect("db struct init failed");
    db.connect().await.expect("connection failed");
    let mut insert_records = InsertRecords::new(&["column1", "column2"]);
    insert_records.add_record(&["value1", "value2"]).expect("add record failed");

    let result = db.insert(&insert_records).await.expect("insert failed");
}
Source

pub async fn update( &self, update_set: &UpdateSets, allow_all_update: bool, ) -> Result<(), PostgresBaseError>

Updates records in the specified table based on the given update sets.

§Arguments
  • update_set: An UpdateSets object reference which containing the fields to update.
  • allow_all_update: A boolean flag indicating whether updating all records is allowed.
§Returns
  • Ok(()) if the update is successful.
  • Err(PostgresBaseError) if an error occurs during the update.
Source

pub async fn update_condition( &self, update_set: &UpdateSets, conditions: &Conditions, ) -> Result<(), PostgresBaseError>

Updates records in the table based on the specified update set and conditions.

§Arguments
  • update_set - The UpdateSets reference specifying the columns and values to update.
  • conditions - The Conditions reference specifying the records to update.
§Returns
  • Ok(()) - If the update operation is successful.
  • Err(PostgresBaseError) - If an error occurs during the update operation.
§Example
use safety_postgres::access::conditions::{Conditions, IsInJoinedTable};
use safety_postgres::access::postgres_base::PostgresBase;
use safety_postgres::access::sql_base::UpdateSets;

async fn postgres_update() {
    let mut database = PostgresBase::new("my_table").expect("postgres base init failed");
    database.connect().await.expect("connection failed");

    let mut update_set = UpdateSets::new();
    update_set.add_set("column1", "value1").unwrap();

    let mut conditions = Conditions::new();
    conditions.add_condition_from_str(
        "column1",
        "value1",
        "eq",
        "",
        IsInJoinedTable::No)
        .expect("adding condition failed");

    database.update_condition(&update_set, &conditions).await.expect("update failed");
}
Source

pub async fn delete( &self, conditions: &Conditions, ) -> Result<(), PostgresBaseError>

Delete records from the database table based on given conditions.

§Arguments
  • conditions - The reference of the conditions used to filter the records to be deleted.
§Returns
  • Ok(()) - Returns this if the deletion is successful
  • PostgresBaseError - Returns an error of type PostgresBaseError when deletion process failed.
§Examples
use safety_postgres::access::conditions::ComparisonOperator::Grater;
use safety_postgres::access::conditions::{Conditions, IsInJoinedTable};
use safety_postgres::access::conditions::LogicalOperator::FirstCondition;
use safety_postgres::access::postgres_base::PostgresBase;

async fn postgres_delete() {
    let mut database = PostgresBase::new("my_table").expect("db init failed");
    database.connect().await.expect("connecting failed");

    let mut conditions = Conditions::new();
    conditions.add_condition(
        "column1",
        "value1",
        Grater,
        FirstCondition,
        IsInJoinedTable::No).expect("adding condition failed");

    database.delete(&conditions).await.expect("delete failed");
}
Source

pub fn set_dbname(&mut self, dbname: &str) -> &mut Self

Sets the name of the database.

This method validates the given dbname parameter to ensure it consists only of alphanumeric characters and underscores. If the validation fails, an error message is printed to the standard error output and the change is rejected.

§Arguments
  • dbname - The new name of the database.
§Returns

The updated self object.

Source

pub fn set_schema(&mut self, schema_name: &str) -> &mut Self

Sets the schema for the database table.

§Arguments
  • schema_name - The new name of the schema to set.
§Returns

The modified Self object.

Source

pub fn set_port(&mut self, port: u32) -> &mut Self

Sets the port for the postgresql.

§Arguments
  • port - The new port setting for the postgresql
§Returns

The modified self object.

Source

pub fn get_config(&self) -> String

Get the configuration string for connecting to the PostgreSQL database.

§Returns
  • Configuration - Representing the configuration for connecting to the database.

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, 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> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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>,

Source§

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V