Node.js - sql()
Creates a reference to a SQL database.
import { sql } from '@nitric/sdk'
const db = sql('my-data')
Parameters
- Name
 name- Required
 - Required
 - Type
 - string
 - Description
 The unique name of this database within the project.
- Name
 migrations- Optional
 - Optional
 - Type
 - string
 - Description
 Points to the location of migration files, prefixed with
file://, or a migration dockerfile, prefixed withdockerfile://.
Examples
Create a reference to a database
import { sql } from '@nitric/sdk'
const db = sql('my-data')
With a migrations directory
import { sql } from '@nitric/sdk'
const db = sql('my-data', {
  migrations: 'file://migrations/my-data',
})
With a migrations dockerfile
import { sql } from '@nitric/sdk'
const db = sql('my-data', {
  migrations: 'dockerfile://migrations.dockerfile',
})
Connect with Prisma
import { api, sql } from '@nitric/sdk'
import { PrismaClient } from '@prisma/client'
const mainApi = api('main')
const db = sql('my-data')
let prisma
const getClient = async () => {
  // ensure we only create the client once
  if (!prisma) {
    const connectionString = await db.connectionString()
    prisma = new PrismaClient({
      datasourceUrl: connectionString,
    })
  }
  return prisma
}
// api demonstrating connecting to prisma and then doing an insert and select
mainApi.post('/users/:name', async (ctx) => {
  const { name } = ctx.req.params
  const client = await getClient()
  await client.user.create({
    data: {
      name,
      email: `${name}@example.com`,
    },
  })
  const createdUser = await client.user.findFirstOrThrow({
    where: {
      name,
    },
  })
  ctx.res.body = `Created ${name} with ID ${createdUser.id}`
  return ctx
})
Connect with Drizzle
import { api, sql } from '@nitric/sdk'
import { drizzle } from 'drizzle-orm/postgres-js'
import * as schema from '../schema'
import postgres from 'postgres'
import { eq } from 'drizzle-orm'
const mainApi = api('main')
const db = sql('my-data')
let drizzleClient
const getClient = async () => {
  // ensure we only create the client once
  if (!drizzleClient) {
    const connectionString = await db.connectionString()
    const queryClient = postgres(connectionString)
    drizzleClient = drizzle(queryClient, { schema })
  }
  return drizzleClient
}
// api demonstrating connecting with drizzle and then doing an insert and select
mainApi.post('/users/:name', async (ctx) => {
  const { name } = ctx.req.params
  const client = await getClient()
  await client.insert(schema.users).values({
    name,
    email: `${name}@example.com`,
  })
  const createdUser = await client
    .select()
    .from(schema.users)
    .where(eq(schema.users.name, name))
  ctx.res.body = `Created ${name} with ID ${createdUser[0].id}`
  return ctx
})