rust:diesel

Diesel

公式: Getting Started with Diesel

デフォルトのすべて対応している DB バックエンドをビルドするのではなく、PostgreSQL のみをビルドする場合は以下のコマンドを実行する🤔

$ cargo install diesel_cli --no-default-features --features postgres

ビルド依存パッケージのインストール…🤔

$ sudo dnf install -y libpq-devel mariadb-devel sqlite-devel

メタデータの期限切れの最終確認: 1:55:06 前の 2024年05月20日 14時41分08秒 に実施しました。
依存関係が解決しました。
==============================================================================================================
 パッケージ                  アーキテクチャー     バージョン                       リポジトリー         サイズ
==============================================================================================================
インストール:
 libpq-devel                 x86_64               16.1-4.fc40                      fedora               111 k
 mariadb-devel               x86_64               3:10.11.6-3.fc40                 fedora               1.1 M
 sqlite-devel                x86_64               3.45.1-2.fc40                    fedora               149 k

トランザクションの概要
==============================================================================================================

ダウンロードサイズの合計: 1.4 M
インストール後のサイズ: 6.7 M
パッケージのダウンロード:
(1/3): libpq-devel-16.1-4.fc40.x86_64.rpm                                     233 kB/s | 111 kB     00:00    
(2/3): sqlite-devel-3.45.1-2.fc40.x86_64.rpm                                  287 kB/s | 149 kB     00:00    
(3/3): mariadb-devel-10.11.6-3.fc40.x86_64.rpm                                1.1 MB/s | 1.1 MB     00:01    
--------------------------------------------------------------------------------------------------------------
合計                                                                          706 kB/s | 1.4 MB     00:01     
トランザクションの確認を実行中
トランザクションの確認に成功しました。
トランザクションのテストを実行中
トランザクションのテストに成功しました。
トランザクションを実行中
  準備             :                                                                                      1/1 
  インストール中   : sqlite-devel-3.45.1-2.fc40.x86_64                                                    1/6 
  インストール中   : mariadb-devel-3:10.11.6-3.fc40.x86_64                                                2/6 
  インストール中   : libpq-devel-16.1-4.fc40.x86_64                                                       3/6 
  整理             : sqlite-devel-3.45.1-2.fc40.x86_64                                                    4/6 
  整理             : mariadb-devel-3:10.11.6-3.fc40.x86_64                                                5/6 
  整理             : libpq-devel-16.1-4.fc40.x86_64                                                       6/6 
  scriptletの実行中: libpq-devel-16.1-4.fc40.x86_64                                                       6/6 

インストール済み:
  libpq-devel-16.1-4.fc40.x86_64   mariadb-devel-3:10.11.6-3.fc40.x86_64   sqlite-devel-3.45.1-2.fc40.x86_64  

完了しました!

Diesel のインストール…🤔

