Skip to main content

Crate tiberius

Crate tiberius 

Source
Expand description

A focused raw bulk-load fork of Tiberius, an asynchronous, runtime-independent, pure-rust Tabular Data Stream (TDS) implementation for Microsoft SQL Server.

This package is published as tiberius-raw-bulk, but the Rust library crate name remains tiberius for compatibility with upstream Tiberius users:

tiberius = { package = "tiberius-raw-bulk", version = "0.12.3-raw-bulk.12" }

The fork keeps upstream query, authentication, TLS, and connection behavior intact outside its raw bulk-load extension points. Application-specific planning, Arrow mapping, and row encoding logic belong in downstream crates.

§Raw bulk-load extensions

The fork adds extension points for callers that want to plan or encode bulk rows outside Tiberius while still using Tiberius for connection handling and TDS packet framing.

Metadata discovery and request setup are available through:

Raw row append APIs are available through:

Direct packet writes can be enabled with BulkLoadRequest::enable_direct_packet_writes and inspected with BulkLoadRequest::direct_packet_writes_enabled.

Profiling and statistics APIs are opt-in through the bulk-load-profile feature. When enabled, the crate exposes packet counters and write timing breakdowns for bulk-load requests.

§Connecting with async-std

Being not bound to any single runtime, a TcpStream must be created separately and injected to the Client.

use tiberius::{Client, Config, Query, AuthMethod};
use async_std::net::TcpStream;

#[async_std::main]
async fn main() -> anyhow::Result<()> {
    // Using the builder method to construct the options.
    let mut config = Config::new();

    config.host("localhost");
    config.port(1433);

    // Using SQL Server authentication.
    config.authentication(AuthMethod::sql_server("SA", "<YourStrong@Passw0rd>"));

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

    // Taking the address from the configuration, using async-std's
    // TcpStream to connect to the server.
    let tcp = TcpStream::connect(config.get_addr()).await?;

    // We'll disable the Nagle algorithm. Buffering is handled
    // internally with a `Sink`.
    tcp.set_nodelay(true)?;

    // Handling TLS, login and other details related to the SQL Server.
    let mut client = Client::connect(config, tcp).await?;

    // Constructing a query object with one parameter annotated with `@P1`.
    // This requires us to bind a parameter that will then be used in
    // the statement.
    let mut select = Query::new("SELECT @P1");
    select.bind(-4i32);

    // A response to a query is a stream of data, that must be
    // polled to the end before querying again. Using streams allows
    // fetching data in an asynchronous manner, if needed.
    let stream = select.query(&mut client).await?;

    // In this case, we know we have only one query, returning one row
    // and one column, so calling `into_row` will consume the stream
    // and return us the first row of the first result.
    let row = stream.into_row().await?;

    assert_eq!(Some(-4i32), row.unwrap().get(0));

    Ok(())
}

§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 one of the sql-browser-smol, sql-browser-tokio, or sql-browser-async-std feature flags to be enabled and has a bit different way of connecting.

sql-browser-async-std is deprecated because async-std is discontinued upstream. It remains available for existing users. New code should prefer sql-browser-smol with async_net::TcpStream as the closest migration path, or sql-browser-tokio when the application already uses Tokio.

The following compatibility example uses async-std:

use tiberius::{Client, Config, AuthMethod};
use async_std::net::TcpStream;

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

#[async_std::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` from `async-std`, 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).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§

BulkLoadColumn
Read-only destination metadata for one bulk-load column.
BulkLoadColumns
Owned destination metadata for a bulk-load request.
BulkLoadConnectionWriteStatsbulk-load-profile
Detailed timing statistics for bulk-load writes through the framed connection sink.
BulkLoadDirectPacketWriteStatsbulk-load-profile
Detailed timing statistics for an experimental raw-bulk direct packet writer.
BulkLoadPacketStatsbulk-load-profile
Packet-write statistics collected by a bulk-load request.
BulkLoadRequest
A handler for a bulk insert data flow.
BulkLoadStatsbulk-load-profile
Complete benchmark statistics collected by a bulk-load request.
BulkLoadWriteTimingStatsbulk-load-profile
Bulk-load write timing statistics collected by a bulk-load request.
Client
Client is the main entry point to the SQL Server, providing query execution capabilities.
Collation
SQL Server collation metadata attached to character columns.
Column
A column of data from a query.
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.
ExecuteResult
A result from a query execution, listing the number of affected rows.
Query
A query object with bind parameters.
QueryStream
A set of Streams of QueryItem values, which can be either result metadata or a row.
RawRowsAppend
Metadata for rows appended directly into a raw bulk-load buffer.
RawRowsAppendBuffer
Append-only access to a raw bulk-load request buffer.
ResultMetadata
Info about the following stream of rows.
Row
A row of data from a query.
TokenRow
A row of data.
Uuid
A Universally Unique Identifier (UUID).
VarLenContext
Detailed metadata for a variable-length TDS type.

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.
EncryptionLevel
The configured encryption level specifying if encryption is required
FixedLenType
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.
SqlBrowser
An extension trait to a TcpStream to find a port and connecting to a named database instance.
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.