diesel rust orm 框架试用
diesel 是一个不错的rust orm框架,提供了cli ,可以方便的进行migration 操作,以及帮助代码生成
以下是一个简单的试用
安装cli
注意需要最新的stable 版本,数据库使用docker-compose 运行
cargo install diesel_cli
项目准备
- docker-compose 服务
关于rust 项目构建的,后边说明
version: "3"
services:
app:
build: ./
pg:
image: postgres:12.1-alpine
environment:
- "POSTGRES_PASSWORD:dalong"
ports:
- "5432:5432"
- 初始化项目
cargo new --lib diesel_demo
cd diesel_demo
- 添加diesel 依赖
Cargo.toml
[dependencies]
diesel = { version = "1.0.0", features = ["postgres"] }
dotenv = "0.9.0"
- 添加数据库环境变量
项目使用dotenv管理环境变量,12 factor 模式
.env 本地开发模式使用
DATABASE_URL=postgres://postgres:dalong@localhost/diesel_demo
.env-prod: docker 生产使用
DATABASE_URL=postgres://postgres:dalong@pg/diesel_demo
- 启动pg 服务
docker-compose up -d pg
- 创建数据库
diesel setup
- 创建一个实体
diesel migration generate create_posts
- 添加migration 脚本
up.sql
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title VARCHAR NOT NULL,
body TEXT NOT NULL,
published BOOLEAN NOT NULL DEFAULT 'f'
)
down.sql
DROP TABLE posts
- schema migration
diesel migration run
代码使用
- 创建连接
src/lib.rs
#[macro_use]
extern crate diesel;
extern crate dotenv;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;
pub mod schema;
pub mod models;
pub fn establish_connection() -> PgConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
PgConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url))
}
- model
src/models.rs
#[derive(Queryable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
- 生成的schema
table! {
posts (id) {
id -> Int4,
title -> Varchar,
body -> Text,
published -> Bool,
}
}
- 代码入口
src/bin/show_posts.rs
extern crate diesel_demo;
extern crate diesel;
use self::diesel_demo::*;
use self::models::*;
use self::diesel::prelude::*;
fn main() {
use diesel_demo::schema::posts::dsl::*;
let connection = establish_connection();
let results = posts.filter(published.eq(true))
.limit(5)
.load::<Post>(&connection)
.expect("Error loading posts");
println!("Displaying {} posts", results.len());
for post in results {
println!("{}", post.title);
println!("----------\n");
println!("{}", post.body);
}
}
- insert demo 数据
INSERT INTO "public"."posts"("id","title","body","published")
VALUES
(1,E'dalong',E'demo',TRUE);
- 本地运行
cargo run --bin show_posts
- docker运行
dockerfile,使用多阶段构建(制作小的镜像),同时为了提高构建的速度,使用了中科大的cargo镜像
FROM rustlang/rust:nightly-slim as build
WORKDIR /app
RUN mkdir -p $HOME/.cargo
COPY diesel_demo/ /app
# cargo 加速
COPY diesel_demo/config $HOME/.cargo/
RUN apt-get update && apt-get install -y libpq-dev
RUN rustup --version
RUN rustc --version && \
rustup --version && \
cargo --version
RUN cargo build --bin show_posts --release
FROM debian:stretch-slim
WORKDIR /app
RUN apt-get update && apt-get install -y libpq5
COPY diesel_demo/.env-prod /app/.env
COPY --from=build /app/target/release/show_posts /usr/local/bin/show_posts
CMD [ "show_posts" ]
加速配置
config
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
说明
从目前来说rust 以及python 还有php 等语言,使用alpine 做为基础镜像并不太好(依赖,libc 的不同,还有依赖)
使用debian,ubuntu,还有centos 作为这类语言的基础镜像会很不错,有时表象的小,可能并不是最优的方案
参考资料
http://diesel.rs/guides/getting-started/
https://github.com/rongfengliang/diesel-docker-running
https://www.cnblogs.com/rongfengliang/p/11337157.html
https://lug.ustc.edu.cn/wiki/mirrors/help/rust-crates