$ cargo install diesel_cli

    Updating crates.io index
  Installing diesel_cli v2.1.1
    Updating crates.io index
   Compiling proc-macro2 v1.0.83
   Compiling unicode-ident v1.0.12
   Compiling serde v1.0.202
   Compiling pkg-config v0.3.30
   Compiling tinyvec_macros v0.1.1
   Compiling hashbrown v0.14.5
   Compiling equivalent v1.0.1
   Compiling tinyvec v1.6.0
   Compiling quote v1.0.36
   Compiling indexmap v2.2.6
   Compiling syn v2.0.65
   Compiling vcpkg v0.2.15
   Compiling utf8parse v0.2.1
   Compiling winnow v0.5.40
   Compiling libsqlite3-sys v0.28.0
   Compiling anstyle-parse v0.2.4
   Compiling unicode-normalization v0.1.23
   Compiling mysqlclient-sys v0.2.5
   Compiling unicode-bidi v0.3.15
   Compiling anstyle v1.0.7
   Compiling colorchoice v1.0.1
   Compiling autocfg v1.3.0
   Compiling pq-sys v0.4.8
   Compiling percent-encoding v2.3.1
   Compiling memchr v2.7.2
   Compiling anstyle-query v1.0.3
   Compiling is_terminal_polyfill v1.70.0
   Compiling anstream v0.6.14
   Compiling aho-corasick v1.1.3
   Compiling diesel_table_macro_syntax v0.1.0
   Compiling form_urlencoded v1.2.1
   Compiling num-traits v0.2.19
   Compiling idna v0.5.0
   Compiling serde_derive v1.0.202
   Compiling regex-syntax v0.8.3
   Compiling clap_lex v0.7.0
   Compiling strsim v0.11.1
   Compiling regex-automata v0.4.6
   Compiling serde_spanned v0.6.6
   Compiling toml_datetime v0.6.6
   Compiling toml_edit v0.19.15
   Compiling toml v0.7.8
   Compiling clap_builder v4.5.2
   Compiling migrations_internals v2.1.0
   Compiling diesel_derives v2.1.4
   Compiling url v2.5.0
   Compiling overload v0.1.1
   Compiling bitflags v2.5.0
   Compiling itoa v1.0.11
   Compiling byteorder v1.5.0
   Compiling diesel v2.1.6
   Compiling nu-ansi-term v0.46.0
   Compiling clap v4.5.4
   Compiling migrations_macros v2.1.0
   Compiling regex v1.10.4
   Compiling iana-time-zone v0.1.60
   Compiling chrono v0.4.38
   Compiling serde_regex v1.1.0
   Compiling clap_complete v4.5.2
   Compiling diesel_migrations v2.1.0
   Compiling diffy v0.3.0
   Compiling heck v0.4.1
   Compiling dotenvy v0.15.7
   Compiling diesel_cli v2.1.1
    Finished `release` profile [optimized] target(s) in 2m 26s
  Installing /home/tomoyan/.cargo/bin/diesel
   Installed package `diesel_cli v2.1.1` (executable `diesel`)

動作確認😉

$ diesel -V

diesel 2.1.1

PostgreSQL
PostgreSQL (Podman)

MariaDB
Piwigo - オープンソースの写真管理 Web アプリ (Podman) を使用する😅

SQLite
構築の必要はない

公式: Cargo Workspaces - The Rust Programming Language 翻訳
   Dependency Resolution - The Cargo Book 翻訳
   The Manifest Format - The Cargo Book 翻訳
   Workspaces - The Cargo Book 翻訳

$ mkdir piwigo_rs && cd piwigo_rs
$ nano Cargo.toml

[workspace]
members = []
resolver = "2"

ワークスペースにプロジェクトを作成する🤔

$ cargo new --lib api

    Creating library `api` package
      Adding `api` as member of workspace at `/home/tomoyan/work/piwigo/piwigo_rs`
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

$ cargo new cli

    Creating binary (application) `cli` package
      Adding `cli` as member of workspace at `/home/tomoyan/work/piwigo/piwigo_rs`
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

ワークスペースの Cargo.toml は自動で追加される🤔

$ bat -p --pager never Cargo.toml

[workspace]
members = ["api", "cli"]
resolver = "2"

clap クレートで引数の処理を書く…🤔
公式: clap - Rust

$ cd cli
$ cargo add clap

    Updating crates.io index
      Adding clap v4.5.4 to dependencies
             Features:
             + color
             + error-context
             + help
             + std
             + suggestions
             + usage
             - cargo
             - debug
             - deprecated
             - derive
             - env
             - string
             - unicode
             - unstable-doc
             - unstable-styles
             - unstable-v5
             - wrap_help

$ bat -p --pager never Cargo.toml

[package]
name = "cli"
version = "0.1.0"
edition = "2021"

[dependencies]
clap = "4.5.4"

$ cargo add clap --features derive

    Updating crates.io index
      Adding clap v4.5.4 to dependencies
             Features:
             + color
             + error-context
             + help
             + std
             + suggestions
             + usage
             - cargo
             - debug
             - deprecated
             - derive
             - env
             - string
             - unicode
             - unstable-doc
             - unstable-styles
             - unstable-v5
             - wrap_help

$ bat -p --pager never Cargo.toml

[package]
name = "cli"
version = "0.1.0"
edition = "2021"

