Skip to content

Commit

Permalink
add template
Browse files Browse the repository at this point in the history
  • Loading branch information
fankaiLiu committed Oct 24, 2023
1 parent 78a1c18 commit 8eca2b5
Show file tree
Hide file tree
Showing 5 changed files with 170 additions and 1 deletion.
18 changes: 18 additions & 0 deletions locales/code_comment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -526,3 +526,21 @@ create_success_sea_orm__mysql_or_pgsql_fist_use:
th: -- ขอโทษที่ทำให้คุณสับสน ข้างล่างนี้คือคำอธิบายในภาษาไทย:คุณต้องเปลี่ยนสตริงการเชื่อมต่อฐานข้อมูลใน .env และ config/config.toml ก่อนตรวจสอบว่าฐานข้อมูลมีอยู่จริง จากนั้นรันการย้ายของ sea-orm เพื่อคืนค่าฐานข้อมูล และรัน SQL ด้านล่างในฐานข้อมูลเพื่อเพิ่มข้อมูลเริ่มต้นหลังจากรัน คุณสามารถใช้ชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123 เพื่อเข้าถึง /loginสำหรับฟังก์ชันเพิ่มเติมของ sea-orm-cli โปรดดูที่ /migration/README.md.
el: -- Παρακαλώ αλλάξτε πρώτα τη συμβολοσειρά σύνδεσης στη βάση δεδομένων στο .env και config/config.toml \n -- Βεβαιωθείτε ότι η βάση δεδομένων υπάρχει, στη συνέχεια εκτελέστε τη μετεγκατάσταση sea-orm για να επαναφέρετε τη βάση δεδομένων, και εκτελέστε το παρακάτω SQL στη βάση δεδομένων για να προσθέσετε τα προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να χρησιμοποιήσετε το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό:123 για να έχετε πρόσβαση στο /login. \n -- Για περισσότερες λειτουργίες του sea-orm-cli, παρακαλώ δείτε το /migration/README.md.
da: -- Ændre først forbindelsesstrengen til databasen i .env og config/config.toml \n -- Sørg for, at databasen eksisterer, kør derefter sea-orm-migrationen for at gendanne databasen, og kør den følgende SQL i databasen for at tilføje standarddataene. \n -- Efter kørsel, kan du bruge standard brugernavnet:zhangsan og adgangskoden:123 for at få adgang til /login. \n -- For mere funktionalitet fra sea-orm-cli, se venligst /migration/README.md.
create_success_diesel__mysql_or_pgsql_fist_use:
en: -- Please modify the database connection string in .env and config/config.toml first \n -- Make sure the database exists, then run diesel migration run to restore the database, and run the following SQL in the database to add the default data. \n -- After running, you can use the default username:zhangsan and password:123 to access /login. \n -- For more diesel-cli functionality, please check /migration/README.md.
zh_CN: -- 请先修改.env和config/config.toml中的数据库连接字符串 \n -- 确保数据库存在,然后运行diesel migration run还原数据库, 在数据库中运以下SQL以添加默认数据。 \n -- 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login。 \n -- 更多diesel-cli功能,请查看/migration/README.md。
zh_TW: -- 請先修改.env和config/config.toml中的數據庫連接字符串 \n -- 確保數據庫存在,然後運行diesel migration run還原數據庫, 在數據庫中運行以下SQL以添加默認數據。 \n -- 運行後,您可以使用默認用戶名:zhangsan和密碼:123訪問/login。 \n -- 更多diesel-cli功能,請查看/migration/README.md。
fr: -- Veuillez d'abord modifier la chaîne de connexion à la base de données dans .env et config/config.toml \n -- Assurez-vous que la base de données existe, puis exécutez diesel migration run pour restaurer la base de données, et exécutez le SQL suivant dans la base de données pour ajouter les données par défaut. \n -- Après exécution, vous pouvez utiliser le nom d'utilisateur par défaut:zhangsan et le mot de passe:123 pour accéder à /login. \n -- Pour plus de fonctionnalités de diesel-cli, veuillez consulter /migration/README.md.
ja: -- 最初に.envとconfig/config.tomlのデータ /migration/README.md \n -- ベース接続文字列を変更してください \n -- データベースが存在することを確認し、次にdiesel migration runを実行してデータベースを復元し、デフォルトのデータを追加するためにデータベースで以下のSQLを実行してください。 \n -- 実行後、デフォルトのユーザーネーム:zhangsanとパスワード:123を使用して/loginにアクセスできます。 \n -- その他のdiesel-cliの機能については、/migration/README.mdをご覧ください。
es: -- Por favor, modifique primero la cadena de conexión a la base de datos en .env y config/config.toml \n -- Asegúrese de que la base de datos exista, luego ejecute diesel migration run para restaurar la base de datos, y ejecute el siguiente SQL en la base de datos para agregar los datos predeterminados. \n -- Después de ejecutar, puede usar el nombre de usuario predeterminado:zhangsan y la contraseña:123 para acceder a /login. \n -- Para más funcionalidad de diesel-cli, por favor consulte /migration/README.md.
de: -- Bitte ändern Sie zuerst die Datenbankverbindungszeichenkette in .env und config/config.toml \n -- Stellen Sie sicher, dass die Datenbank existiert, führen Sie dann diesel migration run aus, um die Datenbank wiederherzustellen, und führen Sie das folgende SQL in der Datenbank aus, um die Standarddaten hinzuzufügen. \n -- Nach dem Ausführen können Sie den Standardbenutzernamen:zhangsan und das Passwort:123 verwenden, um auf /login zuzugreifen. \n -- Weitere Funktionen von diesel-cli finden Sie unter /migration/README.md.
ru: -- Пожалуйста, сначала измените строку подключения к базе данных в .env и config/config.toml \n -- Убедитесь, что база данных существует, затем запустите diesel migration run для восстановления базы данных и выполните следующий SQL в базе данных, чтобы добавить данные по умолчанию. \n -- После выполнения вы можете использовать имя пользователя по умолчанию:zhangsan и пароль:123 для доступа к /login. \n -- Для более подробной информации о функциях diesel-cli, пожалуйста, смотрите /migration/README.md.
it: -- Si prega di modificare prima la stringa di connessione al database in .env e config/config.toml \n -- Assicurarsi che il database esista, poi eseguire diesel migration run per ripristinare il database, e eseguire il seguente SQL nel database per aggiungere i dati predefiniti. \n -- Dopo l'esecuzione, è possibile utilizzare il nome utente predefinito:zhangsan e la password:123 per accedere a /login. \n -- Per ulteriori funzionalità di diesel-cli, si prega di consultare /migration/README.md.
pt: -- Por favor, modifique primeiro a string de conexão do banco de dados em .env e config/config.toml \n -- Certifique-se de que o banco de dados existe, em seguida, execute diesel migration run para restaurar o banco de dados, e execute oSQL seguinte no banco de dados para adicionar os dados padrão. \n -- Após a execução, você pode usar o nome de usuário padrão:zhangsan e a senha:123 para acessar /login. \n -- Para mais funcionalidades do diesel-cli, por favor, verifique /migration/README.md.
ko: -- 먼저 .env와 config/config.toml의 데이터베이스 연결 문자열을 수정해 주세요 \n -- 데이터베이스가 존재하는지 확인한 후 diesel migration run을 실행하여 데이터베이스를 복원하고, 데이터베이스에서 아래 SQL을 실행하여 기본 데이터를 추가합니다. \n -- 실행 후, 기본 사용자 이름:zhangsan과 비밀번호:123을 사용하여 /login에 접속할 수 있습니다. \n -- diesel-cli의 추가 기능은 /migration/README.md를 확인해 주세요.
no: -- Vennligst endre databaseforbindelsesstrengen i .env og config/config.toml først \n -- Forsikre deg om at databasen eksisterer, kjør deretter diesel migration run for å gjenopprette databasen, og kjør følgende SQL i databasen for å legge til standarddata. \n -- Etter kjøring, kan du bruke standard brukernavn:zhangsan og passord:123 for å få tilgang til /login. \n -- For mer diesel-cli-funksjonalitet, vennligst sjekk /migration/README.md.
is: -- Vinsamlegast breyttu gagnagrunnstengistrengjuna í .env og config/config.toml fyrst \n -- Gakktu úr skugga um að gagnagrunnurinn sé til, keyrðu svo diesel migration run til að endurheimta gagnagrunninn og keyrðu eftirfarandi SQL í gagnagrunninum til að bæta við sjálfgefnum gögnum. \n -- Eftir keyrslu, getur þú notað sjálfgefið notendanafn:zhangsan og lykilorð:123 til að fá aðgang að /login. \n -- Fyrir meira um diesel-cli virkni, vinsamlegast athugaðu /migration/README.md.
uk: -- Будь ласка, спочатку змініть рядок підключення до бази даних в .env та config/config.toml \n -- Переконайтеся, що база даних існує, потім запустіть diesel migration run для відновлення бази даних та виконайте наступний SQL в базі даних, щоб додати дані за замовчуванням. \n -- Після запуску ви можете використовувати ім'я користувача за замовчуванням:zhangsan та пароль:123 для доступу до /login. \n -- Для отримання додаткових функцій diesel-cli, будь ласка, перевірте /migration/README.md.
th: -- ขอโทษที่ทำให้คุณสับสน ข้างล่างนี้คือคำอธิบายในภาษาไทย:คุณต้องเปลี่ยนสตริงการเชื่อมต่อฐานข้อมูลใน .env และ config/config.toml ก่อนตรวจสอบว่าฐานข้อมูลมีอยู่จริง จากนั้นรันการย้ายของ diesel เพื่อคืนค่าฐานข้อมูล และรัน SQL ด้านล่างในฐานข้อมูลเพื่อเพิ่มข้อมูลเริ่มต้นหลังจากรัน คุณสามารถใช้ชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123 เพื่อเข้าถึง /loginสำหรับฟังก์ชันเพิ่มเติมของ diesel-cli โปรดดูที่ /migration/README.md.
el: -- Παρακαλώ αλλάξτε πρώτα τη συμβολοσειρά σύνδεσης στη βάση δεδομένων στο .env και config/config.toml \n -- Βεβαιωθείτε ότι η βάση δεδομένων υπάρχει, στη συνέχεια εκτελέστε τη μετεγκατάσταση diesel για να επαναφέρετε τη βάση δεδομένων, και εκτελέστε το παρακάτω SQL στη βάση δεδομένων για να προσθέσετε τα προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να χρησιμοποιήσετε το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό:123 για να έχετε πρόσβαση στο /login. \n -- Για περισσότερες λειτουργίες του diesel-cli, παρακαλώ δείτε το /migration/README.md.
da: -- Ændre først forbindelsesstrengen til databasen i .env og config/config.toml \n -- Sørg for, at databasen eksisterer, kør derefter diesel migration run for at gendanne databasen, og kør den følgende SQL i databasen for at tilføje standarddataene. \n -- Efter kørsel, kan du bruge standard brugernavnet:zhangsan og adgangskoden:123 for at få adgang til /login. \n -- For mere funktionalitet fra diesel-cli, se venligst /migration/README.md.
3 changes: 3 additions & 0 deletions src/template/data/init_sql_sql.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
{{create_success_sea_orm__mysql_or_pgsql_install_sea_orm}}
{{create_success_sea_orm__mysql_or_pgsql_fist_use}}
{{/if}}
{{#if is_diesel}}
{{create_success_diesel__mysql_or_pgsql_fist_use}}
{{/if}}
BEGIN;
INSERT INTO "users" ("id", "username", "password") VALUES ('cdd0e080-5bb1-4442-b6f7-2ba60dbd0555', 'zhangsan', '$argon2id$v=19$m=19456,t=2,p=1$rcosL5pOPdA2c7i4ZuLA4Q$s0JGh78UzMmu1qZMpVUA3b8kWYLXcZhw7uBfwhYDJ4A');
COMMIT;
143 changes: 143 additions & 0 deletions src/template/diesel_migrations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
Diesel CLI
==========

Diesel CLI is a tool that aids in managing your database schema. Migrations are
bi-directional changes to your database that get applied sequentially.

Installation
---------------

The diesel cli, by default, requires [`openssl`][openssl], [`libpq`][postgres],
[`sqlite`][sqlite], and [`mysql`][mysql]. Once these dependencies are installed,
you can run `cargo install diesel_cli`.

> Note: Make sure that both the `bin` and `lib` directories for
> postgres are added to your PATH
To install the cli without these dependencies, omit the unneeded dependencies from
the following command:

```sh
cargo install diesel_cli --no-default-features --features "postgres sqlite mysql"
```

[openssl]: https://www.openssl.org/source
[postgres]: https://www.postgresql.org/download/
[sqlite]: http://www.sqlitetutorial.net/download-install-sqlite/
[mysql]: https://dev.mysql.com/doc/refman/5.7/en/installing.html

If you are using a system without an easy way to install sqlite (for example Windows),
you can use a bundled version instead:

```shell
cargo install diesel_cli --no-default-features --features "sqlite-bundled"
```

Getting Started
---------------

```sh
cargo install diesel_cli
diesel setup --database-url='postgres://localhost/my_db'
diesel migration generate create_users_table
```

You'll see that a `migrations/` directory was generated for you (by the setup
command), and two sql files were generated,
`migrations/{current_timestamp}_create_users_table/up.sql` and
`migrations/{current_timestamp}_create_users_table/down.sql`. You should edit
these files to show how to update your schema, and how to undo that change.

```sql
-- up.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
favorite_color VARCHAR
);
```

```sql
-- down.sql
DROP TABLE USERS;
```

You can then run your new migration by running `diesel migration run`. Your
DATABASE_URL must be set in order to run this command, and there are several
ways that you can set it:

* Set it as an environment variable manually
* Set it as an environment variable using [dotenv](https://github.com/dotenv-rs/dotenv#examples)
* Pass it directly by adding the `--database-url` flag

As an alternative to running migrations with the CLI, you can call
[`diesel::migrations::run_pending_migrations`][pending-migrations] from
`build.rs`.

Diesel will automatically keep track of which migrations have already been run,
ensuring that they're never run twice.

Commands
--------

## `diesel setup`
Searches for a `migrations/` directory, and if it can't find one, creates one
in the same directory as the first `Cargo.toml` it finds. It then tries to
connect to the provided DATABASE_URL, and will create the given database if it
cannot connect to it. Finally it will create diesel's internal table for
tracking which migrations have been run, and run any existing migrations if the
internal table did not previously exist.

## `diesel database`
#### `database setup`
Tries to connect to the provided DATABASE_URL, and will create the given
database if it cannot connect to it. It then creates diesel's internal
migrations tracking table if it needs to be created, and runs any pending
migrations if it created the internal table.

#### `database reset`
Drops the database specified in your DATABASE_URL if it can, and then runs
`diesel database setup`.

## `diesel migration`
#### `migration generate`
Takes the name of your migration as an argument, and will create a migration
directory with `migrations/` in the format of
`migrations/{current_timestamp}_{migration_name}`. It will also generate
`up.sql` and `down.sql` files, for running your migration up and down
respectively.

#### `migration run`
Runs all pending migrations, as determined by diesel's internal schema table.

#### `migration revert`
Runs the `down.sql` for the most recent migration.

#### `migration redo`
Runs the `down.sql` and then the `up.sql` for the most recent migration.

## `diesel print-schema`
Prints table definitions for database schema.

[pending-migrations]: https://docs.rs/diesel_migrations/*/diesel_migrations/fn.run_pending_migrations.html
[rust-dotenv]: https://github.com/dotenv-rs/dotenv#examples


Bash completion
---------------

Diesel can generate a bash completion script for itself:

#### linux

```sh
$ diesel completions bash > /etc/bash_completion.d/diesel
```


#### os x (homebrew)

```sh
$ brew install bash-completion # you may already have this installed
$ diesel completions bash > $(brew --prefix)/etc/bash_completion.d/diesel
```
1 change: 0 additions & 1 deletion src/template/src/models/user.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use diesel::prelude::*;

#[derive(Queryable, Selectable, Insertable)]
#[diesel(table_name = crate::schema::users)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct UserModel {
pub id: String,
pub username: String,
Expand Down
6 changes: 6 additions & 0 deletions src/utils/create_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ fn write_project_file(
"create_success_sea_orm__mysql_or_pgsql_install_sea_orm":t!("create_success_sea_orm__mysql_or_pgsql_install_sea_orm"),
"create_success_mysql_or_pgsql_fist_use":t!("create_success_mysql_or_pgsql_fist_use").replace(r"\n", "\n"),
"create_success_sea_orm__mysql_or_pgsql_fist_use":t!("create_success_sea_orm__mysql_or_pgsql_fist_use").replace(r"\n", "\n"),
"create_success_diesel__mysql_or_pgsql_fist_use":t!("create_success_diesel__mysql_or_pgsql_fist_use").replace(r"\n", "\n"),
});
if need_db_conn {
// Add sqlx dependencies
Expand Down Expand Up @@ -549,6 +550,11 @@ fn write_project_file(
let gitkeep_bytes: [u8; 0] = [];
let mut gitkeep_file = File::create(migrations_path.join(".keep"))?;
gitkeep_file.write_all(&gitkeep_bytes)?;
//migrations/README.md
let migration_readme_bytes = include_bytes!("../template/diesel_migrations/README.md");
let mut migration_readme_file = File::create(migrations_path.join("README.md"))?;
migration_readme_file.write_all(migration_readme_bytes)?;

//.env
let env_template = include_str!("../template/.env.hbs");
let env_rendered = handlebars.render_template(env_template, &data)?;
Expand Down

0 comments on commit 8eca2b5

Please sign in to comment.