Skip to main content

API Reference

This section documents pgtofu’s internal Go packages. While pgtofu is primarily used as a CLI tool, understanding the internal APIs is useful for contributors and for embedding pgtofu in other applications.

Package Structure

github.com/accented-ai/pgtofu/
├── cmd/pgtofu/           # CLI entry point
├── internal/
│   ├── cli/              # CLI commands (not importable)
│   ├── schema/           # Core data models
│   ├── extractor/        # Database extraction
│   ├── parser/           # SQL parsing
│   ├── differ/           # Schema comparison
│   ├── generator/        # Migration generation
│   ├── graph/            # Dependency resolution
│   └── util/             # Utilities
└── pkg/database/         # Database connectivity (importable)
Packages under internal/ cannot be imported by external code per Go’s visibility rules. The pkg/ packages are designed for external use.

Core Packages

Package Dependencies

                    ┌──────────────┐
                    │    cli       │
                    └──────┬───────┘

        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
┌──────────────┐   ┌──────────────┐   ┌──────────────┐
│  extractor   │   │   parser     │   │  generator   │
└──────┬───────┘   └──────┬───────┘   └──────┬───────┘
       │                  │                  │
       │                  │                  │
       └──────────────────┼──────────────────┘


                   ┌──────────────┐
                   │   schema     │
                   └──────────────┘


                   ┌──────────────┐
                   │   differ     │──────► graph
                   └──────────────┘

Common Patterns

Creating a Schema from Database

import (
    "context"
    "github.com/accented-ai/pgtofu/internal/extractor"
    "github.com/accented-ai/pgtofu/pkg/database"
)

func extractSchema(ctx context.Context, dbURL string) (*schema.Database, error) {
    // Connect to database
    pool, err := database.NewPoolFromURL(ctx, dbURL)
    if err != nil {
        return nil, err
    }
    defer pool.Close()

    // Create extractor with options
    opts := extractor.Options{
        ExcludeSchemas: []string{"_prisma"},
    }
    ext := extractor.New(pool, opts)

    // Extract schema
    return ext.Extract(ctx)
}

Parsing SQL Files

import "github.com/accented-ai/pgtofu/internal/parser"

func parseSchema(directory string) (*schema.Database, error) {
    opts := parser.Options{
        // Parser options
    }
    p := parser.New(opts)

    return p.ParseDirectory(directory)
}

Comparing Schemas

import "github.com/accented-ai/pgtofu/internal/differ"

func compareSchemas(current, desired *schema.Database) (*differ.DiffResult, error) {
    opts := differ.DefaultOptions()
    d := differ.New(opts)

    return d.Compare(current, desired)
}

Generating Migrations

import "github.com/accented-ai/pgtofu/internal/generator"

func generateMigrations(diff *differ.DiffResult) (*generator.GenerateResult, error) {
    opts := generator.Options{
        OutputDir:     "./migrations",
        StartVersion:  1,
        PreviewMode:   false,
    }
    gen := generator.New(opts)

    return gen.Generate(diff)
}

Error Handling

All packages follow consistent error handling:
// Errors are wrapped with context
if err != nil {
    return nil, fmt.Errorf("extracting tables: %w", err)
}

// Check specific error types
var parseErr *parser.ParseError
if errors.As(err, &parseErr) {
    // Handle parse error specifically
}

Thread Safety

  • schema.* types are not thread-safe; don’t share between goroutines
  • extractor.Extractor uses a single database connection
  • parser.Parser can parse files concurrently
  • differ.Differ is stateless and safe for concurrent use
  • generator.Generator is stateless and safe for concurrent use

Version Compatibility

The internal API may change between minor versions. For stable integration:
  1. Pin to specific pgtofu versions
  2. Use the CLI for automation
  3. Only use pkg/ packages for embedding

See Also