LaraflareDocsFrameworkPackagesReleases13.x

Docs / Database / Database: Getting Started

Database: Getting Started

Introduction

Almost every modern web application interacts with a database. laraflare makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the Eloquent ORM. Currently, laraflare provides first-party support for these databases:

Every query is awaited, so the same code runs against all of them.

Configuration

The configuration for laraflare's database services is located in your application's config/database.ts configuration file. In this file, you may define all of your database connections, as well as specify which connection should be used by default. Most of the configuration options within this file are driven by the values of your application's environment variables. Examples for the connections a new application uses are provided in this file.

By default, laraflare's sample environment configuration uses SQLite, so a new application works on your local machine with no database server. However, you are free to modify your database configuration as needed for your local database.

SQLite Configuration

SQLite databases are contained within a single file on your filesystem. You can create a new SQLite database using the touch command in your terminal: touch database/database.sqlite. After the database has been created, you may configure your environment variables to point to a different file by placing its absolute path in the DB_DATABASE environment variable:

DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite

By default, foreign key constraints are enabled for SQLite connections. If you would like to disable them, you should set the DB_FOREIGN_KEYS environment variable to false:

DB_FOREIGN_KEYS=false

Note

A deployed Worker has no file to open. It uses the d1 connection, whose D1_BINDING environment variable names the D1 binding in wrangler.toml (DB by default).

Configuration Using URLs

Typically, database connections are configured using multiple configuration values such as host, database, username, password, etc. Each of these configuration values has its own corresponding environment variable. This means that when configuring your database connection information on a production server, you need to manage several environment variables.

Some managed database providers such as AWS and Heroku provide a single database "URL" that contains all of the connection information for the database in a single string. An example database URL may look something like the following:

mysql://root:password@127.0.0.1/forge?charset=UTF-8

These URLs typically follow a standard schema convention:

driver://username:password@host:port/database?options

For convenience, laraflare supports these URLs as an alternative to configuring your database with multiple configuration options. If the url (or corresponding DB_URL environment variable) configuration option is present, it will be used to extract the database connection and credential information.

Read and Write Connections

Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. laraflare makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.

To see how read / write connections should be configured, let's look at this example:

mysql: {
  driver: 'mysql' as const,

  read: {
    host: [
      '192.168.1.1',
      '196.168.1.2',
    ],
  },
  write: {
    host: [
      '192.168.1.3',
    ],
  },
  sticky: true,

  port: envString('DB_PORT', '3306'),
  database: envString('DB_DATABASE', ''),
  username: envString('DB_USERNAME', 'root'),
  password: envString('DB_PASSWORD'),
  socket: envString('DB_SOCKET'),
},

Note that three keys have been added to the configuration object: read, write and sticky. The read and write keys have object values containing a single key: host. The rest of the database options for the read and write connections will be merged from the main mysql configuration object.

You only need to place items in the read and write objects if you wish to override the values from the main mysql object. So, in this case, 192.168.1.1 will be used as the host for the "read" connection, while 192.168.1.3 will be used for the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql object will be shared across both connections. When multiple values exist in the host configuration array, a database host will be randomly chosen for each request.

The sticky Option

The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection. This ensures that any data written during the request cycle can be immediately read back from the database during that same request. It is up to you to decide if this is the desired behavior for your application.

If you need to perform write operations without triggering stickiness for subsequent reads (for example, updating job progress or recording audit timestamps), you may execute the operations within the connection's withoutAffectingStickiness method:

import { DB } from '@laraflare/framework';

await DB.connection().withoutAffectingStickiness(async (connection) => {
  await DB.table('jobs').where('id', jobId).update({ started_at: new Date() });
});

// Subsequent reads will continue using the read connection...

Preventing Stale Database Reads

While the sticky option only affects the current request, the PreventStaleDatabaseReads middleware allows subsequent requests in the same session to read recently written data from the write connection. This can help prevent users from seeing stale data while your read replicas catch up with the write database.

To enable this behavior, append the middleware to the web middleware group in your application's bootstrap/app.ts file:

import { PreventStaleDatabaseReads } from '@laraflare/framework/Foundation/Http/Middleware/PreventStaleDatabaseReads';

.withMiddleware((middleware) => {
  middleware.web({ append: [
    PreventStaleDatabaseReads,
  ] });
})

The middleware tracks writes to the default database connection in the user's session. By default, requests within two seconds of a write will use the write connection for reads on that connection. You may customize this duration using the middleware's for method:

middleware.web({ append: [
  PreventStaleDatabaseReads.for(5),
] });

Since this middleware relies on the session, it must run after the StartSession middleware. It does not affect reads made by other sessions or on other database connections.

Note

D1 has one database, so reads already use it and the middleware changes nothing there.

Using the Write Connection for Reads

If you need to ensure that all reads on a connection use the write database while executing a callback, you may use the connection's usingWritePdo method:

import { DB } from '@laraflare/framework';

const users = await DB.connection().usingWritePdo((connection) => DB.table('users').get());

This also applies to Eloquent queries and relationship queries executed within the callback using the same connection. The method returns the callback's result and restores the connection's previous read preference when the callback finishes, even if an exception is thrown.

Pooled PostgreSQL Connections

Many managed PostgreSQL providers offer transaction-mode connection pooling through services such as PgBouncer or connection proxying. These poolers are ideal for application queries, but some schema operations, migrations, and maintenance commands require a direct database connection.

To use a transaction pooler with PostgreSQL, configure the pooled connection as usual and provide direct connection details via the direct configuration option:

pgsql: {
  driver: 'pgsql' as const,
  // ...
  pooled: envBoolean('DB_POOLED', false),
  direct: {
    host: envString('DB_DIRECT_HOST'),
    port: envString('DB_DIRECT_PORT'),
    username: envString('DB_DIRECT_USERNAME'),
    password: envString('DB_DIRECT_PASSWORD'),
    sslmode: envString('DB_DIRECT_SSLMODE'),
  },
},

When a PostgreSQL connection is configured as pooled, laraflare automatically enables emulated prepares for the pooled connection. The direct connection inherits any options not explicitly defined in the direct configuration and uses native prepares by default.

laraflare automatically uses the direct connection for migrations, schema dumps and restores, db:wipe, db:show, and db:table. The db command also uses the direct connection by default when pooled mode is enabled and a direct connection is configured; you may pass the --pooled option to connect to the pooled connection instead:

npx artisan db --pooled

If you need to explicitly use the direct connection in your application, append the ::direct suffix to the connection name:

await DB.connection('pgsql::direct').statement('create extension if not exists "uuid-ossp"');

Running SQL Queries

Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, delete, and statement. Each one answers a promise, so you await it.

Running a Select Query

To run a basic SELECT query, you may use the select method on the DB facade:

import { DB } from '@laraflare/framework';
import { Controller } from './Controller';

export class UserController extends Controller {
  /**
   * Show a list of all of the application's users.
   */
  async index() {
    const users = await DB.select('select * from users where active = ?', [1]);

    return { users };
  }
}

The first argument passed to the select method is the SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where clause constraints. Parameter binding provides protection against SQL injection.

The select method will always return an array of results. Each result within the array will be an object representing a record from the database:

import { DB } from '@laraflare/framework';

const users = await DB.select('select * from users');

for (const user of users) {
  console.log(user.name);
}

Selecting Scalar Values

Sometimes your database query may result in a single, scalar value. Instead of being required to retrieve the query's scalar result from a record object, laraflare allows you to retrieve this value directly using the scalar method:

const burgers = await DB.scalar(
  "select count(case when food = 'burger' then 1 end) as burgers from menu",
);

Selecting Multiple Result Sets

If your application calls stored procedures that return multiple result sets, you may use the selectResultSets method on a connection to retrieve all of the result sets returned by the stored procedure:

const [options, notifications] = await DB.connection().selectResultSets(
  'CALL get_user_options_and_notifications(?)', [request.user().id],
);

Using Named Bindings

