Skip to content

Latest commit

 

History

History
93 lines (68 loc) · 2.47 KB

File metadata and controls

93 lines (68 loc) · 2.47 KB
icon title
ri:database-2-line
Database

Nitro provides a built-in and lightweight SQL database layer.

::warning Nitro v3 Alpha docs are a work in progress — expect updates, rough edges, and occasional inaccuracies. ::

The default database connection is preconfigured with SQLite and works out of the box for development mode and any Node.js compatible production deployments. By default, data will be stored in .data/db.sqlite.

:read-more{to="https://db0.unjs.io" title="DB0 Documentation"}

Important

Database support is currently experimental. Refer to the db0 issues for status and bug report.

In order to enable database layer you need to enable experimental feature flag.

import { defineNitroConfig } from "nitro/config";

export default defineNitroConfig({
  experimental: {
    database: true
  }
})

Tip

You can change default connection or define more connections to any of the supported databases.

Tip

You can integrate database instance to any of the supported ORMs.

Usage

import { defineHandler } from "nitro/h3";
import { useDatabase } from "nitro/runtime";

export default defineHandler(async () => {
  const db = useDatabase();

  // Create users table
  await db.sql`DROP TABLE IF EXISTS users`;
  await db.sql`CREATE TABLE IF NOT EXISTS users ("id" TEXT PRIMARY KEY, "firstName" TEXT, "lastName" TEXT, "email" TEXT)`;

  // Add a new user
  const userId = String(Math.round(Math.random() * 10_000));
  await db.sql`INSERT INTO users VALUES (${userId}, 'John', 'Doe', '')`;

  // Query for users
  const { rows } = await db.sql`SELECT * FROM users WHERE id = ${userId}`;

  return {
    rows,
  };
});

Configuration

You can configure database connections using database config:

import { defineNitroConfig } from "nitro/config";

export default defineNitroConfig({
  database: {
    default: {
      connector: "sqlite",
      options: { name: "db" }
    },
    users: {
      connector: "postgresql",
      options: {
        url: "postgresql://username:password@hostname:port/database_name"
      },
    },
  },
});

Tip

You can use the devDatabase config to overwrite the database configuration only for development mode.