Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example usage of pg-embed in a unit test with sqlx #27

Open
liamwh opened this issue May 9, 2023 · 2 comments
Open

Example usage of pg-embed in a unit test with sqlx #27

liamwh opened this issue May 9, 2023 · 2 comments

Comments

@liamwh
Copy link

liamwh commented May 9, 2023

Hi there,

It would be super helpful to have an examples dir in the root of the repo, and include an example unit test there using pg-embed and sqlx to talk to the DB?

Is this something you'd be open to adding?

Cheers,

Liam

@liamwh liamwh changed the title Example usage of pg-embed in a unit test with sqlx? Example usage of pg-embed in a unit test with sqlx May 9, 2023
@christopinka
Copy link

christopinka commented Jun 7, 2023

I'm getting errors when compiling the example in the readme.

vogsphere~/projects/apps-data[upgrade-deps|●1✚2] % cargo test

warning: apps-data (lib test) generated 2 warnings (2 duplicates)
Compiling apps-data v0.1.0 (/Users/christopinka/projects/apps-data)
error[E0432]: unresolved import pg_embed::fetch
--> tests/connect.rs:4:5
|
4 | use pg_embed::fetch;
| ^^^^^^^^^^^^^^^ no fetch in the root

error[E0432]: unresolved import pg_embed::fetch
--> tests/connect.rs:5:15
|
5 | use pg_embed::fetch::{PgFetchSettings, PG_V13};
| ^^^^^ could not find fetch in pg_embed

error[E0603]: enum PgAuthMethod is private
--> tests/connect.rs:3:47
|
3 | use pg_embed::postgres::{PgEmbed, PgSettings, PgAuthMethod};
| ^^^^^^^^^^^^ private enum
|
note: the enum PgAuthMethod is defined here
--> /Users/christopinka/.cargo/registry/src/github.com-1ecc6299db9ec823/pg-embed-0.7.1/src/postgres.rs:27:23
|
27 | use crate::pg_enums::{PgAuthMethod, PgServerStatus};
| ^^^^^^^^^^^^

Some errors have detailed explanations: E0432, E0603.
For more information about an error, try rustc --explain E0432.
error: could not compile apps-data due to 3 previous errors

use std::collections::HashMap;
use config::Config;
use apps_data::DBManager;
use pg_embed::postgres::{PgEmbed, PgSettings, PgAuthMethod};
use pg_embed::fetch;
use pg_embed::fetch::{PgFetchSettings, PG_V13};
use std::time::Duration;
use std::path::PathBuf;


#[test]
fn test_connect() {
    let mut settings = Config::new();

    settings.set_default("database.user", "postgres").unwrap();
    settings.set_default("database.password", "password").unwrap();
    settings.set_default("database.host", "172.17.0.3").unwrap();
    settings.set_default("database.dbname", "hmi").unwrap();
    settings.set_default("database.port", "5432").unwrap();

    println!("{:?}", settings);


    db_init();
    let mut dbman = DBManager::new(&settings);


    let conn = dbman.connected();
    println!("connected: {}", conn);
    assert!(conn, "database not connected");
}

// async fn main() -> Result<(), Box<dyn std::error::Error>>
async fn db_init() -> Result<(), Box<dyn std::error::Error>> {
    /// Postgresql settings
    let pg_settings = PgSettings {
        // Where to store the postgresql database
        database_dir: PathBuf::from("data/db"),
        port: 5432,
        user: "postgres".to_string(),
        password: "password".to_string(),
        // authentication method
        auth_method: PgAuthMethod::Plain,
        // If persistent is false clean up files and directories on drop, otherwise keep them
        persistent: false,
        // duration to wait before terminating process execution
        // pg_ctl start/stop and initdb timeout
        // if set to None the process will not be terminated
        timeout: Some(Duration::from_secs(15)),
        // If migration sql scripts need to be run, the directory containing those scripts can be
        // specified here with `Some(PathBuf(path_to_dir)), otherwise `None` to run no migrations.
        // To enable migrations view the **Usage** section for details
        migration_dir: None,
    };

    /// Postgresql binaries download settings
    let fetch_settings = PgFetchSettings {
        version: PG_V13,
        ..Default::default()
    };


    /// async block only to show that these methods need to be executed in an async context

    // Create a new instance
    let mut pg = PgEmbed::new(pg_settings, fetch_settings).await?;

    // Download, unpack, create password file and database cluster
    pg.setup().await;

    // start postgresql database
    pg.start_db().await;

    // create a new database
    // to enable migrations view the [Usage] section for details
    pg.create_database("database_name").await;

    // drop a database
    // to enable migrations view [Usage] for details
    pg.drop_database("database_name").await;

    // check database existence
    // to enable migrations view [Usage] for details
    pg.database_exists("database_name").await;

    // run migration sql scripts
    // to enable migrations view [Usage] for details
    pg.migrate("database_name").await;

    // stop postgresql database
    pg.stop_db().await;

    // get the base postgresql uri
    // `postgres://{username}:{password}@localhost:{port}`
    let pg_uri: &str = &pg.db_uri;

    // get a postgresql database uri
    // `postgres://{username}:{password}@localhost:{port}/{specified_database_name}`
    let pg_db_uri: String = pg.full_db_uri("database_name");

    Ok(())
}

