diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..a8b5cec --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2019-present, The `salvo` Developers + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..204ae2a --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019-present, The `salvo` Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/locales/code_comment.yml b/locales/code_comment.yml index de73d95..b3626ba 100644 --- a/locales/code_comment.yml +++ b/locales/code_comment.yml @@ -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. diff --git a/src/template/.env.hbs b/src/template/.env.hbs index 78fd725..51b5df6 100644 --- a/src/template/.env.hbs +++ b/src/template/.env.hbs @@ -1,3 +1,4 @@ +{{#if is_sea_orm_or_sqlx}} {{#if is_postgres}} DATABASE_URL=postgresql://liufankai:1@localhost/salvo_demo {{/if}} @@ -6,4 +7,16 @@ DATABASE_URL="sqlite:data/demo.db" {{/if}} {{#if is_mysql}} DATABASE_URL="mysql://root:981109@localhost/salvo_demo" +{{/if}} +{{/if}} +{{#if is_diesel}} +{{#if is_postgres}} +DATABASE_URL=postgres://liufankai:1@localhost/diesel_example +{{/if}} +{{#if is_sqlite}} +DATABASE_URL="file:data/test.db" +{{/if}} +{{#if is_mysql}} +DATABASE_URL="mysql://root:123@127.0.0.1:3306/diesel_example" +{{/if}} {{/if}} \ No newline at end of file diff --git a/src/template/config/config.hbs b/src/template/config/config.hbs index fe495b9..4dc65a6 100644 --- a/src/template/config/config.hbs +++ b/src/template/config/config.hbs @@ -4,16 +4,28 @@ address = "0.0.0.0:5800" ssl = false {{#if need_db_conn}} [database] -{{#if is_sqlite}} -database_url= "sqlite:data/demo.db" -{{/if}} +{{#if is_sea_orm_or_sqlx}} {{#if is_postgres}} -database_url="postgresql://liufankai:1@localhost/salvo_demo" +database_url=postgresql://liufankai:1@localhost/salvo_demo +{{/if}} +{{#if is_sqlite}} +database_url="sqlite:data/demo.db" {{/if}} {{#if is_mysql}} database_url="mysql://root:981109@localhost/salvo_demo" {{/if}} {{/if}} +{{#if is_diesel}} +{{#if is_postgres}} +database_url=postgres://liufankai:1@localhost/diesel_example +{{/if}} +{{#if is_sqlite}} +database_url="file:data/test.db" +{{/if}} +{{#if is_mysql}} +database_url="mysql://root:123@127.0.0.1:3306/diesel_example" +{{/if}} +{{/if}}{{/if}} [jwt] jwt_secret = "secret" jwt_exp = 6000 diff --git a/src/template/data/diesel_test.db b/src/template/data/diesel_test.db new file mode 100644 index 0000000..182776a Binary files /dev/null and b/src/template/data/diesel_test.db differ diff --git a/src/template/data/init_sql_sql.hbs b/src/template/data/init_sql_sql.hbs index 0032d68..6fb5894 100644 --- a/src/template/data/init_sql_sql.hbs +++ b/src/template/data/init_sql_sql.hbs @@ -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; diff --git a/src/template/diesel.hbs b/src/template/diesel.hbs new file mode 100644 index 0000000..c028f4a --- /dev/null +++ b/src/template/diesel.hbs @@ -0,0 +1,9 @@ +# For documentation on how to configure this file, +# see https://diesel.rs/guides/configuring-diesel-cli + +[print_schema] +file = "src/schema.rs" +custom_type_derives = ["diesel::query_builder::QueryId"] + +[migrations_directory] +dir = "migrations" diff --git a/src/template/diesel_migrations/.keep b/src/template/diesel_migrations/.keep new file mode 100644 index 0000000..e69de29 diff --git a/src/template/diesel_migrations/2023-10-21-084227_create_users_table/down.sql b/src/template/diesel_migrations/2023-10-21-084227_create_users_table/down.sql new file mode 100644 index 0000000..42ebb17 --- /dev/null +++ b/src/template/diesel_migrations/2023-10-21-084227_create_users_table/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP TABLE IF EXISTS users; \ No newline at end of file diff --git a/src/template/diesel_migrations/2023-10-21-084227_create_users_table/up.sql b/src/template/diesel_migrations/2023-10-21-084227_create_users_table/up.sql new file mode 100644 index 0000000..e84acad --- /dev/null +++ b/src/template/diesel_migrations/2023-10-21-084227_create_users_table/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +CREATE TABLE IF NOT EXISTS users ( + id VARCHAR(255) PRIMARY KEY NOT NULL, + username VARCHAR(255) NOT NULL UNIQUE, + password VARCHAR(511) NOT NULL +); \ No newline at end of file diff --git a/src/template/diesel_migrations/README.md b/src/template/diesel_migrations/README.md new file mode 100644 index 0000000..53b662e --- /dev/null +++ b/src/template/diesel_migrations/README.md @@ -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 +``` \ No newline at end of file diff --git a/src/template/src/app_error.hbs b/src/template/src/app_error.hbs index a79e3c5..87e318e 100644 --- a/src/template/src/app_error.hbs +++ b/src/template/src/app_error.hbs @@ -31,6 +31,10 @@ pub enum AppError { #[error("sea_orm::DbErr:Error:`{0}`")] DbErr(#[from] sea_orm::DbErr), {{/if}} + {{#if is_diesel}} + #[error("diesel::result::Error:`{0}`")] + DieselErr(#[from] diesel::result::Error), + {{/if}} } pub type AppResult = Result; diff --git a/src/template/src/db.hbs b/src/template/src/db.hbs index a1c5596..a76085e 100644 --- a/src/template/src/db.hbs +++ b/src/template/src/db.hbs @@ -1,3 +1,4 @@ +use crate::config::CFG; {{#if is_sqlx}} {{#if is_mysql}} use sqlx::MySqlPool; @@ -13,9 +14,31 @@ use sqlx::SqlitePool; use std::time::Duration; use sea_orm::{entity::prelude::DatabaseConnection, ConnectOptions, Database}; {{/if}} +{{#if is_sea_orm_or_sqlx}} use tokio::sync::OnceCell; - -use crate::config::CFG; +{{/if}} +{{#if is_diesel}} +use diesel::prelude::*; +{{#if is_sqlite}} +pub fn establish_connection() -> SqliteConnection { + let conn = SqliteConnection::establish(&CFG.database.database_url) + .unwrap_or_else(|_| panic!("Error connecting to {}", &CFG.database.database_url)); + conn +} +{{/if}} +{{#if is_mysql}} +pub fn establish_connection() -> MysqlConnection { + MysqlConnection::establish(&CFG.database.database_url) + .unwrap_or_else(|_| panic!("Error connecting to {}", &CFG.database.database_url)) +} +{{/if}} +{{#if is_postgres}} +pub fn establish_connection() -> PgConnection { + PgConnection::establish(&CFG.database.database_url) + .unwrap_or_else(|_| panic!("Error connecting to {}", &CFG.database.database_url)) +} +{{/if}} +{{/if}} {{#if is_sqlx}} {{#if is_sqlite}} pub static DB: OnceCell = OnceCell::const_new(); diff --git a/src/template/src/main_template.hbs b/src/template/src/main_template.hbs index fa997b0..a74eacc 100644 --- a/src/template/src/main_template.hbs +++ b/src/template/src/main_template.hbs @@ -1,4 +1,4 @@ -{{#if need_db_conn}} +{{#if is_sea_orm_or_sqlx}} use crate::db::init_db_conn; {{/if}} use crate::middleware::handle_404::handle_404; @@ -19,9 +19,15 @@ mod config; mod db; mod dtos; mod services; -mod entities; mod utils; {{/if}} +{{#if is_sea_orm_or_sqlx}} +mod entities; +{{/if}} +{{#if is_diesel}} +mod models; +mod schema; +{{/if}} mod middleware; mod routers; @@ -29,7 +35,7 @@ mod routers; async fn main() { //{{main_log_message}} init_log(); - {{#if need_db_conn}} + {{#if is_sea_orm_or_sqlx}} init_db_conn().await; {{/if}} let (tx, rx) = oneshot::channel(); diff --git a/src/template/src/models/mod.hbs b/src/template/src/models/mod.hbs new file mode 100644 index 0000000..22d12a3 --- /dev/null +++ b/src/template/src/models/mod.hbs @@ -0,0 +1 @@ +pub mod user; diff --git a/src/template/src/models/user.hbs b/src/template/src/models/user.hbs new file mode 100644 index 0000000..938fed8 --- /dev/null +++ b/src/template/src/models/user.hbs @@ -0,0 +1,9 @@ +use diesel::prelude::*; + +#[derive(Queryable, Selectable, Insertable)] +#[diesel(table_name = crate::schema::users)] +pub struct UserModel { + pub id: String, + pub username: String, + pub password: String, +} diff --git a/src/template/src/schema.hbs b/src/template/src/schema.hbs new file mode 100644 index 0000000..c6ac61d --- /dev/null +++ b/src/template/src/schema.hbs @@ -0,0 +1,9 @@ +// @generated automatically by Diesel CLI. + +diesel::table! { + users (id) { + id -> Text, + username -> Text, + password -> Text, + } +} diff --git a/src/template/src/services/user.hbs b/src/template/src/services/user.hbs index c8f9e22..64b6796 100644 --- a/src/template/src/services/user.hbs +++ b/src/template/src/services/user.hbs @@ -1,3 +1,4 @@ +{{#if is_sea_orm_or_sqlx}} {{#if is_sqlx}} use crate::{ app_error::AppResult, @@ -214,4 +215,139 @@ pub async fn users() -> AppResult> { .collect::>(); Ok(res) } +{{/if}} +{{/if}} +{{#if is_diesel}} +use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl, SelectableHelper}; +use uuid::Uuid; + +use crate::schema::users::dsl::users as diesel_users; +use crate::{ + app_error::AppResult, + db::establish_connection, + dtos::user::{ + UserAddRequest, UserLoginRequest, UserLoginResponse, UserResponse, UserUpdateRequest, + }, + middleware::jwt::get_token, + models::user::UserModel, + utils::rand_utils, +}; +use diesel::OptionalExtension; + +pub async fn add_user(req: UserAddRequest) -> AppResult { + use crate::schema::users; + let mut db = establish_connection(); + let model = UserModel { + id: Uuid::new_v4().to_string(), + username: req.username.clone(), + password: rand_utils::hash_password(req.password).await?, + }; + + diesel::insert_into(users::table) + .values(&model) + .execute(&mut db) + .expect("Error saving new user"); + + let user: UserModel = users::table + .filter(users::id.eq(&model.id)) + .first(&mut db) + .expect("Error loading user"); + + Ok(UserResponse { + id: user.id, + username: user.username, + }) +} + +pub async fn login(req: UserLoginRequest) -> AppResult { + use crate::schema::users::dsl::*; + let mut connection = establish_connection(); + + let result = diesel_users + .filter(username.eq(&req.username)) + .select((id, username, password)) + .first::<(String, String, String)>(&mut connection) + .optional()?; + + match result { + None => Err(anyhow::anyhow!("{{user_does_not_exist}}").into()), + Some((uid, uname, hashed_pwd)) => { + if rand_utils::verify_password(req.password, hashed_pwd) + .await + .is_err() + { + return Err(anyhow::anyhow!("{{incorrect_password}}").into()); + } + + let (token, exp) = get_token(uname.clone(), uid.clone())?; + let res = UserLoginResponse { + id: uid, + username: uname, + token, + exp, + }; + Ok(res) + } + } +} + +pub async fn update_user(req: UserUpdateRequest) -> AppResult { + use crate::schema::users::dsl::*; + {{#if is_mysql}} + let mut db = establish_connection(); + diesel::update(users.find(req.id.clone())) + .set(( + username.eq(req.username), + password.eq(rand_utils::hash_password(req.password).await?), + )) + .execute(&mut db)?; + + let user = users + .find(req.id) + .select(UserModel::as_select()) + .first(&mut db)?; + + Ok(UserResponse { + id: user.id, + username: user.username, + }) + {{else}} + let mut db = establish_connection(); + let user = diesel::update(diesel_users.find(req.id)) + .set(( + username.eq(req.username), + password.eq(rand_utils::hash_password(req.password).await?), + )) + .returning(UserModel::as_returning()) + .get_result(&mut db)?; + Ok(UserResponse { + id: user.id, + username: user.username, + }) + {{/if}} +} + +pub async fn delete_user(req: String) -> AppResult<()> { + use crate::schema::users::id; + let mut db = establish_connection(); + diesel::delete(diesel_users.filter(id.eq(req))) + .execute(&mut db) + .expect("Error deleting posts"); + Ok(()) +} + +pub async fn users() -> AppResult> { + let mut db = establish_connection(); + let results = diesel_users.select(UserModel::as_select()).load(&mut db)?; + + let res = results + .into_iter() + .map(|user| UserResponse { + id: user.id, + username: user.username, + }) + .collect::>(); + + Ok(res) +} {{/if}} \ No newline at end of file diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index ef2ee71..22e00d0 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -38,7 +38,10 @@ pub fn create_project(project: Project) -> Result<()> { init_git(project_path)?; success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); - if config.db_conn_type == DbConnectionType::Sqlx||config.db_conn_type == DbConnectionType::SeaOrm{ + if config.db_conn_type == DbConnectionType::Sqlx + || config.db_conn_type == DbConnectionType::SeaOrm + || config.db_conn_type == DbConnectionType::Diesel + { if config.db_conn_type == DbConnectionType::Sqlx { success( t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), @@ -46,7 +49,8 @@ pub fn create_project(project: Project) -> Result<()> { } if config.db_conn_type == DbConnectionType::SeaOrm { success( - t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n"), + t!("create_success_sea_orm", project_name = project_name) + .replace(r"\n", "\n"), ); } if config.db_type == DbType::Sqlite { @@ -72,9 +76,11 @@ fn write_project_file( let need_db_conn = user_selected.db_conn_type != DbConnectionType::Nothing; let is_sqlx = user_selected.db_conn_type == DbConnectionType::Sqlx; let is_sea_orm = user_selected.db_conn_type == DbConnectionType::SeaOrm; + let is_diesel = user_selected.db_conn_type == DbConnectionType::Diesel; let is_mysql = user_selected.db_type == DbType::Mysql; let is_postgres = user_selected.db_type == DbType::Postgres; let is_sqlite = user_selected.db_type == DbType::Sqlite; + let is_sea_orm_or_sqlx = is_sea_orm || is_sqlx; let mut data = json!({ "project_name": project.project_name, "dependencies": { @@ -103,6 +109,8 @@ fn write_project_file( "is_postgres":is_postgres, "is_sqlite":is_sqlite, "is_sea_orm":is_sea_orm, + "is_sea_orm_or_sqlx":is_sea_orm_or_sqlx, + "is_diesel":is_diesel, "main_log_message":t!("main_log_message"), "config_error_no_exits":t!("config_error_no_exits"), "config_error_read":t!("config_error_read"), @@ -125,6 +133,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 @@ -167,6 +176,25 @@ fn write_project_file( "features": ["runtime-tokio-native-tls","sqlx-sqlite"] }); } + } else if is_diesel { + if is_mysql { + dependencies["diesel"] = json!({ + "version": "2.1.0", + "features": ["mysql"] + }); + } + if is_postgres { + dependencies["diesel"] = json!({ + "version": "2.1.0", + "features": ["postgres"] + }); + } + if is_sqlite { + dependencies["diesel"] = json!({ + "version": "2.1.0", + "features": ["sqlite","returning_clauses_for_sqlite_3_35"] + }); + } } //add uuid dependency dependencies["uuid"] = json!({ @@ -368,113 +396,192 @@ fn write_project_file( let dtos_user_rendered = handlebars.render_template(dtos_user_template, &data)?; let mut dtos_user_file = File::create(dtos_path.join("user.rs"))?; dtos_user_file.write_all(dtos_user_rendered.as_bytes())?; + if is_sea_orm || is_sqlx { + //src/entities + let entities_path = src_path.join("entities"); + std::fs::create_dir_all(&entities_path)?; + //src/entities/mod.rs + let entities_mod_template = include_str!("../template/src/entities/mod.hbs"); + let entities_mod_rendered = handlebars.render_template(entities_mod_template, &data)?; + let mut entities_mod_file = File::create(entities_path.join("mod.rs"))?; + entities_mod_file.write_all(entities_mod_rendered.as_bytes())?; - //src/entities - let entities_path = src_path.join("entities"); - std::fs::create_dir_all(&entities_path)?; - //src/entities/mod.rs - let entities_mod_template = include_str!("../template/src/entities/mod.hbs"); - let entities_mod_rendered = handlebars.render_template(entities_mod_template, &data)?; - let mut entities_mod_file = File::create(entities_path.join("mod.rs"))?; - entities_mod_file.write_all(entities_mod_rendered.as_bytes())?; - - //src/entities/user.rs - let entities_user_template = include_str!("../template/src/entities/user.hbs"); - let entities_user_rendered = handlebars.render_template(entities_user_template, &data)?; - let mut entities_user_file = File::create(entities_path.join("user.rs"))?; - entities_user_file.write_all(entities_user_rendered.as_bytes())?; - if is_sea_orm { - //src/entities/prelude.rs - let entities_prelude_template = include_str!("../template/src/entities/prelude.hbs"); - let entities_prelude_rendered = - handlebars.render_template(entities_prelude_template, &data)?; - let mut entities_prelude_file = File::create(entities_path.join("prelude.rs"))?; - entities_prelude_file.write_all(entities_prelude_rendered.as_bytes())?; - } - if is_sqlx { - //data - let data_path = project_path.join("data"); - std::fs::create_dir_all(&data_path)?; - if is_sqlite { - //data/demo.db - let demo_db_bytes = include_bytes!("../template/data/demo.db"); - let mut demo_db_file = File::create(data_path.join("demo.db"))?; - demo_db_file.write_all(demo_db_bytes)?; - } else { - //data/init_sql.sql - let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); - let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; - let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; - init_sql_file.write_all(init_sql_rendered.as_bytes())?; + //src/entities/user.rs + let entities_user_template = include_str!("../template/src/entities/user.hbs"); + let entities_user_rendered = + handlebars.render_template(entities_user_template, &data)?; + let mut entities_user_file = File::create(entities_path.join("user.rs"))?; + entities_user_file.write_all(entities_user_rendered.as_bytes())?; + if is_sea_orm { + //src/entities/prelude.rs + let entities_prelude_template = + include_str!("../template/src/entities/prelude.hbs"); + let entities_prelude_rendered = + handlebars.render_template(entities_prelude_template, &data)?; + let mut entities_prelude_file = File::create(entities_path.join("prelude.rs"))?; + entities_prelude_file.write_all(entities_prelude_rendered.as_bytes())?; } + if is_sqlx { + //data + let data_path = project_path.join("data"); + std::fs::create_dir_all(&data_path)?; + if is_sqlite { + //data/demo.db + let demo_db_bytes = include_bytes!("../template/data/demo.db"); + let mut demo_db_file = File::create(data_path.join("demo.db"))?; + demo_db_file.write_all(demo_db_bytes)?; + } else { + //data/init_sql.sql + let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); + let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; + let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; + init_sql_file.write_all(init_sql_rendered.as_bytes())?; + } + //migrations + let migrations_path: std::path::PathBuf = project_path.join("migrations"); + std::fs::create_dir_all(&migrations_path)?; + //migrations/2021-10-20-000000_create_users_table/up.sql + let up_sql_bytes = + include_bytes!("../template/migrations/20231001143156_users.sql"); + let mut up_sql_file = + File::create(migrations_path.join("20231001143156_users.sql"))?; + up_sql_file.write_all(up_sql_bytes)?; + //.env + let env_template = include_str!("../template/.env.hbs"); + let env_rendered = handlebars.render_template(env_template, &data)?; + let mut env_file = File::create(project_path.join(".env"))?; + env_file.write_all(env_rendered.as_bytes())?; + } + if is_sea_orm { + //migration + let migration_path = project_path.join("migration"); + std::fs::create_dir_all(&migration_path)?; + //migration/src + let migration_src_path = migration_path.join("src"); + std::fs::create_dir_all(&migration_src_path)?; + //migration/src/main.rs + let migration_main_byetes = include_bytes!("../template/migration/src/main.rs"); + let mut migration_main_file = File::create(migration_src_path.join("main.rs"))?; + migration_main_file.write_all(migration_main_byetes)?; + //migration/src/lib.rs + let migration_lib_byetes = include_bytes!("../template/migration/src/lib.rs"); + let mut migration_lib_file = File::create(migration_src_path.join("lib.rs"))?; + migration_lib_file.write_all(migration_lib_byetes)?; + //migration/src/m20220101_000001_create_table.rs + let migration_create_table_byetes = + include_bytes!("../template/migration/src/m20220101_000001_create_table.rs"); + let mut migration_create_table_file = + File::create(migration_src_path.join("m20220101_000001_create_table.rs"))?; + migration_create_table_file.write_all(migration_create_table_byetes)?; + //migration/Cargo.toml + let migration_cargo_template = include_str!("../template/migration/Cargo.toml.hbs"); + let migration_cargo_rendered = + handlebars.render_template(migration_cargo_template, &data)?; + let mut migration_cargo_file = File::create(migration_path.join("Cargo.toml"))?; + migration_cargo_file.write_all(migration_cargo_rendered.as_bytes())?; + //migration/README.md + let migration_readme_bytes = include_bytes!("../template/migration/README.md"); + let mut migration_readme_file = File::create(migration_path.join("README.md"))?; + migration_readme_file.write_all(migration_readme_bytes)?; + + if is_sqlite { + //data + let data_path = project_path.join("data"); + std::fs::create_dir_all(&data_path)?; + //data/demo.db + let demo_db_bytes = include_bytes!("../template/data/demo_sea_orm.db"); + let mut demo_db_file = File::create(data_path.join("demo.db"))?; + demo_db_file.write_all(demo_db_bytes)?; + } else { + let data_path = project_path.join("data"); + std::fs::create_dir_all(&data_path)?; + //data/init_sql.sql + let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); + let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; + let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; + init_sql_file.write_all(init_sql_rendered.as_bytes())?; + } + //.env + let env_template = include_str!("../template/.env.hbs"); + let env_rendered = handlebars.render_template(env_template, &data)?; + let mut env_file = File::create(project_path.join(".env"))?; + env_file.write_all(env_rendered.as_bytes())?; + } + } + if is_diesel { + //src/schema.rs + let schema_template = include_str!("../template/src/schema.hbs"); + let schema_rendered = handlebars.render_template(schema_template, &data)?; + let mut schema_file = File::create(src_path.join("schema.rs"))?; + schema_file.write_all(schema_rendered.as_bytes())?; + //src/models + let models_path = src_path.join("models"); + std::fs::create_dir_all(&models_path)?; + //src/models/mod.rs + let models_mod_template = include_str!("../template/src/models/mod.hbs"); + let models_mod_rendered = handlebars.render_template(models_mod_template, &data)?; + let mut models_mod_file = File::create(models_path.join("mod.rs"))?; + models_mod_file.write_all(models_mod_rendered.as_bytes())?; + //src/models/user.rs + let models_user_template = include_str!("../template/src/models/user.hbs"); + let models_user_rendered = handlebars.render_template(models_user_template, &data)?; + let mut models_user_file = File::create(models_path.join("user.rs"))?; + models_user_file.write_all(models_user_rendered.as_bytes())?; //migrations let migrations_path: std::path::PathBuf = project_path.join("migrations"); std::fs::create_dir_all(&migrations_path)?; - //migrations/2021-10-20-000000_create_users_table/up.sql - let up_sql_bytes = include_bytes!("../template/migrations/20231001143156_users.sql"); - let mut up_sql_file = File::create(migrations_path.join("20231001143156_users.sql"))?; + //migrations/2023-10-21-084227_create_users_table + let migrations_create_users_table_path = + migrations_path.join("2023-10-21-084227_create_users_table"); + std::fs::create_dir_all(&migrations_create_users_table_path)?; + //migrations/2023-10-21-084227_create_users_table/up.sql + let up_sql_bytes = include_bytes!( + "../template/diesel_migrations/2023-10-21-084227_create_users_table/up.sql" + ); + let mut up_sql_file = File::create(migrations_create_users_table_path.join("up.sql"))?; up_sql_file.write_all(up_sql_bytes)?; + //migrations/2023-10-21-084227_create_users_table/down.sql + let down_sql_bytes = include_bytes!( + "../template/diesel_migrations/2023-10-21-084227_create_users_table/down.sql" + ); + let mut down_sql_file: File = + File::create(migrations_create_users_table_path.join("down.sql"))?; + down_sql_file.write_all(down_sql_bytes)?; + //migrations/.keep + 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)?; let mut env_file = File::create(project_path.join(".env"))?; env_file.write_all(env_rendered.as_bytes())?; - } - if is_sea_orm { - //migration - let migration_path = project_path.join("migration"); - std::fs::create_dir_all(&migration_path)?; - //migration/src - let migration_src_path = migration_path.join("src"); - std::fs::create_dir_all(&migration_src_path)?; - //migration/src/main.rs - let migration_main_byetes = include_bytes!("../template/migration/src/main.rs"); - let mut migration_main_file = File::create(migration_src_path.join("main.rs"))?; - migration_main_file.write_all(migration_main_byetes)?; - //migration/src/lib.rs - let migration_lib_byetes = include_bytes!("../template/migration/src/lib.rs"); - let mut migration_lib_file = File::create(migration_src_path.join("lib.rs"))?; - migration_lib_file.write_all(migration_lib_byetes)?; - //migration/src/m20220101_000001_create_table.rs - let migration_create_table_byetes = - include_bytes!("../template/migration/src/m20220101_000001_create_table.rs"); - let mut migration_create_table_file = - File::create(migration_src_path.join("m20220101_000001_create_table.rs"))?; - migration_create_table_file.write_all(migration_create_table_byetes)?; - //migration/Cargo.toml - let migration_cargo_template = include_str!("../template/migration/Cargo.toml.hbs"); - let migration_cargo_rendered = - handlebars.render_template(migration_cargo_template, &data)?; - let mut migration_cargo_file = File::create(migration_path.join("Cargo.toml"))?; - migration_cargo_file.write_all(migration_cargo_rendered.as_bytes())?; - //migration/README.md - let migration_readme_bytes = include_bytes!("../template/migration/README.md"); - let mut migration_readme_file = File::create(migration_path.join("README.md"))?; - migration_readme_file.write_all(migration_readme_bytes)?; + //template//diesel.toml + let diesel_template = include_str!("../template/diesel.hbs"); + let diesel_rendered = handlebars.render_template(diesel_template, &data)?; + let mut diesel_file = File::create(project_path.join("diesel.toml"))?; + diesel_file.write_all(diesel_rendered.as_bytes())?; + + //data + let data_path = project_path.join("data"); + std::fs::create_dir_all(&data_path)?; + //data/init_sql.sql + let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); + let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; + let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; + init_sql_file.write_all(init_sql_rendered.as_bytes())?; if is_sqlite { - //data - let data_path = project_path.join("data"); - std::fs::create_dir_all(&data_path)?; - //data/demo.db - let demo_db_bytes = include_bytes!("../template/data/demo_sea_orm.db"); - let mut demo_db_file = File::create(data_path.join("demo.db"))?; - demo_db_file.write_all(demo_db_bytes)?; - } - else { - let data_path = project_path.join("data"); - std::fs::create_dir_all(&data_path)?; - //data/init_sql.sql - let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); - let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; - let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; - init_sql_file.write_all(init_sql_rendered.as_bytes())?; + //data/test.db + let demo_db_bytes = include_bytes!("../template/data/diesel_test.db"); + let mut test_db_file = File::create(data_path.join("test.db"))?; + test_db_file.write_all(demo_db_bytes)?; } - //.env - let env_template = include_str!("../template/.env.hbs"); - let env_rendered = handlebars.render_template(env_template, &data)?; - let mut env_file = File::create(project_path.join(".env"))?; - env_file.write_all(env_rendered.as_bytes())?; } } Ok(()) diff --git a/src/utils/get_selection.rs b/src/utils/get_selection.rs index 1a305a6..ccc2bb3 100644 --- a/src/utils/get_selection.rs +++ b/src/utils/get_selection.rs @@ -35,7 +35,7 @@ pub fn get_user_selected() -> Result> { let db_conn_types = &[ t!("db_conn_types_sqlx"), t!("db_conn_types_sea_orm"), - // t!("db_conn_types_diesel"), + t!("db_conn_types_diesel"), // t!("db_conn_types_rbatis"), t!("db_conn_types_nothing"), // "custom", @@ -49,8 +49,8 @@ pub fn get_user_selected() -> Result> { let db_conn_type = match db_conn_type_selection { 0 => DbConnectionType::Sqlx, 1 => DbConnectionType::SeaOrm, - 2 => DbConnectionType::Nothing, - // 2 => DbConnectionType::Diesel, + 2 => DbConnectionType::Diesel, + 3 => DbConnectionType::Nothing, // 3 => DbConnectionType::Rbatis, _ => anyhow::bail!("Invalid db connection type selection"), }; @@ -100,7 +100,7 @@ pub enum DbType { pub enum DbConnectionType { Sqlx, SeaOrm, - // Diesel, + Diesel, // Rbatis, Nothing, }