<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>nestjs Archives | Mithle.sh</title>
	<atom:link href="https://mithle.sh/tag/nestjs/feed/" rel="self" type="application/rss+xml" />
	<link>https://mithle.sh/tag/nestjs/</link>
	<description>The Diary of a Full Stack Developer</description>
	<lastBuildDate>Wed, 20 Dec 2023 17:49:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.5</generator>

<image>
	<url>https://i0.wp.com/mithle.sh/wp-content/uploads/2023/03/cropped-favicon.png?fit=32%2C32&#038;ssl=1</url>
	<title>nestjs Archives | Mithle.sh</title>
	<link>https://mithle.sh/tag/nestjs/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">219607879</site>	<item>
		<title>How to use Drizzle ORM with NestJS</title>
		<link>https://mithle.sh/how-to-use-drizzle-orm-with-nestjs/</link>
					<comments>https://mithle.sh/how-to-use-drizzle-orm-with-nestjs/#respond</comments>
		
		<dc:creator><![CDATA[Mithlesh]]></dc:creator>
		<pubDate>Wed, 20 Dec 2023 17:49:39 +0000</pubDate>
				<category><![CDATA[NestJS]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[nestjs]]></category>
		<category><![CDATA[postgres]]></category>
		<guid isPermaLink="false">https://mithle.sh/?p=1414</guid>

					<description><![CDATA[<p>In this tutorial we will learn how to use Drizzle ORM with NestJS to connect with all the major databases and serverless database providers such...</p>
<p>The post <a href="https://mithle.sh/how-to-use-drizzle-orm-with-nestjs/">How to use Drizzle ORM with NestJS</a> appeared first on <a href="https://mithle.sh">Mithle.sh</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial we will learn how to use Drizzle ORM with NestJS to connect with all the major databases and serverless database providers such as PlanetScale, Turso.</p>



<p>To set up Drizzle ORM in NestJS with each type of databases, follow these steps:</p>



<h2 class="wp-block-heading">1. <span style="text-decoration: underline;">Install Dependencies</span></h2>



<p>Install <strong>Drizzle ORM</strong>, driver of the database that you wish to use and its NestJS <a href="https://github.com/knaadh/nestjs-drizzle" target="_blank" rel="noreferrer noopener">integration module</a> using your favorite package manager.</p>



<h4 class="wp-block-heading">PlanetScale</h4>



<pre class="wp-block-code language-bash"><code>npm install drizzle-orm
npm install @planetscale/database
npm install @knaadh/nestjs-drizzle-planetscale</code></pre>



<h4 class="wp-block-heading">Turso</h4>



<pre class="wp-block-code language-bash"><code>npm install drizzle-orm
npm install @libsql/client
npm install @knaadh/nestjs-drizzle-turso</code></pre>



<h4 class="wp-block-heading">MySQL2</h4>



<pre class="wp-block-code language-bash"><code>npm install drizzle-orm
npm install mysql2
npm install @knaadh/nestjs-drizzle-mysql2</code></pre>



<h4 class="wp-block-heading">Node-Postgres</h4>



<pre class="wp-block-code language-bash"><code>npm install drizzle-orm
npm install pg
npm install @knaadh/nestjs-drizzle-pg</code></pre>



<h4 class="wp-block-heading">Better-SQLite3</h4>



<pre class="wp-block-code language-bash"><code>npm install drizzle-orm
npm install better-sqlite3
npm install @knaadh/nestjs-drizzle-better-sqlite3</code></pre>



<h2 class="wp-block-heading">2. <span style="text-decoration: underline;">Create SQL Schema File</span></h2>



<p>In Drizzle ORM, you need to define your database schema in TypeScript. You can declare your schema in a single <code>schema.ts</code> file or group them logically in multiple files. The schema declaration includes tables, indexes, constraints, foreign keys, and enums as explained <a href="https://orm.drizzle.team/docs/sql-schema-declaration" target="_blank" rel="noreferrer noopener">here</a>. Here&#8217;s an example of declaring tables in a <code>schema.ts</code> file for each of the database types.</p>



<h4 class="wp-block-heading">MySQL</h4>



<pre class="wp-block-code language-typescript"><code>

import { mysqlTable, serial, varchar } from 'drizzle-orm/mysql-core';

export const books = mysqlTable('Books', {
  id: serial('id').primaryKey(),
  name: varchar('name', { length: 256 }),
});

export const authors = mysqlTable('Authors', {
  id: serial('id').primaryKey(),
  name: varchar('name', { length: 256 }),
});</code></pre>



<h4 class="wp-block-heading">PostgreSQL</h4>



<pre class="wp-block-code language-typescript"><code>

import { pgTable, serial, varchar } from 'drizzle-orm/pg-core';

export const books = pgTable('Books', {
  id: serial('id').primaryKey(),
  name: varchar('name', { length: 256 }),
});

export const authors = pgTable('Authors', {
  id: serial('id').primaryKey(),
  name: varchar('name', { length: 256 }),
});</code></pre>



<h4 class="wp-block-heading">SQLite</h4>



<pre class="wp-block-code language-typescript"><code>

import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';

export const books = sqliteTable('Books', {
  id: integer('id').primaryKey(),
  name: text('name'),
});

export const authors = sqliteTable('Authors', {
  id: integer('id').primaryKey(),
  name: text('name'),
});

</code></pre>



<h2 class="wp-block-heading">3. <span style="text-decoration: underline;">Configure the Module</span>:</h2>



<p><span class=""><span class="">Import the integration module of the respective database driver into the root <code>AppModule</code></span></span> and configure it with your credentials, schema file and injection tag as shown in the sample code below for each of the drivers.</p>



<h4 class="wp-block-heading">PlanetScale</h4>



<pre class="wp-block-code language-typescript"><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as schema from '../db/schema';
import { DrizzlePlanetScaleModule } from '@knaadh/nestjs-drizzle-planetscale';

@Module({
  imports: &#91;
    DrizzlePlanetScaleModule.register({
      tag: 'DB_PROD',
      planetscale: {
        config: {
          username: 'PLANETSCALE_USERNAME',
          password: 'PLANETSCALE_PASSWORD',
          host: 'PLANETSCALE_HOST',
        },
      },
      config: { schema: { ...schema } },
    }),
  ],
  controllers: &#91;AppController],
  providers: &#91;AppService],
})
export class AppModule {}

</code></pre>



<h4 class="wp-block-heading">Turso</h4>



<pre class="wp-block-code language-typescript"><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as schema from '../db/schema';
import { DrizzleTursoModule } from '@knaadh/nestjs-drizzle-turso';

@Module({
  imports: &#91;
    DrizzleTursoModule.register({
      tag: 'DB_PROD',
      turso: {
        config: {
          url: 'DATABASE_URL',
          authToken: 'DATABASE_AUTH_TOKEN',
        },
      },
      config: { schema: { ...schema } },
    }),
  ],
  controllers: &#91;AppController],
  providers: &#91;AppService],
})
export class AppModule {}</code></pre>



