Skip to content

Commit

Permalink
修复seaorm 迁移,增加cursor提示文件
Browse files Browse the repository at this point in the history
  • Loading branch information
fankaiLiu committed Jan 21, 2025
1 parent 29e0c7f commit 41f049e
Show file tree
Hide file tree
Showing 15 changed files with 1,204 additions and 24 deletions.
21 changes: 20 additions & 1 deletion locales/code_comment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -739,4 +739,23 @@ next_page:
uk: Наступна
th: ถัดไป
el: Επόμενο
da: Næste
da: Næste

talk_to_me_lang:
en: "Talk to me in English"
zh_CN: "和我说中文"
zh_TW: "和我說中文"
fr: "Parlez-moi en français"
ja: "日本語で話してください"
es: "Háblame en español"
de: "Sprechen Sie mit mir auf Deutsch"
ru: "Говорите со мной по-русски"
it: "Parlami in italiano"
pt: "Fale comigo em português"
ko: "한국어로 말씀해 주세요"
no: "Snakk med meg på norsk"
is: "Talaðu við mig á íslensku"
uk: "Говоріть зі мною українською"
th: "พูดกับฉันเป็นภาษาไทย"
el: "Μίλα μου στα ελληνικά"
da: "Tal med mig på dansk"
34 changes: 17 additions & 17 deletions locales/readme.yml
Original file line number Diff line number Diff line change
Expand Up @@ -862,23 +862,23 @@ mongodb_usage_import_user_data:
el: 🎯 Παρακαλώ πρώτα τρέξτε το πρόγραμμα, στη συνέχεια εισάγετε τα δεδομένα από το data/user.json στον πίνακα χρήστη
da: 🎯 Kør venligst først programmet, importér derefter data fra data/user.json ind i brugertabellen
rust_version_tip:
en: "😄 The latest version of Salvo requires Rust version 1.75. If your compilation fails, please try upgrading with `rustup update`."
zh_CN: "😄 最新版的 Salvo 依赖 Rust 版本 1.75。如果编译失败,请尝试使用 `rustup update` 来升级版本。"
zh_TW: "😄 最新版的 Salvo 需要 Rust 版本 1.75。如果您的編譯失敗,請嘗試使用 `rustup update` 來升級版本。"
fr: "😄 La dernière version de Salvo nécessite la version 1.75 de Rust. Si votre compilation échoue, veuillez essayer de mettre à niveau avec `rustup update`."
ja: "😄 最新の Salvo には Rust のバージョン 1.75 が必要です。コンパイルに失敗した場合は、`rustup update`でアップグレードしてみてください。"
es: "😄 La última versión de Salvo requiere la versión 1.75 de Rust. Si la compilación falla, intenta actualizar con `rustup update`."
de: "😄 Die neueste Version von Salvo erfordert die Rust-Version 1.75. Wenn die Kompilierung fehlschlägt, versuchen Sie bitte, mit `rustup update` zu aktualisieren."
ru: "😄 Последняя версия Salvo требует версии Rust 1.75. Если компиляция не удаётся, пожалуйста, попробуйте обновиться с помощью `rustup update`."
it: "😄 L'ultima versione di Salvo richiede la versione 1.75 di Rust. Se la compilazione fallisce, prova ad aggiornare con `rustup update`."
pt: "😄 A versão mais recente do Salvo requer a versão 1.75 do Rust. Se a compilação falhar, tente atualizar com `rustup update`."
ko: "😄 최신 Salvo 버전은 Rust 1.75 버전을 필요로 합니다. 컴파일에 실패한다면, `rustup update`로 업그레이드를 시도해보세요."
no: "😄 Den nyeste versjonen av Salvo krever Rust versjon 1.75. Hvis kompileringen feiler, vennligst prøv å oppgradere med `rustup update`."
is: "😄 Nýjasta útgáfa af Salvo krefst Rust útgáfu 1.75. Ef þýðing mistekst, reyndu þá að uppfæra með `rustup update`."
uk: "😄 Остання версія Salvo потребує версію Rust 1.75. Якщо компіляція не вдається, будь ласка, спробуйте оновити за допомогою `rustup update`."
th: "😄 เวอร์ชันล่าสุดของ Salvo ต้องการ Rust เวอร์ชัน 1.75 หากการคอมไพล์ล้มเหลว กรุณาลองอัพเดทด้วย `rustup update`"
el: "😄 Η τελευταία έκδοση του Salvo απαιτεί την έκδοση 1.75 της Rust. Εάν η συνταξιοποίηση αποτύχει, δοκιμάστε να αναβαθμίσετε με `rustup update`."
da: "😄 Den nyeste version af Salvo kræver Rust version 1.75. Hvis din kompilering fejler, prøv da at opgradere med `rustup update`."
en: "😄 The latest version of Salvo requires Rust version 1.80. If your compilation fails, please try upgrading with `rustup update`."
zh_CN: "😄 最新版的 Salvo 依赖 Rust 版本 1.80。如果编译失败,请尝试使用 `rustup update` 来升级版本。"
zh_TW: "😄 最新版的 Salvo 需要 Rust 版本 1.80。如果您的編譯失敗,請嘗試使用 `rustup update` 來升級版本。"
fr: "😄 La dernière version de Salvo nécessite la version 1.80 de Rust. Si votre compilation échoue, veuillez essayer de mettre à niveau avec `rustup update`."
ja: "😄 最新の Salvo には Rust のバージョン 1.80 が必要です。コンパイルに失敗した場合は、`rustup update`でアップグレードしてみてください。"
es: "😄 La última versión de Salvo requiere la versión 1.80 de Rust. Si la compilación falla, intenta actualizar con `rustup update`."
de: "😄 Die neueste Version von Salvo erfordert die Rust-Version 1.80. Wenn die Kompilierung fehlschlägt, versuchen Sie bitte, mit `rustup update` zu aktualisieren."
ru: "😄 Последняя версия Salvo требует версии Rust 1.80. Если компиляция не удаётся, пожалуйста, попробуйте обновиться с помощью `rustup update`."
it: "😄 L'ultima versione di Salvo richiede la versione 1.80 di Rust. Se la compilazione fallisce, prova ad aggiornare con `rustup update`."
pt: "😄 A versão mais recente do Salvo requer a versão 1.80 do Rust. Se a compilação falhar, tente atualizar com `rustup update`."
ko: "😄 최신 Salvo 버전은 Rust 1.80 버전을 필요로 합니다. 컴파일에 실패한다면, `rustup update`로 업그레이드를 시도해보세요."
no: "😄 Den nyeste versjonen av Salvo krever Rust versjon 1.80. Hvis kompileringen feiler, vennligst prøv å oppgradere med `rustup update`."
is: "😄 Nýjasta útgáfa af Salvo krefst Rust útgáfu 1.80. Ef þýðing mistekst, reyndu þá að uppfæra með `rustup update`."
uk: "😄 Остання версія Salvo потребує версію Rust 1.80. Якщо компіляція не вдається, будь ласка, спробуйте оновити за допомогою `rustup update`."
th: "😄 เวอร์ชันล่าสุดของ Salvo ต้องการ Rust เวอร์ชัน 1.80 หากการคอมไพล์ล้มเหลว กรุณาลองอัพเดทด้วย `rustup update`"
el: "😄 Η τελευταία έκδοση του Salvo απαιτεί την έκδοση 1.80 της Rust. Εάν η συνταξιοποίηση αποτύχει, δοκιμάστε να αναβαθμίσετε με `rustup update`."
da: "😄 Den nyeste version af Salvo kræver Rust version 1.80. Hvis din kompilering fejler, prøv da at opgradere med `rustup update`."
build_yml_description:
zh_CN: 此 YAML 文件配置了项目的持续集成 (CI) 管道。它定义了推送代码到仓库时自动执行的步骤。这包括构建软件、运行测试和在满足条件时部署应用程序等任务。
en: This YAML file configures the continuous integration (CI) pipeline for the project. It defines the steps that are executed automatically when code is pushed to the repository. This includes tasks like building the software, running tests, and deploying the application if conditions are met.
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,4 @@ async fn main() -> Result<()> {
}
}
Ok(())
}
}
1 change: 1 addition & 0 deletions src/templates/classic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub(crate) fn create_files(project_path: &Path, selected: Selected, proj: &Proje
"update":t!("update"),
"delete":t!("delete"),
"next_page":t!("next_page"),
"talk_to_me_lang":t!("talk_to_me_lang"),
"salvo_cli_welcome":t!("salvo_cli_welcome"),
"user_list":t!("user_list"),
"are_you_sure_you_want_to_delete":t!("are_you_sure_you_want_to_delete"),
Expand Down
206 changes: 206 additions & 0 deletions templates/classic/diesel/.cursorrules.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
{{ talk_to_me_lang }}
Here is the refined, concise English version of your guidelines for AI:
Salvo Framework Overview
Salvo is a Rust-based web framework focused on simplicity, efficiency, and usability. Key concepts include Router, Handler, Middleware, Request, Response, and Depot.
Key Concepts:
1. Router:
• Create with Router::new().
• Define paths with path() or with_path().
• Use HTTP methods like get(), post(), patch(), delete().
• Support for path parameters (e.g., {id}, <id:num>).
• Filters like filters::path(), filters::get() can be added.
• Add middleware with hoop().
2. Handler:
• Use #[handler] macro for easy definition.
• Optional parameters include Request, Depot, FlowCtrl.
• Return types must implement Writer Trait (e.g., &str, String, Result<T, E>).
3. Middleware:
• Implement Handler Trait.
• Use hoop() to add middleware to Router or Service.
• Control execution flow with FlowCtrl, e.g., ctrl.skip_rest().
4. Request:
• Get path parameters with req.param::<T>("param_name").
• Use req.query::<T>("query_name") for query parameters.
• Parse form or JSON with req.form::<T>("name").await or req.parse_json::<T>().await.
• Extract data into structures with req.extract().
5. Response:
• Render responses with res.render().
• Return types like Text::Plain(), Text::Html(), Json().
• Set status with res.status_code() or StatusError.
• Use Redirect::found() for redirection.
6. Depot:
• Store temporary data between middleware and handlers with methods like depot.insert() and depot.obtain::<T>().
7. Extractors:
• Use #[salvo(extract(...))] annotations to map request data to structures.

Core Features:
• Static File Serving: Use StaticDir or StaticEmbed.
• OpenAPI Support: Auto-generate docs with #[endpoint] macro.

Routing:
• Flat or tree-like route structure supported.

Middleware:
• Middleware is a Handler added to Router, Service, or Catcher.
• FlowCtrl allows skipping handlers or middleware.

Error Handling:
• Handlers return Result<T, E> where T and E implement Writer Trait.
• Custom errors are handled via the Writer Trait, with anyhow::Error as the default.

Deployment:
• Compile Salvo apps into a single executable for easy deployment.

Project Structure:

project/
├── src/
│ ├── routers/
│ ├── models/
│ ├── db/
│ ├── error.rs
│ └── utils.rs
├── views/
│ └── *.html
├── migrations/
└── assets/
├── js/
└── css/

JSON Response Format:

#[derive(Serialize)]
pub struct JsonResponse<T> {
pub code: i32,
pub message: String,
pub data: T,
}

Frontend Guidelines:
1. Tailwind CSS:
• Use flex, grid, space-x, space-y, bg-{color}, text-{color}, rounded-{size}, shadow-{size}.
2. Alpine.js:
• Use x-data, x-model, @click, x-show, x-if.
3. Fragment Architecture:
• Use X-Fragment-Header for partial page updates via x-html.

Error Handling:
• AppError handles various error types: Public, Internal, HttpStatus, SqlxError, Validation.
• Log errors with tracing and return appropriate HTTP status codes.

Database Operations:
• Use SQLx for async DB operations (e.g., query!, query_as!).
• Paginate with LIMIT and OFFSET.

Password Handling:
• Use bcrypt/Argon2 for password hashing.

Input Validation:
• Use validator for validating and sanitizing inputs.

Diesel ORM Guidelines:
1. Database Connection Setup:
{%- if db_type == "postgres" %}
• PostgreSQL:
- URL format: postgres://user:password@host:port/dbname
- Enable features: diesel/postgres
- Types: Timestamp, Uuid, Json/Jsonb support
{%- endif %}

{%- if db_type == "mysql" %}
• MySQL:
- URL format: mysql://user:password@host/dbname
- Enable features: diesel/mysql
- Types: DateTime for timestamps
{%- endif %}

{%- if db_type == "sqlite" %}
• SQLite:
- URL format: file:path/to/db.sqlite
- Enable features: diesel/sqlite
- Types: INTEGER for auto-increment
{%- endif %}

2. Schema Definition:
```rust
diesel::table! {
users (id) {
id -> Text,
username -> Text,
password -> Text,
}
}
```

3. Model Definition:
```rust
#[derive(Queryable, Selectable, Insertable)]
#[diesel(table_name = users)]
pub struct User {
pub id: String,
pub username: String,
pub password: String,
}
```

4. Common Operations:
• Select:
```rust
users::table.filter(users::id.eq(user_id)).first::<User>(conn)?
```
• Insert:
```rust
diesel::insert_into(users::table).values(&user).execute(conn)?
```
• Update:
```rust
diesel::update(users::table)
.filter(users::id.eq(user_id))
.set(users::username.eq(new_username))
.execute(conn)?
```
• Delete:
```rust
diesel::delete(users::table).filter(users::id.eq(user_id)).execute(conn)?
```

5. Relationships:
• belongs_to:
```rust
#[derive(Associations)]
#[belongs_to(User)]
pub struct Post { ... }
```
• has_many: Use inner joins
```rust
users::table.inner_join(posts::table)
```

6. Migrations:
• Create: diesel migration generate create_users
• Run: diesel migration run
• Revert: diesel migration revert

7. Database-Specific Features:
{%- if db_type == "postgres" %}
• PostgreSQL:
- JSONB operations
- Full-text search
- Array types
{%- endif %}
{%- if db_type == "mysql" %}
• MySQL:
- ON DUPLICATE KEY
- REPLACE INTO
{%- endif %}
{%- if db_type == "sqlite" %}
• SQLite:
- Simple file-based
- WAL mode for concurrency
{%- endif %}

8. Best Practices:
• Use connection pools (r2d2)
• Implement From/Into for models
• Use transactions for atomic operations
• Use derive macros for boilerplate
Loading

0 comments on commit 41f049e

Please sign in to comment.