@christopinka
Copy link

fixed with

use config::Config;
use apps_data::DBManager;
use pg_embed::postgres::{PgEmbed, PgSettings};
use pg_embed::pg_enums::PgAuthMethod;
use pg_embed::pg_fetch;
use pg_embed::pg_fetch::{PgFetchSettings, PG_V13};
use std::time::Duration;
use std::path::PathBuf;



#[test]
fn test_connect() {
    let mut settings = Config::new();

    settings.set_default("database.user", "postgres").unwrap();
    settings.set_default("database.password", "password").unwrap();
    settings.set_default("database.host", "172.17.0.3").unwrap();
    settings.set_default("database.dbname", "hmi").unwrap();
    settings.set_default("database.port", "5432").unwrap();

    println!("{:?}", settings);


    db_init();
    let mut dbman = DBManager::new(&settings);


    let conn = dbman.connected();
    println!("connected: {}", conn);
    assert!(conn, "database not connected");
}

// async fn main() -> Result<(), Box<dyn std::error::Error>>
async fn db_init() -> Result<(), Box<dyn std::error::Error>> {
    // Postgresql settings
    let pg_settings = PgSettings {
        // Where to store the postgresql database
        database_dir: PathBuf::from("data/db"),
        port: 5432,
        user: "postgres".to_string(),
        password: "password".to_string(),
        // authentication method
        auth_method: PgAuthMethod::Plain,
        // If persistent is false clean up files and directories on drop, otherwise keep them
        persistent: false,
        // duration to wait before terminating process execution
        // pg_ctl start/stop and initdb timeout
        // if set to None the process will not be terminated
        timeout: Some(Duration::from_secs(15)),
        // If migration sql scripts need to be run, the directory containing those scripts can be
        // specified here with `Some(PathBuf(path_to_dir)), otherwise `None` to run no migrations.
        // To enable migrations view the **Usage** section for details
        migration_dir: None,
    };

    // Postgresql binaries download settings
    let fetch_settings = PgFetchSettings {
        version: PG_V13,
        ..Default::default()
    };


    // async block only to show that these methods need to be executed in an async context

    // Create a new instance
    let mut pg = PgEmbed::new(pg_settings, fetch_settings).await?;

    // Download, unpack, create password file and database cluster
    pg.setup().await;

    // start postgresql database
    pg.start_db().await;

    // create a new database
    // to enable migrations view the [Usage] section for details
    pg.create_database("database_name").await;

    // drop a database
    // to enable migrations view [Usage] for details
    pg.drop_database("database_name").await;

    // check database existence
    // to enable migrations view [Usage] for details
    pg.database_exists("database_name").await;

    // run migration sql scripts
    // to enable migrations view [Usage] for details
    pg.migrate("database_name").await;

    // stop postgresql database
    pg.stop_db().await;

    // get the base postgresql uri
    // `postgres://{username}:{password}@localhost:{port}`
    let pg_uri: &str = &pg.db_uri;

    // get a postgresql database uri
    // `postgres://{username}:{password}@localhost:{port}/{specified_database_name}`
    let pg_db_uri: String = pg.full_db_uri("database_name");

    Ok(())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants