- Notifications
You must be signed in to change notification settings - Fork0
Native PostgreSQL driver for the Rust programming language
License
djc/rust-postgres
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A native PostgreSQL driver for Rust.
You can integrate Rust-Postgres into your project through thereleases on crates.io:
[dependencies]postgres ="0.15"
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);}}
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.
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
anddatabase
defaults 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.
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. Thei
th 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);}
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])?;}
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.
Rust-Postgres enforces a strict correspondence between Rust types and Postgrestypes. The driver currently supports the following conversions:
Rust Type | Postgres Type |
---|---|
bool | BOOL |
i8 | "char" |
i16 | SMALLINT, SMALLSERIAL |
i32 | INT, SERIAL |
u32 | OID |
i64 | BIGINT, BIGSERIAL |
f32 | REAL |
f64 | DOUBLE PRECISION |
str/String | VARCHAR, 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
andFromSql
traits.
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.
UUID support isprovided optionally by thewith-uuid
feature, which addsToSql
andFromSql
implementations foruuid
'sUuid
type.
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.
Date and Timesupport is provided optionally by thewith-time
feature, which addsToSql
andFromSql
implementations fortime
'sTimespec
type, or thewith-chrono
feature, which addsToSql
andFromSql
implementations forchrono
'sDateTime
,NaiveDateTime
,NaiveDate
andNaiveTime
types.
BIT and VARBITsupport is provided optionally by thewith-bit-vec
feature, which addsToSql
andFromSql
implementations forbit-vec
'sBitVec
type.
MACADDRsupport is provided optionally by thewith-eui48
feature, which addsToSql
andFromSql
implementations foreui48
'sMacAddress
type.
POINTsupport is provided optionally by thewith-geo
feature, which addsToSql
andFromSql
implementations forgeo
'sPoint
type.
BOXsupport is provided optionally by thewith-geo
feature, which addsToSql
andFromSql
implementations forgeo
'sBbox
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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- Rust90.5%
- C++8.1%
- Other1.4%