<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Lu on Medium]]></title>
        <description><![CDATA[Stories by Tony Lu on Medium]]></description>
        <link>https://medium.com/@tonylu880042?source=rss-d3fc1ee986d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*R5FJADz13ZxEJml1.jpg</url>
            <title>Stories by Tony Lu on Medium</title>
            <link>https://medium.com/@tonylu880042?source=rss-d3fc1ee986d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:22:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonylu880042/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Environment Setting for Coding Game with Kaplay with Tauri,]]></title>
            <link>https://tonylu880042.medium.com/environment-setting-for-coding-game-with-kaplay-with-tauri-a47b44f0819d?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a47b44f0819d</guid>
            <category><![CDATA[kaplay]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 06:41:42 GMT</pubDate>
            <atom:updated>2024-08-22T06:41:42.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Step 1.Create the tauri project template: npm create tauri-app@latest</p><pre>create-tauri-app@4.3.0<br>Ok to proceed? (y) y<br>&gt; npx<br>&gt; create-tauri-app<br><br>? Project name (tauri-app) › shooter<br>Identifier (com.shooter.app) › [press enter]<br>? Choose which language to use for your frontend ›<br>❯ TypeScript / JavaScript  (pnpm, yarn, npm, bun)<br>  Rust <br>  .NET <br>[press enter: using Javascript]<br>? Choose your package manager ›<br>❯ npm<br>  pnpm<br>  yarn<br>  bun<br>[press enter: npm]<br>? Choose your UI template ›<br>  Vanilla<br>  Vue <br>  Svelte <br> ❯React <br>  Solid <br>  Angular <br>  Preact<br>[Select React, because we want to use vite to do the job]<br>Choose your UI flavor ›<br>  TypeScript<br>❯ JavaScript<br>[Select Javascript]<br> </pre><p>You can find there is a folder named <strong>shooter</strong>. And it contained the project structure and files, however we need to uninstall few things that we don’t need in our game.</p><p>Step 2. Remove the unused react plugin.</p><pre>npm uninstall @vitejs/plugin-react<br>npm uninstall react react-dom     </pre><p>Step 3. Bring up the vscode to fine tune the project.</p><p>3.1 update the vite setting: remove the following two line.</p><pre>remove import react from &quot;@vitejs/plugin-react&quot;;<br>remove plugins: [react()],</pre><p>3.2 update the package.json</p><p>change the scripts block setting for the alias when execute the vite.</p><p>“dev:browser”:”vite”, “build:browser”: “vite build”,<br> “preview:browser”: “vite preview”,</p><p>then add “dev”: “tauri dev”,<br> “build”: “tauri build”</p><pre>{<br>  &quot;name&quot;: &quot;shooter&quot;,<br>  &quot;private&quot;: true,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev:browser&quot;: &quot;vite&quot;,<br>    &quot;build:browser&quot;: &quot;vite build&quot;,<br>    &quot;preview:browser&quot;: &quot;vite preview&quot;,<br>    &quot;tauri&quot;: &quot;tauri&quot;,<br>    &quot;dev&quot;: &quot;tauri dev&quot;,<br>    &quot;build&quot;: &quot;tauri build&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@tauri-apps/api&quot;: &quot;^1&quot;,<br>    &quot;kaplay&quot;: &quot;^3000.1.17&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@tauri-apps/cli&quot;: &quot;^1&quot;,<br>    &quot;vite&quot;: &quot;^5.3.1&quot;<br>  }<br>}</pre><p>3.3 update tauri.conf.json to use vite</p><pre>&quot;build&quot;: {<br>    &quot;beforeDevCommand&quot;: &quot;npm run dev:browser&quot;,<br>    &quot;beforeBuildCommand&quot;: &quot;npm run build:browser&quot;,<br>    &quot;devPath&quot;: &quot;http://localhost:1420&quot;,<br>    &quot;distDir&quot;: &quot;../dist&quot;<br>  }</pre><p>Step 4. add main.js and update index.html for game entry.</p><p>main.js</p><pre>import { appWindow } from &quot;@tauri-apps/api/window&quot;;<br>import kaplay from &quot;kaplay&quot;;<br><br>const k = kaplay({<br>    width: 1280,<br>    height: 720,<br>    letterbox: true,<br>    global: false,<br>    scale: 2,<br>});<br><br></pre><p>index.html</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Test&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;style&gt;<br>      body {<br>        background-color: black;<br>      }<br>    &lt;/style&gt;    <br>    &lt;script type=&quot;module&quot; src=&quot;/src/main.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Step. 5 run the npm run dev to build the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C699eDauEsrq0pEnx-3cWw.png" /></figure><p>if you see this window pops up, congratulations you are ready to code your kaplay game.</p><p>Reference:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fmbljv1EkrRQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dmbljv1EkrRQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fmbljv1EkrRQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/46263815e1667713cf9105e0ea271f59/href">https://medium.com/media/46263815e1667713cf9105e0ea271f59/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a47b44f0819d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PeloLink, anew accessory for Peloton Bike,]]></title>
            <link>https://tonylu880042.medium.com/pelolink-anew-accessory-for-peloton-bike-d817c3b6e779?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d817c3b6e779</guid>
            <category><![CDATA[ftm]]></category>
            <category><![CDATA[accessories]]></category>
            <category><![CDATA[peloton]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 07:45:34 GMT</pubDate>
            <atom:updated>2024-06-18T07:45:34.063Z</atom:updated>
            <content:encoded><![CDATA[<p>🚴‍♂️ **Unlock the Full Potential of Your Peloton Bike!** 🚴‍♀️</p><p>Are you tired of your Peloton Bike becoming just another stationary bike once your subscription ends? 😓 Don’t let your investment go to waste with limited functionality and just on-screen data.</p><p>Introducing Our Solution:</p><p>We’ve developed a compact device that transforms your Peloton Bike’s signal into FTMS Bluetooth, allowing you to connect with a variety of popular fitness apps like Zwift, Rouvy, Kinomap, and many more! 📲✨</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrAMPAdtpprE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrAMPAdtpprE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrAMPAdtpprE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8938d2168cd139c86c57911c44a0280/href">https://medium.com/media/b8938d2168cd139c86c57911c44a0280/href</a></iframe><p>Why You Need This Device:</p><p>🔹 Break Free from Limitations**: No more restricted access to your bike’s data. Enjoy a comprehensive workout experience across multiple platforms.<br>🔹 Enhanced Fitness Experience: Access a wide range of immersive and interactive apps to keep your workouts exciting and engaging.<br>🔹 Versatile Connectivity: Effortlessly sync your Peloton Bike with FTMS-supported apps for a seamless exercise routine.<br>🔹 Simple Setup: Easy to install, so you can start exploring new fitness adventures immediately.</p><p>Don’t let your fitness journey be confined to one screen. Make your workouts versatile and dynamic with our innovative device! 🚴‍♂️🚴‍♀️</p><p>#Peloton #FTMSBluetooth #Zwift #Rouvy #Kinomap #FitnessInnovation #CyclingTech #WorkoutFreedom #FitnessJourney</p><p>This product is in early stage, please left your message and what you thought about this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d817c3b6e779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust Diesel ORM 應用(一)]]></title>
            <link>https://tonylu880042.medium.com/rust-diesel-orm-%E6%87%89%E7%94%A8-%E4%B8%80-ad14659d546a?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad14659d546a</guid>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Wed, 22 May 2024 03:37:18 GMT</pubDate>
            <atom:updated>2024-05-22T07:58:56.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust Diesel ORM 是一款功能強大的資料庫導向關係對映（ORM）工具，可讓您輕鬆地在 Rust 中進行資料庫操作。Diesel 的最大優勢之一就是其簡潔易用的欄位映射機制，目前版本已經來到2.1.6，所以應該是相當成熟的套件。</p><p>Diesel 具有以下特色：</p><ul><li>支援多種資料庫，包括 PostgreSQL、MySQL、SQLite 等（可以用Feature來切換）</li><li>提供安全、可信賴的資料庫操作</li><li>性能卓越</li><li>社區活躍</li></ul><p>使用方式（以新建資料庫為例）</p><ol><li>安裝diesel cli &lt;- 必須透過此工具來產生資料庫的對應，cargo install diesel_cli</li><li>建立專案，cargo new YOUR_PROJECT</li><li>進入專案目錄，執行diesel setup &lt;- 這個動作會在專案目錄下建立一個mirgration的目錄，用以存放後續資料庫操作sql.</li><li>使用diesel migration generate TABLE_NAME建立表格，在migration目錄下可以看到up.sql, down.sql兩個檔案。 up.sql用來建立table與欄位, down.sql 用來刪除表格。 可用diesel migration redo 來刪除與重建表格。對了，如果有一些預設資料的需求，可以直接在這up.sql中</li><li>當完成up.sql, down.sql可以跑一下 diesel migration run，把資料庫建立起來，接著執行一下 diesel print-schema把資料表與rust 資料對應結構建立起來。 完成之後可以在src目錄下看到一個schema.rs的檔案。這個檔案很重要，後面的CRUD都會與這個有關。</li><li>到前五步主要在將Diesel的作業環境建立起來，接著是建立Rust應用的Model.請看下面的資料結構設定。</li></ol><pre>#[derive(Queryable, Selectable,Debug)]<br>#[diesel(table_name = crate::schema::users)]<br>#[diesel(check_for_backend(diesel::sqlite::Sqlite))]<br>pub struct User {<br>    id: i32,<br>    username: String,<br>    email: String,<br>    created_at: NaiveDateTime,<br>}<br><br>#[derive(Insertable)]<br>#[diesel(table_name = crate::schema::users)]<br>pub struct NewUser&lt;&#39;a&gt; {<br>    pub username: &amp;&#39;a str,<br>    pub password: &amp;&#39;a str,<br>    pub email: &amp;&#39;a str,<br>}</pre><p>這邊的mapping 方式很直覺，基本上沒有難度。但要注意的是如果你的欄位設定為Nullable，則欄位對應的資料屬性上要用option&lt;Type&gt;來對應。要注意<strong><em>欄位出現的順序必須與SQL Table 定義的順序一致</em></strong>。這樣在查詢處理時可以避免許多不必要的問題。</p><p>7. 資料庫連線，請參照底下程式碼</p><pre>fn establish_connection() -&gt; SqliteConnection {<br>    let url = env::var(&quot;DATABASE_URL&quot;).expect(&quot;找不到資料庫位置&quot;);<br>    SqliteConnection::establish(&amp;url).expect(&quot;連線失敗&quot;)<br>  }</pre><p>8. CRUD 操作-新增</p><pre>fn create_user( conn:&amp;mut SqliteConnection, username: &amp;str  ,password: &amp;str ,email: &amp;str)<br>  {<br>    let user = NewUser {<br>        username,<br>        password,<br>        email,<br>    };<br><br>    diesel::insert_into(schema::users::table)<br>    .values(&amp;user)<br>    // 執行<br>    .execute(conn)<br>    .expect(&quot;新增失敗&quot;);<br>  }</pre><pre>fn get_users(conn:&amp;mut SqliteConnection)<br>{<br>    use self::schema::users::dsl::*;<br>    let results = users.load::&lt;User&gt;(conn).expect(&quot;取得列表失敗&quot;);<br>    println!(&quot;{:?}&quot;, results);<br>}</pre><p>delete</p><pre>pub fn delete_user(user_id: i32) -&gt; Result&lt;(), diesel::result::Error&gt; {<br>    use crate::schema::users::dsl::*;<br><br>    // Establish connection to the database<br>    let connection = &amp;mut establish_connection();<br><br>    // Delete the user record from the `users` table<br>    delete(users.filter(id.eq(user_id))).execute(connection)?;<br><br>    Ok(())<br>}</pre><p>update</p><pre>pub fn update_user(user_id: i32, _username: &amp;str, _password: &amp;str, _email: &amp;str ) -&gt;Result&lt;(), diesel::result::Error&gt;{<br>    use crate::schema::users::dsl::*;<br>    let connection = &amp;mut establish_connection();<br>    let result = diesel::update(users.filter(id.eq(user_id)))<br>    .set((username.eq(_username),password.eq(_password),email.eq(_email)))<br>    .execute(connection);    <br>    println!(&quot;Update: {:?}&quot;, result);<br>    Ok(())<br>}</pre><h3><strong>總結（誠實的說是AI產生的）</strong></h3><p>Rust Diesel ORM 是一款功能強大的資料庫對象關係對映（ORM）工具，在開發人員中享有盛譽。以下是對其評價的總結：</p><p><strong>正面評價：</strong></p><ul><li><strong>簡單易用：</strong> 開發人員讚賞 Diesel 的直觀語法和易於理解的 API，使其易於學習和採用。</li><li><strong>功能強大且靈活：</strong> Diesel 提供廣泛的功能和功能，允許開發人員有效地處理複雜的資料庫交互。</li><li><strong>類型安全且安全：</strong> Diesel 的強大類型系統和安全功能可幫助防止運行時錯誤並確保數據完整性。</li><li><strong>性能良好：</strong> Diesel 以其高效的性能而聞名，使其適合生產應用程序。</li><li><strong>活躍的社區和文檔：</strong> Diesel 受益於一個充滿活力的社區和全面的文檔，為開發人員提供支持和資源。</li></ul><p><strong>中立評價：</strong></p><ul><li><strong>學習曲線：</strong> 雖然被認為易於使用，但與更簡單的 ORM 或直接使用 SQL 相比，<strong><em>Diesel 仍然存在學習曲線</em></strong>。</li><li><strong><em>有限的資料庫支持：</em></strong> Diesel 主要專注於 PostgreSQL 和 MySQL，對其他資料庫的支持尚不成熟。</li><li><strong>潛在的樣板代碼：</strong> 根據用例，開發人員在使用複雜查詢或自定義數據類型時可能會遇到樣板代碼。</li></ul><p><strong>負面評價：</strong></p><ul><li><strong>對於有些人來說，學習曲線陡峭：</strong> 一些開發人員認為 Diesel 的類型系統和巨集比其他 ORM 更複雜且更具挑戰性。</li><li><strong>並非總是簡單的解決方案：</strong> 對於更簡單的資料庫交互，直接 SQL 或輕量級 ORM 可能更簡單。</li><li><strong>潛在的性能開銷：</strong> 雖然通常性能良好，但 Diesel 的類型安全檢查和抽象可能會引入與原始 SQL 相比的一些開銷。</li></ul><p>總體而言，Rust Diesel ORM 被高度評價為 Rust 開發人員的一款功能強大、靈活且類型安全的 ORM。其易用性、強大的安全功能和活躍的社區使其成為構建 Web 應用程序和數據驅動項目的熱門選擇。但是，重要的是要考慮學習曲線和潛在的樣板代碼，尤其是對於初學者或具有更簡單資料庫需求的項目。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad14659d546a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sea ORM 的Model 定義]]></title>
            <link>https://tonylu880042.medium.com/sea-orm-%E7%9A%84model-%E5%AE%9A%E7%BE%A9-e76c28f951c3?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e76c28f951c3</guid>
            <category><![CDATA[sea-orm]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 02:42:58 GMT</pubDate>
            <atom:updated>2024-03-14T02:42:58.564Z</atom:updated>
            <content:encoded><![CDATA[<h3>在開始之前</h3><p>Sea ORM 中的 Active Model 概念是受到了 ActiveRecord (Ruby on Rail)面向物件的資料庫互動方式的啟發。它也將每個資料表對應一個模型類,提供類似的create、read、update、delete等方法,所以開發者就無需手動編寫SQL,可有效率地對資料庫進行操作。但是天下沒有白吃的午餐，在建立模型時得去定義你的新增、更新的模型方式。</p><h3>新增的model 定義</h3><p>Sea_ORM的entity 定義是有一個基本的樣板可以參考的，底下是範本案例，要注意的是Relation 如果沒有定義就留空不要刪除，impl ActiveModelBehavior for ActiveModel {}也是。</p><pre>use sea_orm::entity::prelude::*;<br><br>#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]<br>#[sea_orm(table_name = &quot;cake&quot;)]<br>pub struct Model {<br>    #[sea_orm(primary_key)]<br>    pub id: i32,<br>    pub name: String,<br>}<br><br>#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]<br>pub enum Relation {<br>    #[sea_orm(has_many = &quot;super::fruit::Entity&quot;)]<br>    Fruit,<br>}<br><br>impl Related&lt;super::fruit::Entity&gt; for Entity {<br>    fn to() -&gt; RelationDef {<br>        Relation::Fruit.def()<br>    }<br>}<br><br>impl ActiveModelBehavior for ActiveModel {}</pre><p>關於這段程式碼impl ActiveModelBehavior for ActiveModel {}是實做了一個Trait(特徵)，用於為該ActiveModel添加一些自定義的行為和功能。</p><p>在Sea ORM中, ActiveModelBehavior是一個Trait, 它定義了一些可覆寫的方法,允許開發人員對ActiveModel的默認行為進行定制。通過實現這個Trait, 你可以對ActiveModel的生命週期方法(如before_create、after_update等)進行攔截並添加自定義邏輯。</p><p>讓我們來看一個例子:</p><pre>use sea_orm::entity::prelude::*;<br><br>#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]<br>#[sea_orm(table_name = &quot;users&quot;)]<br>pub struct Model {<br>    pub id: i32,<br>    pub name: String,<br>    pub created_at: DateTimeWithTimeZone,<br>    pub updated_at: DateTimeWithTimeZone,<br>}<br><br>#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]<br>pub enum Relation {}<br><br>impl ActiveModelBehavior for ActiveModel {<br>    fn before_create(mut self, _: &amp;mut DbBackend) -&gt; Result&lt;Self, DbErr&gt; {<br>        self.created_at = DateTimeWithTimeZone::current();<br>        Ok(self)<br>    }<br><br>    fn before_update(mut self, _: &amp;mut DbBackend) -&gt; Result&lt;Self, DbErr&gt; {<br>        self.updated_at = DateTimeWithTimeZone::current();<br>        Ok(self)<br>    }<br>}</pre><p>在這個例子中,重寫了before_create和before_update方法。</p><ul><li>before_create在創建新實體前觸發,在這裡設置了created_at字段的值為當前時間。</li><li>before_update在更新實體前觸發,我們在這裡更新了updated_at字段為當前時間。</li></ul><p>通過實做ActiveModelBehavior Trait,就可以攔截模型的生命週期事件,注入自定義邏輯,實現如自動填充時間戳記、執行validation、觸發側邊效應等需求,使ActiveModel更加強大和靈活。</p><p>這是Sea ORM賦予開發者擴展能力的一個體現,允許根據業務需求定制預設行為,同時不影響其餘功能,提高了程式碼的可維護性和可擴展性。</p><p>對於entity 的欄位定義可以參考<a href="https://www.sea-ql.org/SeaORM/docs/generate-entity/entity-structure/">這裡</a></p><p>有時間再寫透過Sea_ORM對資料庫基本操作。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e76c28f951c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SeaORM 初探]]></title>
            <link>https://tonylu880042.medium.com/%E7%B0%A1%E5%96%AE%E8%A8%98%E9%8C%84%E4%B8%80%E4%B8%8B-seaorm-%E7%9A%84%E6%87%89%E7%94%A8%E9%81%8E%E7%A8%8B-000b743bd673?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/000b743bd673</guid>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 10:39:56 GMT</pubDate>
            <atom:updated>2024-03-14T04:50:31.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>前置工作</h3><h4>1.資料庫設定</h4><p>前提，必須先安裝資料庫，目前常用的資料庫如postgres, 並在資料庫中有一個可以登入的使用者，登陸到一個資料庫中。本例安裝postgres 在本機中，並建立一個使用者為tony/tony. 建立資料庫egym. 我所採用的工具是pgAdmin 4 很好用的工具</p><h4>2.建立Rust專案並安裝sea_orm_cli</h4><ol><li>簡單用cargo 建立一個專案，略過不說。</li><li>安裝sea_orm_cli ，用cargo install sea_orm_cli 即可安裝</li></ol><h4>3.建立專案架構</h4><ol><li>建立migration 子計畫，透過者個子計畫產生資料庫對應的表格。 可以利用sea_orm_cli migration init. 這樣會在你的專案下建立一個migration 目錄，進去修改。 打開m20220101_000001_create_table.rs 你可以用這個檔案作為你的樣板，進行修改，我建議是把table的名字改成你對應的entity 名稱。</li><li>修改一下migration 目錄下的cargo.toml ，要把這兩個feature都打開，如果你是用其他的資料庫記得修改一下對應的sqlx</li></ol><pre>features = [<br>  # Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.<br>  # View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.<br>  # e.g.<br>  &quot;runtime-tokio-rustls&quot;, # `ASYNC_RUNTIME` feature<br>  &quot;sqlx-postgres&quot;,        # `DATABASE_DRIVER` feature<br>]</pre><p>修改m20220101_000001_create_table.rs</p><ol><li>把那個todo!() macro mark掉，不然會有panic</li><li>設定你的資料表，其實滿直覺的你可以看懂。</li></ol><pre>Table::create()<br>                    .table(Post::Table)<br>                    .if_not_exists()<br>                    .col(<br>                        ColumnDef::new(Post::Id)<br>                            .integer()<br>                            .not_null()<br>                            .auto_increment()<br>                            .primary_key(),<br>                    )<br>                    .col(ColumnDef::new(Post::Title).string().not_null())<br>                    .col(ColumnDef::new(Post::Text).string().not_null())<br>                    .to_owned(),</pre><p>3. 修改migration\lib.rs 加入你的migration.rs</p><pre>Box::new(m20220101_000001_create_table::Migration)</pre><p>4. 執行sea_orm_cli migration -u postgres://tony:tony@localhost/egym</p><p>檢查一下執行成果，記得要先refresh 資料庫的schema.</p><p>如果你的資料存在就恭喜你啦，可以往下一步走，下一步討論一下Sea_ORM的特色，ActiveModel, ActiceRecord.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=000b743bd673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SDL2 in Rust under Mac M1]]></title>
            <link>https://tonylu880042.medium.com/using-sdl2-in-rust-under-mac-m1-78a3b0c7eea9?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a3b0c7eea9</guid>
            <category><![CDATA[sdl2-env-setting]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 08:33:44 GMT</pubDate>
            <atom:updated>2024-02-05T08:33:44.933Z</atom:updated>
            <content:encoded><![CDATA[<p>This artcle is a document to record how I solve the issues when using SDL2 in rust on my mac.</p><ol><li>install SDL2 with following command.</li></ol><pre>&gt;brew install sdl2</pre><p>2. using cargo to create the rust app.</p><p>3.add sdl2 crate into toml file</p><pre>[package]<br>name = &quot;game&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html<br><br>[dependencies.sdl2]<br>version = &quot;*&quot;</pre><p>4. add a libary path to your environment. this is the most important steps. if not doing this you will encounter the <a href="https://stackoverflow.com/questions/77829286/no-lc-rpaths-found">No LC_RPATH’s found</a> error….</p><pre>export LIBRARY_PATH=&quot;$LIBRARY_PATH:$(brew --prefix)/lib&quot;</pre><p>That’s it. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a3b0c7eea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust 在match pattern 的借用]]></title>
            <link>https://tonylu880042.medium.com/rust-%E5%9C%A8match-pattern-%E7%9A%84%E5%80%9F%E7%94%A8-37cb2ff8c399?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/37cb2ff8c399</guid>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 02:49:20 GMT</pubDate>
            <atom:updated>2024-01-26T02:49:20.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust的借用是這個語言最重要的特色，但是借用的概念卻常常讓新進的程式設計師感到困惑，看一下底下的程式。乍看之下這個程式似乎沒有啥問題對吧。</p><pre>struct Point {<br>    x: i32,<br>    y: i32,<br>}<br><br>fn main() {<br>    let y: Option&lt;Point&gt; = Some(Point { x: 100, y: 200 });<br><br>    match y {<br>        Some(p) =&gt; {<br>            println!(&quot;Co-ordinates are {},{} &quot;, p.x, p.y);<br>        }<br>        _ =&gt; panic!(&quot;no match!&quot;),<br>    }<br>    y; // Fix without deleting this line.<br>}</pre><p>但當去編譯時就會出現，Error code E0382 A variable was used after its contents have been moved elsewhere. 所以最後的y已經無效。這是因為在match y時，y 已經被移動到Some(p)而失效而導致編譯錯誤。</p><p>該如何解呢？請看底下程式碼，就在Some(p)加入ref 代表這個只是借用參考如此即可保留y的有效性啦。</p><pre>struct Point {<br>    x: i32,<br>    y: i32,<br>}<br><br>fn main() {<br>    let y: Option&lt;Point&gt; = Some(Point { x: 100, y: 200 });<br><br>    match y {<br>        Some(ref p) =&gt; {<br>            println!(&quot;Co-ordinates are {},{} &quot;, p.x, p.y);<br>        }<br>        _ =&gt; panic!(&quot;no match!&quot;),<br>    }<br>    y; // Fix without deleting this line.<br>}</pre><p>下一題繼續。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37cb2ff8c399" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[關於Rust字串]]></title>
            <link>https://tonylu880042.medium.com/%E9%97%9C%E6%96%BCrust%E5%AD%97%E4%B8%B2-1b231ebb2774?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b231ebb2774</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[str]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 02:11:43 GMT</pubDate>
            <atom:updated>2023-11-07T04:19:30.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxPFEP5F_QJxn0j7syTUMw.png" /></figure><p>字串是學習任何一個語言第一個會接觸到的資料型態，打從C的Hello World 開始不能免俗的是我們學習新語言的第一個程式。Rust的字串設計與其他語言是否有差異嗎？這是本篇文章想要探討的主題，也是很基礎的問題，我從自己出發初學這個語言時常常會搞不清楚。在Rust the Book中的<a href="https://doc.rust-lang.org/book/ch04-03-slices.html">The Slice Type</a>有提到字串在Rust中的設計。看一下下面的定義，請問這是什麼意思？</p><pre>let s = “Hello, world!”; </pre><p>“Hello, world” 是個字串常值，也就是無法變更，而字串常值就是指向預先配置的文字的&amp;str (字串切片, String Slice)。slice是一個Rust的參考（reference, 或你也可以稱之為指標），本身是一個胖指標（fat pointer），內容為指向一個記憶體位址以及指向內容的長度。所以上面的 s 的型態就是 &amp;str.</p><p>那Rust的String又是什麼呢？ 基本上他就是一個Vec&lt;u8&gt;的型態，也有是一個保存格式良好（well formed）的向量，存放在Heap，所以String是可以擴展的。</p><p>要注意的是String, &amp;str 都可有一個.len()的方法，這個方法回傳的不是字元數而是bytes的長度（記憶體用量）。</p><pre>assert_eq!(“😀”.len(), 4);<br>assert_eq!(&quot;😀&quot;.chars().count(), 1);</pre><p>補充一個觀念，由於&amp;str是個指標，所以&amp;str本身是無法修改的，必須是要String才能處理。</p><p>字串的使用上，支援 == 與 != 運算子，還有許多方法。可以看一下 std::str。另外有關於目錄的系統字串這得另外處理，有機會再來討論。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b231ebb2774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nuxtjs using Bun to Config Tailwind CSS]]></title>
            <link>https://tonylu880042.medium.com/nuxtjs-using-bun-to-config-tailwind-css-5ba79285bdd7?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ba79285bdd7</guid>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[buns]]></category>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Sat, 23 Sep 2023 00:31:02 GMT</pubDate>
            <atom:updated>2023-09-23T00:31:02.447Z</atom:updated>
            <content:encoded><![CDATA[<p>Bun represents a highly efficient, all-inclusive toolkit designed for accelerating the development of JavaScript and TypeScript applications. What sets Bun apart is its capacity to optimize the development workflow, providing unparalleled speed and efficiency. This is made achievable through Bun’s multifaceted nature, encompassing not only runtime capabilities but also serving as a package manager, bundler, and test runner.</p><p>When I start to use bun with tailwindcss, by install it using</p><pre>bun install --save-dev @nuxtjs/tailwindcss</pre><p>Then add a module in nuxt.config.ts</p><pre>// https://nuxt.com/docs/api/configuration/nuxt-config<br>export default defineNuxtConfig({<br>  modules:[&#39;tailwindcss&#39;]<br>})</pre><p>then run with bun run dev, I encounter following error.</p><pre>Cannot start nuxt:  Cannot find module &#39;/Users/tony/projects/xxxx/@nuxtjs/tailwindcss&#39;<br>Require stack:<br>- /Users/tony/projects/xxxx/index.js<br><br>  Require stack:<br>  - index.js<br>  at Module._resolveFilename (node:internal/modules/cjs/loader:1070:15)<br>  at Function.resolve (node:internal/modules/helpers:127:19)<br>  at Function._resolve [as resolve] (node_modules/jiti/dist/jiti.js:1:250334)<br>  at resolveModule (node_modules/@nuxt/kit/dist/index.mjs:2239:29)<br>  at requireModule (node_modules/@nuxt/kit/dist/index.mjs:2244:24)<br>  at loadNuxtModuleInstance (node_modules/@nuxt/kit/dist/index.mjs:2459:90)<br>  at async installModule (node_modules/@nuxt/kit/dist/index.mjs:2425:47)<br>  at async initNuxt (node_modules/nuxt/dist/index.mjs:3563:7)<br>  at async NuxtDevServer._load (node_modules/nuxi/dist/chunks/dev2.mjs:255:5)<br>  at async NuxtDevServer.load (node_modules/nuxi/dist/chunks/dev2.mjs:187:7)<br><br></pre><p>after spent some time to expore this issue and found we need to add to bun so that it can load the module to execution environment.</p><pre>bun add tailwindcss</pre><p>with this command you can find there is some change in the package.json.</p><pre>&quot;dependencies&quot;: {<br>    &quot;@nuxtjs/tailwindcss&quot;: &quot;^6.8.0&quot;<br>  }<br>}</pre><p>then you can enjoy the tailwindcss.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ba79285bdd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在Mac book pro M1 上編譯Rust問題的解法]]></title>
            <link>https://tonylu880042.medium.com/%E5%9C%A8mac-book-pro-m1-%E4%B8%8A%E7%B7%A8%E8%AD%AFrust%E5%95%8F%E9%A1%8C%E7%9A%84%E8%A7%A3%E6%B3%95-d237106a9102?source=rss-d3fc1ee986d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d237106a9102</guid>
            <dc:creator><![CDATA[Tony Lu]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 02:55:02 GMT</pubDate>
            <atom:updated>2023-01-12T02:55:02.610Z</atom:updated>
            <content:encoded><![CDATA[<p>有時候在我的mac 上編譯rust程式碼時會出現，底下的問題：</p><p>error: linking with `cc` failed: exit status: 1</p><p>這問題有時讓人很絕望，我看到有人說重新安裝rust就可以解決</p><pre>rustup self uninstall</pre><p>但是我試都不行，後來我發現其實應安裝的不是rust 而是xcode-select。</p><pre>xcode-select install</pre><p>之後就可以，探究其原因是因為環境變數可能因為某些原因跑掉了，以至於cc 的路徑不在當下的環境，透過安裝可以再抓回來。</p><p>以上，happy coding ~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d237106a9102" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>