Skip to main content

Crate tiberius

Crate tiberius 

Source
Expand description

An asynchronous, runtime-independent, pure-rust Tabular Data Stream (TDS) implementation for Microsoft SQL Server.

Tiberius is not bound to any single async runtime: a TcpStream is created separately and injected into the Client, so it works with Tokio, smol, and other runtimes that provide futures::io::{AsyncRead, AsyncWrite}.

§Connecting with Tokio

Tokio is using their own version of AsyncRead and AsyncWrite traits, meaning that when wanting to use Tiberius with Tokio, their TcpStream needs to be wrapped in Tokio’s Compat module.

use tiberius::{Client, Config, AuthMethod};
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncWriteCompatExt;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut config = Config::new();

    config.host("localhost");
    config.port(1433);
    config.authentication(AuthMethod::sql_server("SA", "<YourStrong@Passw0rd>"));
    config.trust_cert(); // on production, it is not a good idea to do this

    let tcp = TcpStream::connect(config.get_addr()).await?;
    tcp.set_nodelay(true)?;

    // To be able to use Tokio's tcp, we're using the `compat_write` from
    // the `TokioAsyncWriteCompatExt` to get a stream compatible with the
    // traits from the `futures` crate.
    let mut client = Client::connect(config, tcp.compat_write()).await?;

    Ok(())
}

§Ways of querying

Tiberius offers two ways to query the database: directly from the Client with the Client#query and Client#execute, or additionally through the Query object.

§With the client methods

When the query parameters are known when writing the code, the client methods are easy to use.

let _res = client.query("SELECT @P1", &[&-4i32]).await?;

§With the Query object

In case of needing to pass the parameters from a dynamic collection, or if wanting to pass them by-value, use the Query object.

let params = vec![String::from("foo"), String::from("bar")];
let mut select = Query::new("SELECT @P1, @P2, @P3");

for param in params.into_iter() {
    select.bind(param);
}

let _res = select.query(&mut client).await?;

§Authentication

Tiberius supports different ways of authentication to the SQL Server:

  • SQL Server authentication uses the facilities of the database to authenticate the user.
  • On Windows, you can authenticate using the currently logged in user or specified Windows credentials.
  • If enabling the integrated-auth-gssapi feature, it is possible to login with the currently active Kerberos credentials.

§AAD(Azure Active Directory) Authentication

Tiberius supports AAD authentication by taking an AAD token. Suggest using azure_identity crate to retrieve the token, and config tiberius with token. There is an example in examples folder on how to setup this.

§TLS

When compiled using the default features, a TLS encryption will be available and by default, used for all traffic. TLS is handled with the given TcpStream. Please see the documentation for EncryptionLevel for details.

§SQL Browser

On Windows platforms, connecting to the SQL Server might require going through the SQL Browser service to get the correct port for the named instance. This feature requires the sql-browser-tokio (or sql-browser-smol) feature flag to be enabled and has a bit different way of connecting:

use tiberius::{Client, Config, AuthMethod};
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncWriteCompatExt;

// An extra trait that allows connecting to a named instance with the given
// `TcpStream`.
use tiberius::SqlBrowser;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut config = Config::new();

    config.authentication(AuthMethod::sql_server("SA", "<password>"));
    config.host("localhost");

    // The default port of SQL Browser
    config.port(1434);

    // The name of the database server instance.
    config.instance_name("INSTANCE");

    // on production, it is not a good idea to do this
    config.trust_cert();

    // This will create a new `TcpStream`, connected to the right port of the
    // named instance.
    let tcp = TcpStream::connect_named(&config).await?;

    // And from here on continue the connection process in a normal way.
    let mut client = Client::connect(config, tcp.compat_write()).await?;
    Ok(())
}

§Other features

  • If using an ADO.NET connection string, it is possible to create a Config from one. Please see the documentation for from_ado_string for details.
  • If wanting to use Tiberius with SQL Server version 2005, one must disable the tds73 feature.

Modules§

error
Error module
numeric
Representations of numeric types.
time
Date and time handling.
xml
The XML containers

Structs§

AltMetaDataColumn
A column produced by a COMPUTE clause, as described by an TokenAltMetaData (ALTMETADATA, token 0x88) stream.
BaseMetaDataColumn
Describes the type and flags of a column, exposing metadata such as the column type (including size, precision and scale), whether the column is nullable and whether it is an identity column.
BulkLoadRequest
A handler for a bulk insert data flow.
Client
Client is the main entry point to the SQL Server, providing query execution capabilities.
Collation
The collation of a character column, describing its locale (LCID), sort order and code page.
Column
A column of data from a query.
Command
A remote command (stored procedure or user-defined function) with bound parameters, executed by name via an RPC request.
CommandResult
A materialized result from executing a Command, carrying the number of affected rows, the return code, the values of any OUT parameters and any record sets returned by the command.
CommandReturnValue
A single OUT parameter value returned by a Command.
CommandStream
A Stream of CommandItem values produced by executing a Command.
Config
The Config struct contains all configuration information required for connecting to the database with a Client. It also provides the server address when connecting to a TcpStream via the get_addr method.
ConfigBuilder
A builder for Config, providing an ergonomic, chainable way to construct a connection configuration.
ExecuteResult
A result from a query execution, listing the number of affected rows.
MetaDataColumn
Metadata for a single result/table column: its name plus the BaseMetaDataColumn describing its type, size and flags.
Query
A query object with bind parameters.
QueryStream
A set of Streams of QueryItem values, which can be either result metadata or a row.
ResultMetadata
Info about the following stream of rows.
Row
A row of data from a query.
SqlTableData
The internal representation of a table-valued parameter’s data.
SqlTableDataRow
A single row of a table-valued parameter, used by TableValueRow implementations to bind column values.
TokenAltMetaData
The token describing the layout of a COMPUTE (BY) result set (ALTMETADATA, token 0x88).
TokenAltRow
A row of computed data produced by a COMPUTE (BY) clause (ALTROW, token 0xD3).
TokenRow
A row of data.
Uuid
A Universally Unique Identifier (UUID).
VarLenContext
The context of a variable-length column: its underlying type, size and optional collation.

Enums§

AuthMethod
Defines the method of authentication to the server.
ColumnData
A container of a value that can be represented as a TDS value.
ColumnFlag
A setting a column can hold.
ColumnType
The type of the column.
CommandItem
An item produced by a CommandStream.
EncryptionLevel
The configured encryption level specifying if encryption is required
FixedLenType
IsolationLevel
The transaction isolation level requested when beginning a transaction through a Transaction Manager request (MS-TDS 2.2.6.8).
QueryItem
Resulting data from a query.
TypeInfo
Describes a type of a column.
TypeLength
A length of a column in bytes or characters.
VarLenType
2.2.5.4.2

Traits§

FromSql
A conversion trait from a TDS type by-reference.
FromSqlOwned
A conversion trait from a TDS type by-value.
IntoRow
create a TokenRow from list of values
IntoSql
A by-value conversion trait to a TDS type.
QueryIdx
A type that can address a column within a Row, either by its zero-based position (usize) or by name (&str).
SqlBrowser
An extension trait to a TcpStream to find a port and connecting to a named database instance.
TableValue
A collection of TableValueRow values that can be bound as a table-valued parameter. Implemented for any IntoIterator of rows.
TableValueRow
A structure that represents a single row of a table-valued parameter (TVP) implements this trait.
ToSql
A conversion trait to a TDS type.

Type Aliases§

Result
An alias for a result that holds crate’s error type as the error.

Derive Macros§

TableValueRow
Generates a trivial implementation of the TableValueRow trait.