<h4 class="wp-block-heading">MySQL2</h4>



<pre class="wp-block-code language-typescript"><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as schema from '../db/schema';
import { DrizzleMySqlModule } from '@knaadh/nestjs-drizzle-mysql2';

@Module({
  imports: &#91;
    DrizzleMySqlModule.register({
      tag: 'DB_PROD',
      mysql: {
        connection: 'client',
        config: {
          host: DATABASE_HOST,
          user: DATABASE_USER,
          password : DATABASE_PASSWORD,
          database: DATABASE_NAME,
        },
      },
      config: { schema: { ...schema }, mode: 'default' },
    }),
  ],
  controllers: &#91;AppController],
  providers: &#91;AppService],
})
export class AppModule {}</code></pre>



<h4 class="wp-block-heading">Node-Postgres</h4>



<pre class="wp-block-code language-typescript"><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as schema from '../db/schema';
import { DrizzlePGModule } from '@knaadh/nestjs-drizzle-pg';

@Module({
  imports: &#91;
    DrizzlePGModule.register({
      tag: 'DB_PROD',
      pg: {
        connection: 'client',
        config: {
          connectionString: DATABASE_CONNECTION_URL,
        },
      },
      config: { schema: { ...schema } },
    }),
  ],
  controllers: &#91;AppController],
  providers: &#91;AppService],
})
export class AppModule {}</code></pre>



