Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/sync-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jobs:

- name: Copy docs to phi-website content/docs
run: |
rm -rf phi-website/content/docs
mkdir -p phi-website/content/docs
cp -r docs/* phi-website/content/docs/

Expand Down
69 changes: 69 additions & 0 deletions docs/cli/Client-Generation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
title: Client Generation
description: Generate strongly-typed Go client code from schema.prisma using the phi generate command.
category: CLI
tags: [cli, generate, client, code-generation, phi-g]
---

# Client Generation Command

The `phi generate` command parses your `schema.prisma` file and generates a 100% type-safe, zero-allocation Go ORM client in the configured output directory.

---

## 1. Quick Usage

Run the generate command from your project root:

```bash
phi generate
```

Or using the short flag:

```bash
phi -g
```

---

## 2. Generation Workflow

When `phi generate` is executed, the CLI performs the following steps:

1. **Configuration Resolution**: Reads `phi.yml` or `phi.json` to determine schema input path and client output directory.
2. **Prisma Schema Parsing**: Parses data models, scalar fields, enums, relation constraints, default values, and native `@db.*` types.
3. **Template Rendering**: Executes Phi's internal Go code generation templates:
* **`client.go`**: Core DB client, connection handles, predicate data types, and dialect queries.
* **`[model].go`**: Model structs, query builders, create/update/upsert inputs, select/omit maps, and model delegates.
* **`[model]/[model].go`**: Isolated model sub-packages exporting type-safe field constants (`user.Email`, `user.Role`, etc.).
* **`errors.go` & `validation.go`**: Sentinel error definitions, driver error translation engines, and in-memory input validation guards.
4. **Formatting & Cleanup**: Ensures generated Go source files are cleanly formatted and ready for instant compilation.

---

## 3. When to Re-Run `phi generate`

Re-run `phi generate` whenever you update your Prisma schema:
* Adding or renaming models or fields.
* Modifying field types or adding `@unique` / `@id` constraints.
* Defining or updating enum values.
* Changing relation rules (`onDelete`).

> [!TIP]
> Add `phi generate` to your project Makefile or CI build script to ensure generated client code is always in sync with your `schema.prisma`.

---

## 4. Generated Package Architecture

For a schema containing a `User` model, `phi generate` outputs the following package structure under `./phi`:

```text
phi/
├── client.go # Core Client instance, DB handle, raw SQL helpers
├── runtime.go # Dialect execution engine & statement caching
├── user.go # User model struct, UserQueryBuilder, UserCreateBuilder, UserUpdateBuilder
└── user/
└── user.go # Model package exporting field constants (user.Email, user.Id, etc.)
```
115 changes: 115 additions & 0 deletions docs/cli/Init-Command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
---
title: Init Command
description: Initialize project configuration files (phi.yml / phi.json) using the Phi CLI.
category: CLI
tags: [cli, init, configuration, setup, phi-yml, phi-json]
---

# Init Command

The `phi init` command bootstraps a configuration file for your project. The configuration file dictates schema locations, output directories for generated Go client packages, migration directories, client package naming, embedded migration flags, and logging options.

---

## 1. Quick Usage

Generate a default YAML configuration file (`phi.yml`) in the current directory:

```bash
phi init
```

Specify a target output directory:

```bash
phi init ./my-project
```

---

## 2. Supported Formats

Phi supports both **YAML** (`.yml` / `.yaml`) and **JSON** (`.json`) configuration formats.

### YAML (Default)

```bash
phi init yml [directory]
```

Generates `phi.yml`:

```yaml
# Name of the generated Go client package (default: "phi")
client_name: phi

# Enable Go 1.16+ embedded migrations (//go:embed) inside client
embed_migrations: true

database:
url_env: DATABASE_URL # Environment variable for runtime client connections.
direct_url_env: DATABASE_DIRECT_URL # Environment variable used for DDL migrations.

schema: ./schema.prisma # Path to your Prisma schema.

output:
client: ./phi # Output directory for generated Go client code.
migrations: ./phi/migrations # Directory for Goose-compatible .sql migration files.

log:
- none # Logging flags: none, query, warn, error, info, all
```

### JSON

```bash
phi init json [directory]
```

Generates `phi.json`:

```json
{
"client_name": "phi",
"embed_migrations": true,
"database": {
"url_env": "DATABASE_URL",
"direct_url_env": "DATABASE_DIRECT_URL"
},
"schema": "./schema.prisma",
"output": {
"client": "./phi",
"migrations": "./phi/migrations"
},
"log": [
"none"
]
}
```

---

## 3. Configuration Fields Breakdown

| Field | Description | Default |
| :--- | :--- | :--- |
| `client_name` | Go package name for the generated client code. | `"phi"` |
| `embed_migrations` | Controls whether Go 1.16+ `//go:embed` migration code is generated inside the client. | `true` |
| `database.url_env` | Environment variable holding runtime database connection URL. | `"DATABASE_URL"` |
| `database.direct_url_env` | Environment variable holding migration/direct DDL connection URL. | `"DATABASE_DIRECT_URL"` |
| `schema` | Path to your input `schema.prisma` file. | `"./schema.prisma"` |
| `output.client` | Directory path where generated client code will be saved. | `"./phi"` |
| `output.migrations` | Directory path where versioned `.sql` migration files are stored. | `"./phi/migrations"` |
| `log` | Active logging categories (`none`, `query`, `warn`, `error`, `info`, `all`). | `["none"]` |

---

## 4. Configuration Ambiguity Protection

To prevent conflicting settings across different files, Phi inspects your project directory for configuration files (`phi.yml`, `phi.yaml`, `phi.json`).

If **more than one** configuration file is detected in the same directory (e.g. both `phi.yml` and `phi.json`), Phi CLI immediately halts with a fatal error:

```text
FATAL: multiple configuration files found (phi.yml, phi.json). Please keep only one configuration file in the project directory.
```
91 changes: 91 additions & 0 deletions docs/cli/Migrations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
---
title: Migrations
description: Declarative, forward-only migration workflows and Goose-compatible DDL file generation in Phi.
category: CLI
tags: [migrations, goose, atlas, ddl, schema-diff, phi-migrate]
---

# Migrations

Phi features a production-grade, **forward-only** migration engine (`phi migrate`). Inspired by Prisma's declarative migration workflow and powered by the Atlas DDL calculation engine, Phi diffs your `schema.prisma` against your database state and generates standard, Goose-compatible SQL migration files.

---

## 1. Migration Model: Forward-Only

Phi adopts a **forward-only** migration strategy. In production database engineering, rolling back migrations via down scripts frequently leads to data corruption or accidental column dropping.

When your schema evolves:

1. Update `schema.prisma`.
2. Run `phi migrate <migration_name>`.
3. Phi calculates the exact SQL delta, appends a new versioned `.sql` migration file, and executes it.

---

## 2. CLI Migration Workflows

### Generating & Applying Migrations

Run the CLI command to create and apply a migration:

```bash
phi migrate <migration_name>
```

Or using the short flag:

```bash
phi -m <migration_name>
```

### What Happens During `phi migrate`:

1. **Database Initialization**: Creates the target database automatically if it does not already exist.
2. **Schema Diffing**: Uses Atlas DDL engine to compare your Prisma schema against current database tables.
3. **Goose SQL Generation**: Writes a versioned SQL file (e.g. `./phi/migrations/00001_init.sql`) containing standard Goose migration headers:
```sql
-- +goose Up
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
PRIMARY KEY ("id")
);
```
4. **Execution**: Applies the migration immediately to the database.

---

## 3. Goose & Embed Compatibility

Because Phi migration files use standard Goose `-- +goose Up` headers, you can embed migration scripts directly into your Go binaries using Go 1.16+ `embed.FS`:

```go
package main

import (
"embed"
"github.com/pressly/goose/v3"
)

//go:embed phi/migrations/*.sql
var embedMigrations embed.FS

func runEmbeddedMigrations(db *sql.DB) error {
goose.SetBaseFS(embedMigrations)
return goose.Up(db, "phi/migrations")
}
```

---

## 4. Dialect-Aware Migration DDL

Phi's migration generator adjusts DDL syntax based on your `schema.prisma` `datasource db { provider = "..." }`:

| Feature | PostgreSQL DDL | SQLite DDL |
| :-------------------- | :---------------------------------------- | :--------------------------------------- |
| **Enums** | Native `CREATE TYPE "Enum" AS ENUM (...)` | Column `TEXT` + `CHECK ("col" IN (...))` |
| **UUID Primary Keys** | `UUID NOT NULL` | `TEXT NOT NULL` |
| **AutoIncrement** | `BIGSERIAL` / `SERIAL` | `INTEGER PRIMARY KEY AUTOINCREMENT` |
| **JSON / JSONB** | `JSONB` | `TEXT` / `BLOB` |
2 changes: 0 additions & 2 deletions docs/Count-Records.md → docs/crud/Count-Records.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Count Records
description: Count the number of records matching a set of predicates.
category: CRUD
tags: [count, count records]
categoryOrder: 2
order: 6
---

# Count Records
Expand Down
2 changes: 0 additions & 2 deletions docs/Create-Records.md → docs/crud/Create-Records.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Create Records
description: Create one or more records.
category: CRUD
tags: [create, createMany, createManyAndReturn, onConflict, conflictAction]
categoryOrder: 2
order: 1
---

# Create Records
Expand Down
30 changes: 26 additions & 4 deletions docs/Delete-Records.md → docs/crud/Delete-Records.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
title: Delete Records
description: Delete one or more records using type-safe delete builders.
category: CRUD
tags: [delete, deleteMany]
categoryOrder: 2
order: 4
tags: [delete, deleteMany, relations, cascade, foreign-key]
---

# Delete Records
Expand All @@ -18,6 +16,30 @@ Phi provides two methods for deleting records:

---

## Relation Deletion Behavior (`onDelete`)

Deletion behavior for foreign key relations is controlled by your `schema.prisma` `@relation(onDelete: ...)` rules:

```prisma
model Post {
id String @id @default(cuid())
authorId String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
}
```

Phi translates `@relation(onDelete: ...)` rules into database foreign key constraints in DDL:

| Prisma `onDelete` Action | SQL Foreign Key DDL Action | Database Behavior on Deleting Parent Record |
| :----------------------- | :------------------------- | :------------------------------------------------------------------------------------- |
| `Cascade` | `ON DELETE CASCADE` | Child records referencing the parent are automatically deleted by the database engine. |
| `Restrict` | `ON DELETE RESTRICT` | Prevents deletion of the parent record if dependent child records exist. |
| `NoAction` | `ON DELETE NO ACTION` | Prevents deletion unless constraints are satisfied within the transaction. |
| `SetNull` | `ON DELETE SET NULL` | Sets foreign key columns on referencing child records to `NULL`. |
| `SetDefault` | `ON DELETE SET DEFAULT` | Resets foreign key columns on child records to their schema default values. |

---

## Delete

Deletes a **single record**.
Expand Down Expand Up @@ -71,7 +93,7 @@ user, err := db.User.Delete(
### Supported Builder Methods

| Method | Description |
| ------------------------ | ------------------------------------------------- |
| :----------------------- | :------------------------------------------------ |
| [`Select`](/docs/Select) | Return only the selected fields and relations. |
| [`Omit`](/docs/Omit) | Return all scalar fields except the omitted ones. |

Expand Down
2 changes: 0 additions & 2 deletions docs/Omit.md → docs/crud/Omit.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Omit
description: Omit specific scalar fields from a query result.
category: Select & Omit
tags: [omit, omit fields, scalar selection]
categoryOrder: 3
order: 2
---

# Omit
Expand Down
2 changes: 0 additions & 2 deletions docs/Query-Filters.md → docs/crud/Query-Filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Query Filters
description: The predicate system for filtering records with EQ, NEQ, GT, LT, In, Contains, Like, and logical operators.
category: Query Filters
tags: [query, filters, eq, neq, gt, lt, in, contains, like, and, or, not, predicates]
categoryOrder: 4
order: 1
---

# Query Filters
Expand Down
2 changes: 0 additions & 2 deletions docs/Read-Records.md → docs/crud/Read-Records.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Read Records
description: Query records using FindUnique, FindFirst, and FindMany.
category: CRUD
tags: [read, query, findUnique, findFirst, findMany]
categoryOrder: 2
order: 2
---

# Read Records
Expand Down
2 changes: 0 additions & 2 deletions docs/Select.md → docs/crud/Select.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ tags:
omit fields,
omit relations,
]
categoryOrder: 3
order: 1
---

# Select
Expand Down
2 changes: 0 additions & 2 deletions docs/Update-Records.md → docs/crud/Update-Records.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ title: Update Records
description: Update one or more records using type-safe update builders.
category: CRUD
tags: [update, updateMany, updateManyAndReturn]
categoryOrder: 2
order: 3
---

# Update Records
Expand Down
Loading
Loading