[dependencies]
clap = { version = "4.5.4", features = ["derive"] }

$ nano src/main.rs

use clap::Parser;

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// 挨拶する人の名前🤪
    #[arg(short, long)]
    name: String,

    /// 挨拶の回数😍
    #[arg(short, long, default_value_t = 1)]
    count: u8,
}

fn main() {
    let args = Args::parse();

    for _ in 0..args.count {
        println!("Hello {} 💩🤪", args.name)
    }
}

$ cargo run -- --help

   Compiling proc-macro2 v1.0.83
   Compiling unicode-ident v1.0.12
   Compiling utf8parse v0.2.1
   Compiling is_terminal_polyfill v1.70.0
   Compiling anstyle v1.0.7
   Compiling anstyle-parse v0.2.4
   Compiling colorchoice v1.0.1
   Compiling anstyle-query v1.0.3
   Compiling heck v0.5.0
   Compiling strsim v0.11.1
   Compiling anstream v0.6.14
   Compiling clap_lex v0.7.0
   Compiling clap_builder v4.5.2
   Compiling quote v1.0.36
   Compiling syn v2.0.65
   Compiling clap_derive v4.5.4
   Compiling clap v4.5.4
   Compiling cli v0.1.0 (/home/tomoyan/work/piwigo/piwigo_rs/cli)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 15.13s
     Running `/home/tomoyan/work/piwigo/piwigo_rs/target/debug/cli --help`
Simple program to greet a person

Usage: cli [OPTIONS] --name <NAME>

Options:
  -n, --name <NAME>    挨拶する人の名前🤪
  -c, --count <COUNT>  挨拶の回数😍 [default: 1]
  -h, --help           Print help
  -V, --version        Print version

$ cargo run -- --name Tomoyan -c 7

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
     Running `/home/tomoyan/work/piwigo/piwigo_rs/target/debug/cli --name Tomoyan -c 7`
Hello Tomoyan 💩🤪
Hello Tomoyan 💩🤪
Hello Tomoyan 💩🤪
Hello Tomoyan 💩🤪
Hello Tomoyan 💩🤪
Hello Tomoyan 💩🤪
Hello Tomoyan 💩🤪

データベース接続設定

Diesel でデータベース接続するために、.env ファイルに DATABASE_URL 環境変数を設定する…🤔
データベースは Podman のコンテナ内であるため、UNIX ドメインソケットではなく TCP/IP ソケット通信する必要があるので、ローカルホストは IPv6/IPv4 アドレスを指定する😉

$ echo DATABASE_URL=mysql://piwigo:piwigo@[::1]:3306/piwigo_db > .env
or
$ echo DATABASE_URL=mysql://piwigo:piwigo@127.0.0.1:3306/piwigo_db > .env
$ diesel setup

--features に仕様する RDBMS に応じて postgres|mysql|sqlite を指定する🤔
複数指定する場合はカンマ区切りで指定できる😉

$ cargo add diesel --features postgres,mysql
or
$ cargo add diesel --features mysql

    Updating crates.io index
      Adding diesel v2.1.6 to dependencies
             Features:
             + 32-column-tables
             + bitflags
             + byteorder
             + itoa
             + mysql
             + mysql_backend
             + mysqlclient-sys
             + percent-encoding
             + postgres
             + postgres_backend
             + pq-sys
             + url
             + with-deprecated
             28 deactivated features

$ bat -p --pager never Cargo.toml

[package]
name = "cli"
version = "0.1.0"
edition = "2021"

[dependencies]
clap = { version = "4.5.4", features = ["derive"] }
diesel = { version = "2.1.6", features = ["postgres", "mysql"] }

UNIX ドメインソケット経由の接続エラー

UNIX ドメインソケット経由でローカルサーバーに接続できない場合は…🤪

$ echo DATABASE_URL=mysql://piwigo:piwigo@localhost:3306/piwigo_db > .env
$ diesel setup

Creating database: piwigo_db
Can't connect to local server through socket '/var/lib/mysql/mysql.sock' (2)