<h4 class="wp-block-heading">Better-SQLite3</h4>



<pre class="wp-block-code language-typescript"><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as schema from '../db/schema';
import { DrizzleBetterSQLiteModule } from '@knaadh/nestjs-drizzle-better-sqlite3';

@Module({
  imports: &#91;
    DrizzleBetterSQLiteModule.register({
      tag: 'DB_PROD',
      sqlite3: {
        filename: DATABASE_FILE,
      },
      config: { schema: { ...schema } },
    }),
  ],
  controllers: &#91;AppController],
  providers: &#91;AppService],
})
export class AppModule {}

</code></pre>



<h2 class="wp-block-heading">4. <span style="text-decoration: underline;">Inject Drizzle Service</span>:</h2>



<p>You can inject the Drizzle instance anywhere using the <code>tag</code> specified in the module configuration of its respective database driver.</p>



<h4 class="wp-block-heading">PlanetScale</h4>



<pre class="wp-block-code language-bash"><code>import { Inject, Injectable } from '@nestjs/common';
import * as schema from '../db/schema';
import { PlanetScaleDatabase } from 'drizzle-orm/planetscale-serverless';
@Injectable()
export class AppService {
  constructor(
    @Inject('DB_PROD') private drizzleProd: PlanetScaleDatabase&lt;typeof schema>
  ) {}
  async getData() {
    const authors = await this.drizzleProd.query.authors.findMany();
    return authors;
  }
}</code></pre>



<h4 class="wp-block-heading">Turso</h4>



<pre class="wp-block-code language-bash"><code>import { Inject, Injectable } from '@nestjs/common';
import * as schema from '../db/schema';
import { LibSQLDatabase } from 'drizzle-orm/libsql';
@Injectable()
export class AppService {
  constructor(
    @Inject('DB_PROD') private drizzleProd: LibSQLDatabase&lt;typeof schema>
  ) {}
  async getData() {
    const authors = await this.drizzleProd.query.authors.findMany();
    return authors;
  }
}</code></pre>



<h4 class="wp-block-heading">MySQL2</h4>



<pre class="wp-block-code language-bash"><code>import { Inject, Injectable } from '@nestjs/common';
import * as schema from '../db/schema';
import { MySql2Database } from 'drizzle-orm/mysql2';
@Injectable()
export class AppService {
  constructor(
    @Inject('DB_PROD') private drizzleProd: MySql2Database&lt;typeof schema>
  ) {}
  async getData() {
    const authors = await this.drizzleProd.query.authors.findMany();
    return authors;
  }
}</code></pre>



<h4 class="wp-block-heading">Node-Postgres</h4>



<pre class="wp-block-code language-bash"><code>import { Inject, Injectable } from '@nestjs/common';
import * as schema from '../db/schema';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
@Injectable()
export class AppService {
  constructor(
    @Inject('DB_PROD') private drizzleProd: NodePgDatabase&lt;typeof schema>
  ) {}
  async getData() {
    const authors = await this.drizzleProd.query.authors.findMany();
    return authors;
  }
}</code></pre>



<h4 class="wp-block-heading">Better-SQLite3</h4>



<pre class="wp-block-code language-bash"><code>import { Inject, Injectable } from '@nestjs/common';
import * as schema from '../db/schema';
import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
@Injectable()
export class AppService {
  constructor(
    @Inject('DB_PROD') private drizzleProd: BetterSQLite3Database&lt;typeof schema>
  ) {}
  async getData() {
    const authors = await this.drizzleProd.query.authors.findMany();
    return authors;
  }
}</code></pre>



<p><strong>Note:</strong> You can connect as many databases as you want, provided the <code>tag</code> should always be different for each database module.</p>
<p>The post <a href="https://mithle.sh/how-to-use-drizzle-orm-with-nestjs/">How to use Drizzle ORM with NestJS</a> appeared first on <a href="https://mithle.sh">Mithle.sh</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mithle.sh/how-to-use-drizzle-orm-with-nestjs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1414</post-id>	</item>
	</channel>
</rss>
