Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Native PostgreSQL driver for the Rust programming language

License

NotificationsYou must be signed in to change notification settings

djc/rust-postgres

 
 

Repository files navigation

CircleCILatest Version

A native PostgreSQL driver for Rust.

Documentation

You can integrate Rust-Postgres into your project through thereleases on crates.io:

[dependencies]postgres ="0.15"

Overview

Rust-Postgres is a pure-Rust frontend for the popular PostgreSQL database.

externcrate postgres;use postgres::{Connection,TlsMode};structPerson{id:i32,name:String,data:Option<Vec<u8>>,}fnmain(){let conn =Connection::connect("postgres://postgres@localhost:5433",TlsMode::None).unwrap();    conn.execute("CREATE TABLE person (                    id              SERIAL PRIMARY KEY,                    name            VARCHAR NOT NULL,                    data            BYTEA                  )",&[]).unwrap();let me =Person{id:0,name:"Steven".to_string(),data:None,};    conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",&[&me.name,&me.data]).unwrap();for rowin&conn.query("SELECT id, name, data FROM person",&[]).unwrap(){let person =Person{id: row.get(0),name: row.get(1),data: row.get(2),};println!("Found person {}", person.name);}}

Requirements

  • Rust - Rust-Postgres is developed against the 1.18 release of Rustavailable onhttp://www.rust-lang.org. It should also compile against morerecent releases.

  • PostgreSQL 7.4 or later - Rust-Postgres speaks version 3 of thePostgreSQL protocol, which corresponds to versions 7.4 and later. If yourversion of Postgres was compiled in the last decade, you should be okay.

Usage

Connecting

Connect to a Postgres server using the standard URI format:

let conn =Connection::connect("postgres://user:pass@host:port/database?arg1=val1&arg2=val2",TlsMode::None)?;

pass may be omitted if not needed.port defaults to5432 anddatabasedefaults to the value ofuser if not specified. The driver supportstrust,password, andmd5 authentication.

Unix domain sockets can be used as well. Thehost portion of the URI shouldbe set to the absolute path to the directory containing the socket file. Since/ is a reserved character in URLs, the path should be URL encoded. If Postgresstored its socket files in/run/postgres, the connection would then look like:

let conn =Connection::connect("postgres://postgres@%2Frun%2Fpostgres",TlsMode::None)?;

Paths which contain non-UTF8 characters can be handled in a different manner;see the documentation for details.

Querying

SQL statements can be executed with thequery andexecute methods. Bothmethods take a query string as well as a slice of parameters to bind to thequery. Theith query parameter is specified in the query string by$i. Notethat query parameters are 1-indexed rather than the more common 0-indexing.

execute returns the number of rows affected by the query (or 0 if notapplicable):

let updates = conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2",&[&1i32,&"biz"])?;println!("{} rows were updated", updates);

query returns an iterable object holding the rows returned from the database.The fields in a row can be accessed either by their indices or their columnnames, though access by index is more efficient. Unlike statement parameters,result columns are zero-indexed.

for rowin&conn.query("SELECT bar, baz FROM foo WHERE buz = $1",&[&1i32])?{let bar:i32 = row.get(0);let baz:String = row.get("baz");println!("bar: {}, baz: {}", bar, baz);}

Statement Preparation

If the same statement will be executed repeatedly (possibly with differentparameters), explicitly preparing it can improve performance:

let stmt = conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2")?;for(bar, baz)in updates{    stmt.execute(&[bar, baz])?;}

Transactions

Thetransaction method will start a new transaction. It returns aTransaction object which has the functionality of aConnection as well as methods to control the result of thetransaction:

let trans = conn.transaction()?;trans.execute(...)?;let stmt = trans.prepare(...)?;// ...trans.commit()?;

The transaction will be active until theTransaction object falls out ofscope. A transaction will roll back by default. Nested transactions aresupported via savepoints.

Type Correspondence

Rust-Postgres enforces a strict correspondence between Rust types and Postgrestypes. The driver currently supports the following conversions:

Rust TypePostgres Type
boolBOOL
i8"char"
i16SMALLINT, SMALLSERIAL
i32INT, SERIAL
u32OID
i64BIGINT, BIGSERIAL
f32REAL
f64DOUBLE PRECISION
str/StringVARCHAR, CHAR(n), TEXT, CITEXT, NAME
[u8]/Vec<u8>BYTEA
serialize::json::Json andserde_json::Value (optional)JSON, JSONB
time::Timespec andchrono::NaiveDateTime (optional)TIMESTAMP
time::Timespec,chrono::DateTime<Utc>,chrono::DateTime<Local>, andchrono::DateTime<FixedOffset> (optional)TIMESTAMP WITH TIME ZONE
chrono::NaiveDate (optional)DATE
chrono::NaiveTime (optional)TIME
uuid::Uuid (optional)UUID
bit_vec::BitVec (optional)BIT, VARBIT
HashMap<String, Option<String>>HSTORE
eui48::MacAddress (optional)MACADDR
geo::Point<f64> (optional)POINT
geo::Bbox<f64> (optional)BOX
geo::LineString<f64> (optional)PATH

Option<T> implementsFromSql whereT: FromSql andToSql whereT: ToSql, and represents nullable Postgres values.

&[T] andVec<T> implementToSql whereT: ToSql, andVec<T>additionally implementsFromSql whereT: FromSql, which representone-dimensional Postgres arrays.

More conversions can be defined by implementing theToSql andFromSqltraits.

Thepostgres-derivecrate will synthesizeToSql andFromSql implementations for enum, domain,and composite Postgres types.

Full support for array types is located in thepostgres-array crate.

Support for range types is located in thepostgres-range crate.

Support for the large object API is located in thepostgres-large-objectcrate.

Optional features

UUID type

UUID support isprovided optionally by thewith-uuid feature, which addsToSql andFromSqlimplementations foruuid'sUuid type.

JSON/JSONB types

JSON and JSONBsupport is provided optionally by thewith-rustc-serialize feature, which addsToSql andFromSql implementations forrustc-serialize'sJson type, andthewith-serde_json feature, which adds implementations forserde_json'sValue type.

TIMESTAMP/TIMESTAMPTZ/DATE/TIME types

Date and Timesupport is provided optionally by thewith-time feature, which addsToSqlandFromSql implementations fortime'sTimespec type, or thewith-chronofeature, which addsToSql andFromSql implementations forchrono'sDateTime,NaiveDateTime,NaiveDate andNaiveTime types.

BIT/VARBIT types

BIT and VARBITsupport is provided optionally by thewith-bit-vec feature, which addsToSqlandFromSql implementations forbit-vec'sBitVec type.

MACADDR type

MACADDRsupport is provided optionally by thewith-eui48 feature, which addsToSqlandFromSql implementations foreui48'sMacAddress type.

POINT type

POINTsupport is provided optionally by thewith-geo feature, which addsToSql andFromSql implementations forgeo'sPoint type.

BOX type

BOXsupport is provided optionally by thewith-geo feature, which addsToSql andFromSql implementations forgeo'sBbox type.

PATH type

PATHsupport is provided optionally by thewith-geo feature, which addsToSql andFromSql implementations forgeo'sLineString type.Paths converted from LineString are always treated as "open" paths. Use thepclosegeometric function to insert a closed path.

About

Native PostgreSQL driver for the Rust programming language

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Rust90.5%
  • C++8.1%
  • Other1.4%

[8]ページ先頭

©2009-2025 Movatter.jp