ホストをIPv6 アドレス@[::1]:3306 または IPv4 アドレス@127.0.0.1:3306 で指定する🤔

$ echo DATABASE_URL=mysql://piwigo:piwigo@[::1]:3306/piwigo_db > .env
or
$ echo DATABASE_URL=mysql://piwigo:piwigo@127.0.0.1:3306/piwigo_db > .env
$ diesel setup

以下の mysql コマンドの仕様と同じ🤔

UNIX ドメインソケット経由でローカルサーバーに接続できない場合は…🤪

$ mysql -u root -p

Enter password: 
ERROR 2002 (HY000): Can't connect to local server through socket '/var/lib/mysql/mysql.sock' (2)

同一コンピューター内なので UNIX ドメインソケット (mysql.sock) で通信しようとするが、Podman や Docker などのコンテナ仮想化では別マシンと通信するときと同様に TCP/IP ソケット通信でなければ接続できない。

-h ::1 オプションで IPv6/IPv4 ローカルホストアドレスを指定すると TCP/IP ソケット通信にできる😉
または、-P 3306 オプションでポート指定することでも同様に通信できる😊

$ mysql -u root -h ::1 -p
or
$ mysql -u root -h 127.0.0.1 -p
or
$ mysql -u root -P 3306 -p

Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 54
Server version: 10.11.6-MariaDB-log Alpine Linux

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> \q
Bye

参考: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) - Stack Overflow

2022/08/04 04:24

RDBMS スキーマーから src/schema.rs を生成する

Diesel の print-schema コマンドでデータベース スキーマのテーブル定義を Rust ソースコードで出力できる🤔

$ diesel print-schema -o piwigo_images | bat -p -l rs --pager never

// @generated automatically by Diesel CLI.

pub mod sql_types {
    #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)]
    #[diesel(mysql_type(name = "Mediumint"))]
    pub struct PiwigoImagesAddedByMediumint;

    #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)]
    #[diesel(mysql_type(name = "Mediumint"))]
    pub struct PiwigoImagesFilesizeMediumint;

    #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)]
    #[diesel(mysql_type(name = "Mediumint"))]
    pub struct PiwigoImagesIdMediumint;
}

diesel::table! {
    use diesel::sql_types::*;
    use super::sql_types::PiwigoImagesIdMediumint;
    use super::sql_types::PiwigoImagesFilesizeMediumint;
    use super::sql_types::PiwigoImagesAddedByMediumint;

    piwigo_images (id) {
        id -> Unsigned<PiwigoImagesIdMediumint>,
        #[max_length = 255]
        file -> Varchar,
        date_available -> Datetime,
        date_creation -> Nullable<Datetime>,
        #[max_length = 255]
        name -> Nullable<Varchar>,
        comment -> Nullable<Text>,
        #[max_length = 255]
        author -> Nullable<Varchar>,
        hit -> Unsigned<Integer>,
        filesize -> Nullable<Unsigned<PiwigoImagesFilesizeMediumint>>,
        width -> Nullable<Unsigned<Smallint>>,
        height -> Nullable<Unsigned<Smallint>>,
        #[max_length = 4]
        coi -> Nullable<Char>,
        #[max_length = 4]
        representative_ext -> Nullable<Varchar>,
        date_metadata_update -> Nullable<Date>,
        rating_score -> Nullable<Unsigned<Float>>,
        #[max_length = 255]
        path -> Varchar,
        storage_category_id -> Nullable<Unsigned<Smallint>>,
        level -> Unsigned<Tinyint>,
        #[max_length = 32]
        md5sum -> Nullable<Char>,
        added_by -> Unsigned<PiwigoImagesAddedByMediumint>,
        rotation -> Nullable<Unsigned<Tinyint>>,
        latitude -> Nullable<Double>,
        longitude -> Nullable<Double>,
        lastmodified -> Nullable<Timestamp>,
    }
}

bat コマンドについては bat - シンタックスハイライトとGitとの連携機能付きの cat(1) クローン を参照😉

それを src/schema.rs へリダイレクトで追記する😉

$ diesel print-schema -o piwigo_images >> src/schema.rs