Instead of using ? to represent your parameter bindings, you may execute a query using named bindings:

const results = await DB.select('select * from users where id = :id', { id: 1 });

Running an Insert Statement

To execute an insert statement, you may use the insert method on the DB facade. Like select, this method accepts the SQL query as its first argument and bindings as its second argument:

import { DB } from '@laraflare/framework';

await DB.insert('insert into users (id, name) values (?, ?)', [1, 'Marc']);

Running an Update Statement

The update method should be used to update existing records in the database. The number of rows affected by the statement is returned by the method:

import { DB } from '@laraflare/framework';

const affected = await DB.update(
  'update users set votes = 100 where name = ?',
  ['Anita'],
);

Running a Delete Statement

The delete method should be used to delete records from the database. Like update, the number of rows affected will be returned by the method:

import { DB } from '@laraflare/framework';

const deleted = await DB.delete('delete from users');

Running a General Statement

Some database statements do not return any value. For these types of operations, you may use the statement method on the DB facade:

await DB.statement('drop table users');

Running an Unprepared Statement

Sometimes you may want to execute an SQL statement without binding any values. You may use the DB facade's unprepared method to accomplish this:

await DB.unprepared('update users set votes = 100 where name = "Dries"');

Warning

Since unprepared statements do not bind parameters, they may be vulnerable to SQL injection. You should never allow user controlled values within an unprepared statement.

Implicit Commits

When using the DB facade's statement and unprepared methods within transactions you must be careful to avoid statements that cause implicit commits. These statements will cause the database engine to indirectly commit the entire transaction, leaving laraflare unaware of the database's transaction level. An example of such a statement is creating a database table:

await DB.unprepared('create table a (col varchar(1) null)');

Please refer to the MySQL manual for a list of all statements that trigger implicit commits.

Using Multiple Database Connections

If your application defines multiple connections in your config/database.ts configuration file, you may access each connection via the connection method provided by the DB facade. The connection name passed to the connection method should correspond to one of the connections listed in your config/database.ts configuration file or configured at runtime using the config helper:

import { DB } from '@laraflare/framework';

const users = await DB.connection('sqlite').select(/* ... */);

You may access the raw, underlying driver handle of a connection using the getPdo method on a connection instance:

const pdo = await DB.connection().getPdo();

Running Analytical Queries on Vitess

When using a Vitess database, such as PlanetScale, you may use the olap method to execute analytical queries using the OLAP workload:

import { DB } from '@laraflare/framework';

const totals = await DB.connection('mysql').olap((connection) => DB.table('orders')
  .selectRaw('customer_id, sum(total) as total')
  .groupBy('customer_id')
  .get(),
);

laraflare sets the workload on both the read and write connections, then resets it to OLTP when the callback finishes, even if an exception is thrown. The olap method returns the callback's result. On MySQL connections that are not using Vitess, the callback is executed without changing the workload.

You may determine whether a MySQL connection is using Vitess via the isVitess method:

const isVitess = await DB.connection('mysql').isVitess();

Listening for Query Events

If you would like to specify a closure that is invoked for each SQL query executed by your application, you may use the DB facade's listen method. This method can be useful for logging queries or debugging. You may register your query listener closure in the boot method of a service provider:

import { DB, ServiceProvider, type QueryExecuted } from '@laraflare/framework';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   */
  override register(): void {
    //
  }

  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    DB.listen((query: QueryExecuted) => {
      // query.sql;
      // query.bindings;
      // query.time;
      // query.toRawSql();
    });
  }
}

Monitoring Cumulative Query Time

A common performance bottleneck of modern web applications is the amount of time they spend querying databases. Thankfully, laraflare can invoke a closure or callback of your choice when it spends too much time querying the database during a single request. To get started, provide a query time threshold (in milliseconds) and closure to the whenQueryingForLongerThan method. You may invoke this method in the boot method of a service provider:

import { DB, ServiceProvider, type QueryExecuted } from '@laraflare/framework';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   */
  override register(): void {
    //
  }

  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    DB.whenQueryingForLongerThan(500, (connection: object, event: QueryExecuted) => {
      // Notify development team...
    });
  }
}

