Convert Figma logo to code with AI

sfackler logorust-postgres

Native PostgreSQL driver for the Rust programming language

3,429
436
3,429
116

Top Related Projects

12,665

A safe, extensible ORM and Query Builder for Rust

🚂 Engine components of Prisma ORM

6,922

🐚 An async & dynamic ORM for Rust

2,246

Rust Compile Time ORM robustness,async, pure Rust Dynamic SQL

Quick Overview

Rust-postgres is a native PostgreSQL driver for the Rust programming language. It provides a high-level, safe, and efficient interface for interacting with PostgreSQL databases from Rust applications.

Pros

  • Strong type safety and compile-time checks, leveraging Rust's type system
  • Asynchronous support, allowing for efficient database operations
  • Comprehensive feature set, including support for various PostgreSQL data types
  • Active development and maintenance, with regular updates and improvements

Cons

  • Steeper learning curve compared to some other database libraries, especially for developers new to Rust
  • Limited support for ORM-like features, requiring more manual query writing
  • Potential performance overhead compared to lower-level C-based drivers in some scenarios
  • Documentation, while improving, can be challenging for beginners

Code Examples

  1. Connecting to a database and executing a simple query:
use tokio_postgres::{NoTls, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let (client, connection) =
        tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;

    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });

    let rows = client
        .query("SELECT $1::TEXT", &[&"Hello world!"])
        .await?;

    let value: &str = rows[0].get(0);
    println!("Value: {}", value);

    Ok(())
}
  1. Executing a parameterized query:
let rows = client
    .query("SELECT * FROM users WHERE age > $1", &[&25])
    .await?;

for row in rows {
    let name: &str = row.get("name");
    let age: i32 = row.get("age");
    println!("Name: {}, Age: {}", name, age);
}
  1. Using transactions:
let mut tx = client.transaction().await?;

tx.execute("INSERT INTO users (name, age) VALUES ($1, $2)", &[&"Alice", &30]).await?;
tx.execute("UPDATE users SET age = age + 1 WHERE name = $1", &[&"Bob"]).await?;

tx.commit().await?;

Getting Started

To use rust-postgres in your Rust project, add the following to your Cargo.toml:

[dependencies]
tokio-postgres = "0.7"
tokio = { version = "1", features = ["full"] }

Then, in your Rust code, you can import and use the library as shown in the code examples above. Make sure to handle errors appropriately and use async/await syntax for database operations.

Competitor Comparisons

12,665

A safe, extensible ORM and Query Builder for Rust

Pros of Diesel

  • Provides a powerful ORM with type-safe query building
  • Supports multiple database backends (PostgreSQL, MySQL, SQLite)
  • Offers database schema management and migrations

Cons of Diesel

  • Steeper learning curve due to its more complex API
  • Potentially slower performance for simple queries compared to raw SQL
  • Requires additional setup and configuration

Code Comparison

Diesel query example:

let results = users
    .filter(published.eq(true))
    .limit(5)
    .load::<Post>(&mut conn)?;

Rust-postgres query example:

let rows = client.query("SELECT * FROM users WHERE published = $1 LIMIT $2", &[&true, &5])?;
let results: Vec<Post> = rows.iter().map(|row| Post::from_row(row)).collect();

Diesel focuses on type-safe query building using Rust's type system, while Rust-postgres uses raw SQL queries with parameter binding. Diesel's approach provides more compile-time safety and better integration with Rust's type system, but Rust-postgres offers more flexibility and potentially better performance for simple queries.

Both libraries are well-maintained and widely used in the Rust ecosystem. The choice between them depends on project requirements, complexity, and developer preferences.

🚂 Engine components of Prisma ORM

Pros of prisma-engines

  • More comprehensive ORM functionality, including schema management and migrations
  • Supports multiple databases beyond PostgreSQL (MySQL, SQLite, etc.)
  • Provides a higher-level abstraction for database operations

Cons of prisma-engines

  • Larger and more complex codebase, potentially harder to contribute to
  • May have higher overhead due to additional features and abstractions
  • Less focused on PostgreSQL-specific optimizations

Code Comparison

prisma-engines:

let result = client
    .query()
    .select(user::all_columns)
    .from(user::table)
    .where(user::id.eq(1))
    .execute()
    .await?;

rust-postgres:

let rows = client
    .query("SELECT * FROM users WHERE id = $1", &[&1])
    .await?;

Summary

prisma-engines offers a more feature-rich ORM experience with support for multiple databases, while rust-postgres provides a focused and lightweight PostgreSQL driver. prisma-engines is better suited for complex applications requiring database-agnostic operations, while rust-postgres excels in PostgreSQL-specific use cases with lower overhead.

6,922

🐚 An async & dynamic ORM for Rust

Pros of sea-orm

  • Higher-level ORM with entity generation and query building
  • Supports multiple database backends (PostgreSQL, MySQL, SQLite)
  • Provides migration tools and database-agnostic schema definitions

Cons of sea-orm

  • Steeper learning curve due to more complex API
  • Potentially slower performance for simple queries due to abstraction layer
  • Less flexibility for raw SQL queries compared to rust-postgres

Code Comparison

sea-orm:

let posts = Post::find()
    .filter(post::Column::Title.contains("Rust"))
    .order_by_asc(post::Column::PublishedDate)
    .all(db)
    .await?;

rust-postgres:

let rows = client
    .query("SELECT * FROM posts WHERE title LIKE $1 ORDER BY published_date ASC", &[&"%Rust%"])
    .await?;

Summary

sea-orm is a full-featured ORM that provides a higher level of abstraction, making it easier to work with multiple database backends and manage complex queries. It offers entity generation, migration tools, and a query builder, which can be beneficial for larger projects.

rust-postgres, on the other hand, is a lower-level driver that provides more direct control over SQL queries and potentially better performance for simple operations. It's more suitable for projects that require fine-grained control over database interactions or have simpler database needs.

The choice between the two depends on the project's requirements, complexity, and the developer's preference for abstraction versus direct database control.

2,246

Rust Compile Time ORM robustness,async, pure Rust Dynamic SQL

Pros of rbatis

  • Supports multiple databases (MySQL, PostgreSQL, SQLite, etc.)
  • Provides ORM functionality with macro-based code generation
  • Includes built-in connection pooling

Cons of rbatis

  • Less mature and less widely used compared to rust-postgres
  • May have a steeper learning curve due to macro-based approach
  • Potentially higher overhead due to ORM abstraction

Code Comparison

rbatis:

#[crud_table]
#[derive(Clone, Debug)]
pub struct User {
    pub id: Option<i32>,
    pub name: String,
}

let user = User { id: None, name: "John".to_string() };
rb.save(&user, &[]).await?;

rust-postgres:

let user = User { id: None, name: "John".to_string() };
client.execute(
    "INSERT INTO users (name) VALUES ($1)",
    &[&user.name]
).await?;

Summary

rbatis offers a more feature-rich ORM experience with support for multiple databases, while rust-postgres provides a more focused and lightweight PostgreSQL-specific solution. rbatis may be preferable for projects requiring database abstraction and code generation, while rust-postgres might be better suited for PostgreSQL-specific applications prioritizing simplicity and performance.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Rust-Postgres

PostgreSQL support for Rust.

postgres Latest Version

Documentation

A native, synchronous PostgreSQL client.

tokio-postgres Latest Version

Documentation

A native, asynchronous PostgreSQL client.

postgres-types Latest Version

Documentation

Conversions between Rust and Postgres types.

postgres-native-tls Latest Version

Documentation

TLS support for postgres and tokio-postgres via native-tls.

postgres-openssl Latest Version

Documentation

TLS support for postgres and tokio-postgres via openssl.

Running test suite

The test suite requires postgres to be running in the correct configuration. The easiest way to do this is with docker:

  1. Install docker and docker-compose.
    1. On ubuntu: sudo apt install docker.io docker-compose.
  2. Make sure your user has permissions for docker.
    1. On ubuntu: sudo usermod -aG docker $USER
  3. Change to top-level directory of rust-postgres repo.
  4. Run docker-compose up -d.
  5. Run cargo test.
  6. Run docker-compose stop.