schema.rs から src/models.rs を生成する

$ diesel_ext --model -t | bat -p -l rs --pager never

Unsigned<PiwigoImagesIdMediumint> is not recognized. Please feel free to expand the HashMap. This could provide good hints: https://kotiri.com/2018/01/31/postgresql-diesel-rust-types.html
Nullable<Unsigned<PiwigoImagesFilesizeMediumint>> is not recognized. Please feel free to expand the HashMap. This could provide good hints: https://kotiri.com/2018/01/31/postgresql-diesel-rust-types.html
Nullable<Unsigned<Float>> is not recognized. Please feel free to expand the HashMap. This could provide good hints: https://kotiri.com/2018/01/31/postgresql-diesel-rust-types.html
Unsigned<PiwigoImagesAddedByMediumint> is not recognized. Please feel free to expand the HashMap. This could provide good hints: https://kotiri.com/2018/01/31/postgresql-diesel-rust-types.html
// Generated by diesel_ext

#![allow(unused)]
#![allow(clippy::all)]


use chrono::NaiveDate;
use chrono::NaiveDateTime;
#[derive(Queryable, Debug)]
#[diesel(table_name = piwigo_images)]
pub struct PiwigoImage {
    pub id: /* TODO: unknown type Unsigned<PiwigoImagesIdMediumint> */,
    pub file: String,
    pub date_available: NaiveDateTime,
    pub date_creation: Option<NaiveDateTime>,
    pub name: Option<String>,
    pub comment: Option<String>,
    pub author: Option<String>,
    pub hit: u32,
    pub filesize: Option</* TODO: unknown type Nullable<Unsigned<PiwigoImagesFilesizeMediumint>> */>,
    pub width: Option<u16>,
    pub height: Option<u16>,
    pub coi: Option<String>,
    pub representative_ext: Option<String>,
    pub date_metadata_update: Option<NaiveDate>,
    pub rating_score: Option</* TODO: unknown type Nullable<Unsigned<Float>> */>,
    pub path: String,
    pub storage_category_id: Option<u16>,
    pub level: u8,
    pub md5sum: Option<String>,
    pub added_by: /* TODO: unknown type Unsigned<PiwigoImagesAddedByMediumint> */,
    pub rotation: Option<u8>,
    pub latitude: Option<f64>,
    pub longitude: Option<f64>,
    pub lastmodified: Option<NaiveDateTime>,
}

データベース データ型との対応関係のヒント

参考: MySQL :: MySQL 8.0 Reference Manual :: 13.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT

タイプ ストレージ (Bytes) 符号付き最小値 符号なしの最小値 符号付き最大値 符号なしの最大値
TINYINT 1 -128 0 127 255
SMALLINT 2 -32,768 0 32,767 65,535
MEDIUMINT 3 -8,388,608 0 8,388,607 16,777,215
INT 4 -2,147,483,648 0 2,147,483,647 4,294,967,295
BIGINT 8 -263 0 263-1 264-1

diesel::sql_types - Rust
min_max_traits - Rust

符号なし整数型
タイプ 最小値 最大値
u8 0 28-1
u16 0 216-1
u32 0 232-1
u64 0 264-1
u128 0

2128-1
符号付き 2 の補数整数型
タイプ 最小値 最大値
i8 -(27) 27-1
i16 -(215) 215-1
i32 -(231) 231-1
i64 -(263) 263-1
i128

-(2127)

2127-1

postgresql-diesel-rust-types.md

