首页
/ Clorinde 开源项目教程

Clorinde 开源项目教程

2025-05-25 04:08:28作者:管翌锬

1. 项目介绍

Clorinde 是一个用于生成类型检查的 Rust 接口从 PostgreSQL 查询的开源项目。它以 SQL 为优先的方法,通过强大的查询验证,同步和异步驱动支持,非分配行映射等功能,提供了一个接近原生 rust-postgres 性能的数据映射工具。Clorinde 是 Cornucopia 项目的分支,它在原有基础上进行了架构改进和功能扩展。

2. 项目快速启动

首先,确保你已经安装了 Rust 和 Cargo。以下是快速启动 Clorinde 项目的步骤:

# 克隆项目仓库
git clone https://github.com/halcyonnouveau/clorinde.git

# 进入项目目录
cd clorinde

# 安装依赖
cargo install --path .

# 编译项目
cargo build

创建一个简单的查询

在项目目录中创建一个名为 queries 的文件夹,并在该文件夹中创建一个 SQL 文件,例如 authors.sql

-- queries/authors.sql
! insert_author
INSERT INTO
  Author (first_name, last_name, country)
VALUES
  (:first_name, :last_name, :country);

! authors
SELECT
  first_name, last_name, country
FROM
  Author;

生成 Rust 代码

使用 Clorinde CLI 工具生成对应的 Rust 代码:

clorinde generate

配置 Cargo.toml

将生成的 crate 添加到你的 Cargo.toml 文件中:

[dependencies]
clorinde = { path = "./clorinde" }

使用生成的代码

在你的 Rust 项目中,引入生成的模块并使用它:

use clorinde::queries::authors::{authors, insert_author};

fn main() {
    let client = // 获取数据库连接

    insert_author.bind(&client, "Agatha", "Christie", "England");

    let all_authors = authors(&client).all();
    for author in all_authors {
        println!("[{}] {}, {}", author.country, author.last_name.to_uppercase(), author.first_name);
    }
}

3. 应用案例和最佳实践

  • 类型安全和性能:Clorinde 强调编译时安全性和高性能,确保你的数据库操作既安全又高效。
  • SQL 验证:通过 SQL-first 方法,在编写 Rust 代码之前验证 SQL 查询的正确性。
  • 驱动支持:同时支持同步和异步数据库驱动,根据应用需求选择合适的驱动。

4. 典型生态项目

Clorinde 可以与其他 Rust 数据库项目配合使用,例如:

  • rust-postgres:一个用于 PostgreSQL 的 Rust 客户端库。
  • sqlx:一个异步的 Rust 数据库框架,支持多种数据库。
  • diesel:一个用于 Rust 的数据库框架,提供类型安全的 SQL 查询。

通过以上教程,你可以开始使用 Clorinde 来提高 Rust 项目中数据库操作的效率和安全性。

登录后查看全文

项目优选

收起
leetcodeleetcode
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
51
14
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
445
366
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
97
177
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
52
120
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
274
470
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
88
245
MateChatMateChat
前端智能化场景解决方案UI库,轻松构建你的AI应用,我们将持续完善更新,欢迎你的使用与建议。 官网地址:https://matechat.gitcode.com
637
77
IImageKnife
专门为OpenHarmony打造的一款图像加载缓存库,致力于更高效、更轻便、更简单
ArkTS
20
12
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
346
34
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
344
233