35 releases

0.4.5 Nov 12, 2024
0.4.3 Oct 11, 2024
0.3.16 Jun 13, 2024
0.3.13 Sep 9, 2023
0.1.2 Mar 24, 2022

#1154 in Database interfaces

Download history 145/week @ 2024-08-23 16/week @ 2024-08-30 70/week @ 2024-09-06 192/week @ 2024-09-13 37/week @ 2024-09-20 42/week @ 2024-09-27 19/week @ 2024-10-04 179/week @ 2024-10-11 14/week @ 2024-10-18 1/week @ 2024-10-25 229/week @ 2024-11-08 47/week @ 2024-11-15 12/week @ 2024-11-22 36/week @ 2024-11-29 59/week @ 2024-12-06

163 downloads per month

Apache-2.0

14KB
220 lines

sqlx-type

crates.io crates.io License actions-badge

Proc macros to perform type sql queries similarly to sqlx::query, but without the need to run cargo sqlx prepare

A schema definition must be placed in "sqlx-type-schema.sql" in the root of a using crate:

DROP TABLE IF EXISTS `t1`;
CREATE TABLE `t1` (
    `id` int(11) NOT NULL,
    `cbool` tinyint(1) NOT NULL,
    `cu8` tinyint UNSIGNED NOT NULL,
    `cu16` smallint UNSIGNED NOT NULL,
    `cu32` int UNSIGNED NOT NULL,
    `cu64` bigint UNSIGNED NOT NULL,
    `ci8` tinyint,
    `ci16` smallint,
    `ci32` int,
    `ci64` bigint,
    `ctext` varchar(100) NOT NULL,
    `cbytes` blob,
    `cf32` float,
    `cf64` double
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `t1`
    MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

See sql_type::schema for a detailed description.

This schema can then be used to type queries:

use std::env, sqlx::MySqlPool, sqlx_type::query;

async fn test() -> Result<(), sqlx::Error> {
    let pool = MySqlPool::connect(&env::var("DATABASE_URL").unwrap()).await?;

    let id = query!("INSERT INTO `t1` (`cbool`, `cu8`, `cu16`, `cu32`, `cu64`, `ctext`)
        VALUES (?, ?, ?, ?, ?, ?)", true, 8, 1243, 42, 42, "Hello world")
        .execute(&pool).await?.last_insert_id();

    let row = query!("SELECT `cu16`, `ctext`, `ci32` FROM `t1` WHERE `id`=?", id)
        .fetch_one(&pool).await?;

    assert_eq!(row.cu16, 1234);
    assert_eq!(row.ctext, "Hello would");
    assert!(row.ci32.is_none());
    Ok(())
}

Dependencies

~3.5–5MB
~89K SLoC