PostgreSQL Type PostgreSQL Size Description Range Diesel Type Rust Type
Nullable Types nullable Nullable<T> Option<T>
Numeric Types
smallint, int2 2 bytes signed integer -32768 to +32767 SmallInt i16
integer, int, int4 4 bytes signed integer -2147483648 to +2147483647 Integer i32
bigint, int8 8 bytes signed integer -9223372036854775808 to +9223372036854775807 BigInt i64
numeric(p, s), decimal(p, s) 2 bytes per 4 digits + 3 to 8 bytes exact numeric of selectable precision 131072.16383 digits Numeric bigdecimal::BigDecimal
real, float4 4 bytes single precision floating-point number 6 digits precision Float f32
double precision, float8 8 bytes double precision floating-point number 15 digits precision Double f64
smallserial, serial2 2 bytes autoincrementing integer 1 to 32767 SmallInt i16
serial, serial4 4 bytes autoincrementing integer 1 to 2147483647 Integer i32
bigserial, serial8 8 bytes autoincrementing integer 1 to 9223372036854775807 BigInt i64
Monetary Types
money 8 bytes currency amount -92233720368547758.08 to +92233720368547758.07 Money Cents
Character Types
character varying(n), varchar(n) n+1 or n+4 bytes variable-length character string Text String, &str
character(n), char(n) n+1 or n+4 bytes fixed-length character string Text String, &str
text n+1 or n+4 bytes variable-length character string Text String, &str
Binary Data Types
bytea n+1 to n+4 bytes binary data (“byte array”) Binary Vec<u8>, &u8
Date/Time Types
timestamp, timestamp(p) without time zone 8 bytes date and time of day 4713 BC to 294276 AD, 1 microsecond Timestamp chrono::NaiveDateTime
timestamptz, timestamp(p) with time zone 8 bytes date and time of day, with time zone 4713 BC to 294276 AD, 1 microsecond Timestamptz chrono::DateTime
date 4 bytes calendar date (year, month, day) 4713 BC to 5874897 AD, 1 day Date chrono::NaiveDate
time, time(p) without time zone 8 bytes time of day (no date) 00:00:00 to 24:00:00, 1 microsecond Time chrono::NaiveTime
timetz, time(p) with time zone 12 bytes time of day (no date), with time zone 00:00:00+1459 to 24:00:00-1459, 1 microsecond
interval(fields)(p) 16 bytes time span -178000000 years to 178000000 years, 1 microsecond Interval PgInterval
Boolean Type
boolean, bool 1 byte logical Boolean (true/false) Bool bool
Geometric Types
point (x,y) 16 bytes geometric point on a plane
line {A,B,C} 32 bytes infinite line on a plane
lseg 1) 32 bytes finite line segment on a plane
box 2) 32 bytes rectangular box on a plane
path ((x1,y1),…) 16+16n bytes closed geometric path on a plane
path [(x1,y1),…] 16+16n bytes open geometric path on a plane
polygon ((x1,y1),…) 40+16n bytes closed geometric path on a plane
circle <(x,y),r\> 24 bytes circle on a plane
Network Address Types
cidr 7 or 19 bytes IPv4 or IPv6 network address Cidr ipnetwork::IpNetwork
inet 7 or 19 bytes IPv4 or IPv6 host address Inet ipnetwork::IpNetwork
macaddr 6 bytes MAC address MacAddr [u8; 6]
macaddr8 8 bytes MAC address (EUI-64 format)
Enumerated Types
enum 4 bytes enumerated value (user-defined) String, enum
Bit String Types
bit(n) 1 byte per 8 bits + 5 or 8 bytes fixed-length bit string
bit varying(n), varbit 1 byte per 8 bits + 5 or 8 bytes variable-length bit string
Text Search Types
tsvector text search document TsVector
tsquery text search query TsQuery
UUID Type
uuid 16 bytes universally unique identifier Uuid uuid::Uuid
XML Type
xml XML data
JSON Types
json textual JSON data Json serde_json::Value
jsonb binary JSON data, decomposed Jsonb serde_json::Value
Arrays
t[] array of values Array<T> Vec<T>, Vec<Option<T», &[T], &[Option<T>]
Range Types
int4range range of integer Range<Integer>
int8range range of bigint Range<BigInt>
numrange range of numeric Range<Numeric>
tsrange range of timestamp Range<Timestamp>
tstzrange range of timestamptz Range<Timestamptz>
daterange range of date Range<Date> (Bound<chrono::NaiveDate>, Bound<chrono::NaiveDate>)

参考文献


1) , 2)
x1,y1),(x2,y2
  • rust/diesel.txt
  • 最終更新: 2024/06/04 17:41
  • by ともやん