Database Transactions

You may use the transaction method provided by the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown. If the closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method:

import { DB } from '@laraflare/framework';

await DB.transaction(async () => {
  await DB.update('update users set votes = 1');

  await DB.delete('delete from posts');
});

Note

On D1, a transaction is one batch: its writes run together when the closure returns, all or none. A write inside it therefore cannot fail on a unique key there, and a query that reads back what an earlier write in the same closure wrote sees the database as it was before the closure.

Handling Deadlocks

The transaction method accepts an optional second argument which defines the number of times a transaction should be retried when the database reports a conflict (a deadlock, or SQLite's busy database). Once these attempts have been exhausted, an exception will be thrown:

import { DB } from '@laraflare/framework';

await DB.transaction(async () => {
  await DB.update('update users set votes = 1');

  await DB.delete('delete from posts');
}, 5);

Manually Using Transactions

If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method on a connection:

import { DB } from '@laraflare/framework';

await DB.connection().beginTransaction();

You can rollback the transaction via the rollBack method:

await DB.connection().rollBack();

Lastly, you can commit a transaction via the commit method:

await DB.connection().commit();

Note

The transaction methods control the transactions for both the query builder and Eloquent ORM.

Connecting to the Database CLI

If you would like to connect to your database's CLI, you may use the db Artisan command:

npx artisan db

If needed, you may specify a database connection name to connect to a database connection that is not the default connection:

npx artisan db mysql

Inspecting Your Databases

Using the db:show and db:table Artisan commands, you can get valuable insight into your database and its associated tables. To see an overview of your database, including its size, type, number of open connections, and a summary of its tables, you may use the db:show command:

npx artisan db:show

You may specify which database connection should be inspected by providing the database connection name to the command via the --database option:

npx artisan db:show --database=pgsql

If you would like to include table row counts and database view details within the output of the command, you may provide the --counts and --views options, respectively. On large databases, retrieving row counts and view details can be slow:

npx artisan db:show --counts --views

In addition, you may use the following Schema methods to inspect your database:

import { Schema } from '@laraflare/framework';

const tables = await Schema.getTables();
const views = await Schema.getViews();
const columns = await Schema.getColumns('users');
const indexes = await Schema.getIndexes('users');
const foreignKeys = await Schema.getForeignKeys('users');

If you would like to inspect a database connection that is not your application's default connection, you may use the connection method:

const columns = await Schema.connection('sqlite').getColumns('users');

Table Overview

If you would like to get an overview of an individual table within your database, you may execute the db:table Artisan command. This command provides a general overview of a database table, including its columns, types, attributes, keys, and indexes:

npx artisan db:table users

Monitoring Your Databases

Using the db:monitor Artisan command, you can instruct laraflare to dispatch a DatabaseBusy event if your database is managing more than a specified number of open connections.

To get started, you should schedule the db:monitor command to run every minute. The command accepts the names of the database connection configurations that you wish to monitor as well as the maximum number of open connections that should be tolerated before dispatching an event:

npx artisan db:monitor --databases=mysql,pgsql --max=100

Scheduling this command alone is not enough to trigger a notification alerting you of the number of open connections. When the command encounters a database that has an open connection count that exceeds your threshold, a DatabaseBusy event will be dispatched. You should listen for this event within your application's AppServiceProvider in order to send a notification to you or your development team:

import { Event, Notification } from '@laraflare/framework';
import { DatabaseBusy } from '@laraflare/framework/Database/Events/DatabaseBusy';
import { DatabaseApproachingMaxConnections } from '../Notifications/DatabaseApproachingMaxConnections';

/**
 * Bootstrap any application services.
 */
override boot(): void {
  Event.listen(DatabaseBusy, async (event: DatabaseBusy) => {
    await Notification.route('mail', 'dev@example.com')
      .notify(new DatabaseApproachingMaxConnections(
        event.connectionName,
        event.connections,
      ));
  });
}
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.