# Database: Getting Started

## Introduction

Almost every modern web application talks to a database. Laravel Bash talks to two, through their command line clients, which both agree to print tab-separated text with a header row. That's the only thing the rest of Eloquent needs.

| Connection | Client | How it's asked for tabs |
|---|---|---|
| `sqlite` | `sqlite3` | `-separator $'\t' -header` |
| `pgsql` | `psql` | `--no-align --field-separator=$'\t' --pset=footer=off` |

### Configuration

SQLite is the default, and keeps everything in `database/database.sqlite`. To use the Postgres container that Sail starts, set `DB_CONNECTION=pgsql` in `.env`, or for one command:

```bash
DB_CONNECTION=pgsql ./sail artisan migrate --seed
```

```bash
DB_HOST=pgsql
DB_PORT=5432
DB_DATABASE=laravel
DB_USERNAME=sail
DB_PASSWORD=password
```

## Running SQL Queries

```bash
DB::select 'SELECT id, title FROM posts WHERE votes > 100'   # rows, with a header line
DB::statement 'SELECT COUNT(*) FROM posts'                   # no header: one value
```

### Quoting

There are no prepared statements on the command line, so values are quoted with `DB::quote`, which doubles single quotes:

```bash
DB::quote "O'Brien"   # 'O''Brien'
```

> [!WARNING]
> Tabs and newlines are the field and row separators, so `DB::quote` turns them into spaces. A post body can't contain a newline. This is a known limitation, and also a feature, depending on who's asking.

### Inserting

```bash
id=$(DB::insert posts title="Hello" body="World")
```

`DB::insert` builds the column and value lists, and ends the statement with `RETURNING id`, which SQLite has supported since 3.35.

## The SQLite busy timeout

Every request is a separate process, and so is every worker, so several `sqlite3` processes can write to the same file at once. SQLite locks the whole database during a write, and by default anyone else gives up straight away with `database is locked`. Laravel Bash passes `-cmd '.timeout 5000'`, so they wait up to five seconds instead.

## Connecting to the Databases

```bash
./sail sqlite   # sqlite3 database/database.sqlite
./sail psql     # psql in the pgsql container
```
