在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
diesel 是一个不错的rust orm框架,提供了cli ,可以方便的进行migration 操作,以及帮助代码生成 安装cli注意需要最新的stable 版本,数据库使用docker-compose 运行 cargo install diesel_cli
项目准备
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
[dependencies]
diesel = { version = "1.0.0", features = ["postgres"] }
dotenv = "0.9.0"
.env 本地开发模式使用
DATABASE_URL=postgres://postgres:dalong@localhost/diesel_demo
.env-prod: docker 生产使用
DATABASE_URL=postgres://postgres:dalong@pg/diesel_demo
docker-compose up -d pg
diesel setup
diesel migration generate create_posts
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
diesel migration run
代码使用
#[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))
}
#[derive(Queryable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
table! {
posts (id) {
id -> Int4,
title -> Varchar,
body -> Text,
published -> Bool,
}
}
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 INTO "public"."posts"("id","title","body","published")
VALUES
(1,E'dalong',E'demo',TRUE);
cargo run --bin show_posts
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" ]
加速配置 [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 的不同,还有依赖) 参考资料http://diesel.rs/guides/getting-started/ |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论