<?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 Andrii Sherman on Medium]]></title>
        <description><![CDATA[Stories by Andrii Sherman on Medium]]></description>
        <link>https://medium.com/@andriisherman?source=rss-4bcf940351e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*R5uH2ONcz7q49iBh1on3Uw.jpeg</url>
            <title>Stories by Andrii Sherman on Medium</title>
            <link>https://medium.com/@andriisherman?source=rss-4bcf940351e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:13:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andriisherman/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[The Data-Access-Pattern first approach with Drizzle]]></title>
            <link>https://medium.com/drizzle-stories/the-data-access-pattern-first-approach-with-drizzle-bca035bbdc63?source=rss-4bcf940351e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bca035bbdc63</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[drizzle]]></category>
            <dc:creator><![CDATA[Andrii Sherman]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 18:19:41 GMT</pubDate>
            <atom:updated>2023-09-22T18:27:12.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*10tnIiF-QTN_4II5VbwgiQ.jpeg" /></figure><h4>Bringing database and backend work into a single TS file is just as beneficial as developing a full-stack application in one language.</h4><h4>Overview</h4><p>When you’re diving into the world of building a backend system from scratch, it’s like starting with a blank canvas. But here’s the thing: your canvas is filled with data, and how you handle it can make or break your project. You might have heard the phrase ‘data is king,’ and it couldn’t be more true in the world of backend development. It’s something most of us understand on a gut level, but often, we don’t have the perfect tools to bring this understanding to life. In this post, we’re going to talk about why taking a data-first approach is the secret sauce for successful backend projects and how you can make it work for you, even if you’re just starting out</p><p>Recently I’ve <a href="https://x.com/andrii_sherman/status/1704940739006747086?s=20">asked on X</a>:</p><blockquote>When you start working on a backend, do you prefer business logic first or database modelling first?</blockquote><p>And I was glad to see that almost all responses are about data modelling first because it’s the right answer, in my opinion. I asked this question because I’m using a pattern that has helped me greatly. It’s all about schema-first data modelling, and there are some TS tools to help you with that.</p><h4>Drizzle for data modelling</h4><p>If you choose to do database modelling first because you care about your models’ performance, and I’ve also seen some comments like, ‘backend may change, but data and the database will be there for a long time,’ then I personally prefer to prioritise thinking about data access patterns initially. This is the right approach for you to take these steps:</p><p>1. Define what data you will store and how you will access it most of the time;<br>2. Define the exact schema, data types, properties, etc.;<br>3. Implement proper indexing and constraint strategies;<br>4. Attempt to write queries right away to see if it’s feasible, how difficult it might be, etc.</p><p>Using Drizzle makes the process much easier, and this is what we’re implementing on all projects. It enables us to iterate rapidly and minimise mistakes. Additionally, we already have a schema defined in TypeScript, and some queries are already prepared in the logic. It appears that we’ve accomplished several tasks in one go without any trade-offs. You can simply ‘push’ your schema and start testing immediately.</p><p>So, how do I plan the backend? Let’s assume that we already have all the UI designs and requirements in place, we’ve already thought about the infrastructure architecture, and we need an SQL database for our main backend features. Here are the steps I would take:</p><p>1. Create a *.ts file and start modelling your schema with Drizzle. Drizzle aims to closely resemble DDL SQL statements, allowing you to define data types, constraints, properties, and more.</p><p>2. If it’s important for your app, you can easily plan indexing and constraint strategies.</p><p>3. Define relationships (in any way you prefer, whether real constraints, using `relations()`, or comments).</p><p>4. In the same file, you can create a mock connection to a database and visualise how your queries, based on the data access patterns you need, will look. This can help you understand if the current schema is suitable. If it’s not, you can make changes in the same file, and types will be inferred automatically, eliminating the need to wait.</p><p>With all of that, you can perform rapid data modelling in one place, eliminating the need for multiple tools, notes, and whiteboards.</p><p>Additionally, you don’t have to learn a custom schema syntax, which can sometimes be challenging. You have control over the precise data types, relationships, and constraints, just as you would with raw DDL statements in SQL. Plus, there’s no need for a generation step each time you make a change, which simplifies the process.</p><h4>Example</h4><p>Let’s say we have a task to build a backend API for managing a simple feed solution, which includes users, posts, and replies to these posts.</p><p>First, you’ll need to create a .ts file, document all the access patterns you would need, create mock database functions, model a schema that you think will fit, and finally, try to write a query that you believe will be the most common.</p><pre>import { drizzle } from &#39;drizzle-orm/node-postgres&#39;;<br>import { index, integer, pgTable, text } from &#39;drizzle-orm/pg-core&#39;;<br><br>const users = pgTable(&#39;users&#39;, {<br> id: integer(&#39;id&#39;).primaryKey(),<br> name: text(&#39;name&#39;).notNull(),<br>});<br><br>const posts = pgTable(&#39;post&#39;, {<br> id: integer(&#39;id&#39;).primaryKey(),<br> content: text(&#39;name&#39;).notNull(),<br> ownerId: integer(&#39;owner_id&#39;).references(() =&gt; users.id),<br>});<br><br>// Let&#39;s mock the database<br>const db = drizzle({} as any);<br><br>// We need to get all posts with a post creator<br>function getPostsWithOwner(userId: number) {<br> <br>}<br><br>// We need to open specific post with all replies<br>function getPostWithReplies(postId: number) {<br> <br>}</pre><p>You can already prototype queries that you think will be used to check which index/constraint strategy to choose.</p><pre>import { eq } from &#39;drizzle-orm&#39;;<br>import { drizzle } from &#39;drizzle-orm/node-postgres&#39;;<br>import { index, integer, pgTable, text } from &#39;drizzle-orm/pg-core&#39;;<br><br>const users = pgTable(&#39;users&#39;, {<br> id: integer(&#39;id&#39;).primaryKey(),<br> name: text(&#39;name&#39;).notNull(),<br>});<br><br>const posts = pgTable(&#39;post&#39;, {<br> id: integer(&#39;id&#39;).primaryKey(),<br> content: text(&#39;name&#39;).notNull(),<br> ownerId: integer(&#39;owner_id&#39;).references(() =&gt; users.id),<br>}, (t) =&gt; ({<br> // we will filter by ownerId, let&#39;s index it<br> ownerSearch: index(&#39;owner_search_idx&#39;).on(t.ownerId),<br>}));<br><br>// Let&#39;s mock the database<br>const db = drizzle({} as any);<br><br>function getPostsWithOwner(userId: number) {<br> db.select().from(posts)<br>      .leftJoin(users, eq(users.id, posts.ownerId))<br>      .where(eq(posts.ownerId, userId));<br>}<br><br>function getPostWithReplies(postId: number) {<br> db.select().from(posts)<br>        // Post replies is still not defined <br>        .leftJoin(postReplies, eq(posts.id, postReplies.parentPost))<br>        .where(eq(posts.id, postId));<br>}</pre><p>We just added an index for the owner_id column and noticed that the postReplies table is missing. To ensure all our queries work, let’s go ahead and add it.</p><pre>const postReplies = pgTable(&#39;post_replies&#39;, {<br> id: integer(&#39;id&#39;).primaryKey(),<br> content: text(&#39;name&#39;).notNull(),<br> // We want to have 1 parent post for all replies<br> parentPost: integer(&#39;parent_post&#39;).references(() =&gt; posts.id),<br>});</pre><p>Now it seems like the basic data access patterns are defined, we’ve played around with the schema, indexes, and queries. Everything was defined in one single file, and all type hints were changed immediately, thanks to TypeScript.</p><p>You can now use the drizzle-kit push command and have the entire schema in your database, allowing you to test it with real data.</p><p>For more references you can check <a href="https://orm.drizzle.team/docs/overview">Drizzle ORM</a> and <a href="https://orm.drizzle.team/kit-docs/overview#prototyping-with-db-push">Drizzle Kit</a></p><h4>Summary</h4><p>While a Drizzle schema may initially seem ‘messy’ and ‘hard to understand,’ and perhaps ‘not as good as a custom DSL,’ once you dive into real data modelling and schema prototyping, you can grasp the true power of having a TypeScript-first, schema-first Drizzle design. This approach not only provides you with the full capabilities of SQL in your backend but also offers a highly productive way to design any backend and database systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bca035bbdc63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drizzle-stories/the-data-access-pattern-first-approach-with-drizzle-bca035bbdc63">The Data-Access-Pattern first approach with Drizzle</a> was originally published in <a href="https://medium.com/drizzle-stories">Drizzle Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrations with Drizzle just got better: push to SQLite is here]]></title>
            <link>https://andriisherman.medium.com/migrations-with-drizzle-just-got-better-push-to-sqlite-is-here-c6c045c5d0fb?source=rss-4bcf940351e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6c045c5d0fb</guid>
            <category><![CDATA[drizzle]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[push]]></category>
            <category><![CDATA[orm]]></category>
            <dc:creator><![CDATA[Andrii Sherman]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 06:41:00 GMT</pubDate>
            <atom:updated>2023-06-17T06:41:00.168Z</atom:updated>
            <content:encoded><![CDATA[<h4>drizzle-kit push is finally here for SQLite. We’ll explore how it works: locally and at the edge.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htV7aKvVsDLqEai307PycA.jpeg" /></figure><h4>Overview</h4><p>When it comes to databases, it is always hard to keep your schema up-to-date. There is the ‘old good’ approach with a set of migration files that can keep track of schema changes and help you upgrade your schema gradually. However, when it comes to local prototyping and rapid schema changes, this approach can quickly become a real mess.</p><p>So, are migration files the only way to manage your schema? <br>In this article, we’ll explore a different approach featured by drizzle-kit, based on a push/pull workflow.</p><p>We’ll showcase drizzle-kit push:sqlite, to manage migrations with local SQLite files, which is a great productivity boost for local development and rapid prototyping.</p><p>But if you think SQLite is still only good for local development, you haven&#39;t been paying attention! To spice it up, we&#39;ll showcase applying those same migrations to Turso, an Edge database compatible with SQLite.</p><h4>What is Turso?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbHr4jpLdJJBQxw1ebXILw.png" /></figure><p><a href="https://turso.tech/">Turso</a> is an edge-hosted, distributed database based on <a href="https://libsql.org/">libSQL</a>, an open-source and open-contribution fork of <a href="https://sqlite.org/">SQLite</a>. It was designed to minimize query latency for applications where queries come from anywhere in the world. In particular, it works well with edge functions provided by cloud platforms such as CloudFlare, Netlify, and Vercel, by putting your data geographically close to the code that accesses it</p><p>For this example, we will set up a new project that will use <a href="https://turso.tech/">Turso</a> as the database</p><h4>Installation</h4><ol><li>Install Turso on your machine:</li></ol><pre>curl -sSfL https://get.tur.so/install.sh | bash</pre><p>2. Verify the installation:</p><pre>turso --version</pre><h4>Managing you databases</h4><ol><li>Use the auth command to start the login process. The command launches your default browser and prompts you to log in with GitHub:</li></ol><pre>turso auth login</pre><p>2. Create a new Turso database:</p><pre>turso db create drizzle-demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*T8KXph2_jw-Uxqy_VAYOMg.png" /></figure><p>3. Create an auth token to get access to your database using <a href="https://libsql.org/">libSQL</a></p><pre>turso db tokens create drizzle-demo</pre><p>Congratulations! 🎉 <br>You have created your first edge database with Turso!</p><p>Now that we have a full set of keys, we can explore the best practices for managing your schema with Drizzle and Turso databases</p><h4>Schema management flows</h4><p>To ensure a smooth and easy development flow, let’s stick to a simple pattern:</p><ol><li>Change your drizzle schema.</li><li>Run drizzle-kit push:sqliteon a local database.</li><li>Check if the schema is ready to be deployed. If not, repeat steps 1–3</li><li>If the schema is ready, run drizzle-kit generate:sqlite</li><li>Execute migrations on a production database during a backend code deployment.</li></ol><p>In case you want to push your schema directly to a production database, follow these steps:</p><ol><li>Change your drizzle schema.</li><li>Run drizzle-kit push:sqlite on a production database.</li></ol><p><em>** However, we will stick with the first approach because the second one is risky and not recommended for usage on production databases</em></p><h4>Using local file for prototyping (First approach)</h4><p>Let’s install all the necessary dependencies for this example</p><p>We will use a <a href="https://libsql.org/">libSQL</a> driver, which is an open-source and open-contribution fork of SQLite. It will help us communicate with both local SQLite files and the <a href="https://turso.tech/">Turso</a> database you just created</p><pre>pnpm add drizzle-orm@latest<br>pnpm add drizzle-kit@latest -D<br><br>pnpm add @libsql/client</pre><p>Firstly, we should create a basic schema for the drizzle tables in SQLite.</p><pre>import { index, sqliteTable, integer, text } from &quot;drizzle-orm/sqlite-core&quot;;<br><br>export const users = sqliteTable( &quot;users&quot;, {<br>    id: integer(&quot;id&quot;),<br>    name: text(&quot;name&quot;).notNull(),<br>  },<br>  (table) =&gt; ({<br>    idx1: index(&quot;name_index&quot;).on(table.name),<br>  })<br>);</pre><p>And a drizzle.config.ts file for migration variables with package.json scripts for running migrations:</p><pre>import { Config } from &quot;drizzle-kit&quot;;<br><br>export default {<br>  schema: &quot;./schema.ts&quot;,<br>  out: &quot;./migrations&quot;,<br>  driver: &quot;turso&quot;,<br>  dbCredentials: {<br>    url: &#39;file:./local.db&#39;,<br>  }<br>} satisfies Config;</pre><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;generate&quot;: &quot;drizzle-kit generate:sqlite&quot;,<br>    &quot;push&quot;: &quot;drizzle-kit push:sqlite&quot;,<br>  }<br>}</pre><p>All you need to do is to run drizzle-kit push:sqlite anytime you change your schema file while implementing any new feature in your project</p><pre>pnpm run push</pre><p>If there is no possibility of data loss while changing your schema, <br>drizzle-kit will output</p><pre>No config path provided, using default &#39;drizzle.config.ts&#39;<br>Reading config file &#39;./drizzle.config.ts&#39;<br><br>[✓] Changes applied</pre><p>You can use the --verbose option to print all statements that Drizzle is going to execute in order to sync your schema.</p><p>Additionally, you can use the --strict option to make Drizzle always ask for your confirmation about actions to be taken, even if they do not result in data loss.</p><pre>import { Config } from &quot;drizzle-kit&quot;;<br><br>export default {<br>  schema: &quot;./schema.ts&quot;,<br>  out: &quot;./migrations&quot;,<br>  driver: &quot;turso&quot;,<br>  dbCredentials: {<br>    url: &#39;file:./local.db&#39;,<br>  },<br>  // Print all statements<br>  verbose: true,<br>  // Always ask for my confirmation<br>  strict: true,<br>} satisfies Config;</pre><p>In this case, the same table creation process will yield the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dInVM1qypBhX4s6GoG9Vdg.png" /></figure><p>You can continue pushing any changes you need while developing your application. Let’s say you no longer need the name column and instead need to create a new non-null column called position</p><pre>import { integer, sqliteTable } from &quot;drizzle-orm/sqlite-core&quot;;<br><br>export const users = sqliteTable(<br>  &quot;users&quot;,<br>  {<br>    id: integer(&quot;id&quot;),<br>    position: integer(&quot;position&quot;).notNull(),<br>  }<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUoOalbfpxKaj5XcFkCMxw.png" /></figure><p>Finally, when you are ready with the table structure, you can generate the migration file and then run it on a <strong>Turso</strong> production database.</p><pre>pnpm run generate</pre><pre>No config path provided, using default &#39;drizzle.config.ts&#39;<br>Reading config file &#39;./drizzle.config.ts&#39;<br><br>1 tables<br>users 2 columns 0 indexes 0 fks<br><br>[✓] Your SQL migration file ➜ drizzle/0000_amusing_ego.sql 🚀</pre><p><strong><em>Important! </em></strong><em>The migration files flow was designed for migrating production databases with data. Since in SQLite, many changes require the use of a mirror table and copying data between tables, the generate command won’t automatically handle those changes. Drizzle will provide suggestions, but you are the one who needs to decide on a better migration strategy for your application. Here is an example of the generated output for changes like dropping NOT NULL.</em></p><pre>/*<br> SQLite does not support &quot;Drop not null from column&quot; out of the box, <br> we do not generate automatic migration for that, so it has to be done manually<br> Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php<br>                  https://www.sqlite.org/lang_altertable.html<br>                  https://stackoverflow.com/questions/2083543/modify-a-columns-type-in-sqlite3<br><br> Due to that we don&#39;t generate migration automatically <br> and it has to be done manually<br>*/</pre><p>Now you can create migrate.ts file to either run migrations on server start or in your CI.</p><pre>import { migrate } from &quot;drizzle-orm/libsql/migrator&quot;;<br>import { drizzle } from &quot;drizzle-orm/libsql&quot;;<br>import { createClient } from &quot;@libsql/client&quot;;<br><br>async function main() {<br>  const db = drizzle(createClient({ url: &quot;&quot;, authToken: &quot;&quot; }));<br><br>  console.log(&#39;Running migrations&#39;)<br><br>  await migrate(db, { migrationsFolder: &quot;drizzle&quot; });<br><br>  console.log(&#39;Migrated successfully&#39;)<br><br>  process.exit(0)<br>}<br><br>main().catch((e) =&gt; {<br>    console.error(&#39;Migration failed&#39;)<br>    console.error(e)<br>    process.exit(1)<br>});</pre><h4>Push directly to Turso (Second approach)</h4><p>If you still don’t need those migration files and you are fine with applying schema changes directly to a remote database, you can still do it. All you need to do is change the drizzle.config.ts file to work with Turso.</p><p><em>Note: Be aware of possible data loss statements that may truncate data you don’t want to lose. Drizzle will warn you and ask for your confirmation.</em></p><pre>import { Config } from &quot;drizzle-kit&quot;;<br><br>export default {<br>  schema: &quot;./schema.ts&quot;,<br>  out: &quot;./migrations&quot;,<br>  driver: &quot;turso&quot;,<br>  dbCredentials: {<br>    url: &#39;&#39;,<br>    authToken: &#39;&#39;<br>  }<br>} satisfies Config;</pre><p>Don’t hesitate to hit us a star on <a href="https://github.com/drizzle-team/drizzle-orm">GitHub</a> and subscribe on <a href="http://twitter.com/drizzleorm">Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6c045c5d0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>