This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Reference

Detailed technical reference for CLI, configuration, services, and APIs.

Reference documentation provides detailed technical information.

How to Use

Reference docs are for looking up specific information:

  • CLI Commands: Full command reference
  • Configuration: All configuration options
  • Services: Details about built-in services

Topics

TopicDescription
CLICommand-line interface reference
ConfigConfiguration file reference
VS CodeVS Code server details
JupyterJupyterLab configuration
PostgreSQLDatabase configuration
NginxWeb server configuration
GrafanaMonitoring dashboard
JuiceFSDistributed filesystem
ExtensionsPostgreSQL extensions
APIREST API reference

1 - CLI

Command-line interface reference for Piglet Run, powered by pig - the PostgreSQL package manager.

Overview

The pig CLI provides complete control over PostgreSQL installation, extension management, and system operations.

Installation

# Default (Cloudflare CDN)
curl -fsSL https://repo.pigsty.io/pig | bash

# China Mirror
curl -fsSL https://repo.pigsty.cc/pig | bash

Verify installation:

pig --version
pig --help

Global Options

OptionDescription
--help, -hShow help
--debugEnable debug mode
--log-levelSet log level (debug/info/warn/error)
-H, --homePigsty home directory
-i, --inventoryConfiguration inventory path

Main Commands

Repository Management (pig repo)

pig repo list                    # List available repos and modules
pig repo info                    # Show repository information
pig repo status                  # Display current repo config
pig repo add [modules...]        # Add repositories
pig repo set                     # Setup all required repos (recommended)
pig repo rm [modules...]         # Remove repositories
pig repo update                  # Update package cache

Extension Management (pig ext)

pig ext list [pattern]           # Search/list extensions
pig ext info <name>              # Show extension details
pig ext avail <name>             # Show availability matrix
pig ext status                   # Show installed extensions
pig ext scan                     # Scan installed extensions
pig ext add <name> [-v version]  # Install extension
pig ext rm <name>                # Remove extension
pig ext update                   # Update extensions

Installation Alias (pig install)

pig install pg17                 # Install PostgreSQL 17
pig install pg_duckdb -v 17      # Install extension for PG 17
pig install vector postgis       # Install multiple extensions

PostgreSQL Management (pig pg)

pig pg init                      # Initialize data directory
pig pg start                     # Start PostgreSQL
pig pg stop                      # Stop PostgreSQL
pig pg status                    # Check status
pig pg psql [database]           # Connect to database
pig pg ps                        # Show connections
pig pg vacuum [database]         # Vacuum database
pig pg log tail                  # View logs in real-time

Backup Management (pig pb)

pig pb info                      # Show backup information
pig pb ls                        # List all backups
pig pb backup                    # Create backup
pig pb backup full               # Full backup
pig pb backup incr               # Incremental backup
pig pb restore                   # Restore to latest
pig pb restore -t <time>         # Restore to specific time
pig pb log tail                  # View backup logs

Patroni Cluster (pig pt)

pig pt list                      # List cluster members
pig pt config                    # Show cluster config
pig pt status                    # View service status
pig pt log -f                    # View logs in real-time

Pigsty Management (pig sty)

pig sty init                     # Download and install Pigsty
pig sty boot                     # Install Ansible dependencies
pig sty conf [-m template]       # Generate configuration
pig sty deploy                   # Run deployment playbook
pig sty list                     # List available versions

System Status (pig status)

pig status                       # Show environment status

Environment Variables

VariableDescription
PIGSTY_HOMEPigsty home directory (default: ~/pigsty)
PIG_LOG_LEVELLog level

Examples

# Quick setup for Piglet Run
pig repo set                     # Setup repositories
pig install pg17                 # Install PostgreSQL 17
pig install vector pg_duckdb    # Install extensions
pig sty init && pig sty deploy  # Deploy Pigsty

# Daily operations
pig pg status                    # Check PostgreSQL
pig pb info                      # Check backups
pig ext status                   # Check extensions

See Also

2 - Configuration

Configuration file reference for Piglet Run.

Overview

Piglet Run uses YAML configuration files located in /etc/piglet/.

Main Configuration

File: /etc/piglet/piglet.yml

# Piglet Run Configuration

# System settings
system:
  hostname: piglet
  timezone: UTC
  locale: en_US.UTF-8

# Database settings
database:
  host: localhost
  port: 5432
  user: dba
  database: postgres
  max_connections: 100
  shared_buffers: 256MB

# Services
services:
  vscode:
    enabled: true
    port: 8080
  jupyter:
    enabled: true
    port: 8888
  grafana:
    enabled: true
    port: 3000

# Storage
storage:
  data_dir: /data
  backup_dir: /data/backup
  temp_dir: /tmp/piglet

# Logging
logging:
  level: info
  file: /var/log/piglet/piglet.log
  max_size: 100M
  max_files: 10

Database Configuration

File: /etc/piglet/database.yml

# PostgreSQL Configuration

postgresql:
  version: 17
  data_directory: /data/postgres

  # Connection settings
  listen_addresses: localhost
  port: 5432
  max_connections: 100

  # Memory settings
  shared_buffers: 256MB
  effective_cache_size: 768MB
  work_mem: 4MB
  maintenance_work_mem: 64MB

  # WAL settings
  wal_level: replica
  max_wal_size: 1GB
  min_wal_size: 80MB

  # Logging
  log_destination: csvlog
  logging_collector: on
  log_directory: pg_log

Service Configuration

VS Code Server

File: /etc/piglet/vscode.yml

vscode:
  enabled: true
  port: 8080
  auth: password
  extensions:
    - ms-python.python
    - rust-lang.rust-analyzer

JupyterLab

File: /etc/piglet/jupyter.yml

jupyter:
  enabled: true
  port: 8888
  notebook_dir: /home/dba/notebooks
  kernels:
    - python3
    - ir

Backup Configuration

File: /etc/piglet/backup.yml

backup:
  enabled: true
  schedule: "0 2 * * *"
  retention: 7

  database:
    type: full
    compress: true

  files:
    enabled: true
    paths:
      - /home/dba
      - /etc/piglet

Network Configuration

File: /etc/piglet/network.yml

network:
  # Domain settings
  domain: localhost

  # SSL settings
  ssl:
    enabled: false
    cert: /etc/piglet/ssl/cert.pem
    key: /etc/piglet/ssl/key.pem

  # Proxy settings
  proxy:
    enabled: false
    host: proxy.example.com
    port: 8080

Environment Variables

Override configuration with environment variables:

export PIG_DATABASE_PORT=5433
export PIG_SERVICES_VSCODE_ENABLED=false
export PIG_LOGGING_LEVEL=debug

See Also

3 - VS Code Server

VS Code Server configuration and details for Piglet Run.

Overview

Piglet Run includes a pre-configured VS Code Server (code-server) for browser-based development.

Access

Default URL: http://<ip>/code

Configuration

File: /etc/piglet/vscode.yml

vscode:
  enabled: true
  bind_addr: 127.0.0.1:8080
  auth: password
  password: ${VSCODE_PASSWORD}
  cert: false

  # User data directory
  user_data_dir: /home/dba/.local/share/code-server

  # Extensions directory
  extensions_dir: /home/dba/.local/share/code-server/extensions

Pre-installed Extensions

ExtensionDescription
ms-python.pythonPython language support
ms-toolsai.jupyterJupyter notebook support
rust-lang.rust-analyzerRust language support
golang.goGo language support
dbaeumer.vscode-eslintJavaScript linting
esbenp.prettier-vscodeCode formatter
mtxr.sqltoolsSQL tools

Installing Extensions

Via CLI

code-server --install-extension ms-python.python

Via Settings

  1. Open VS Code in browser
  2. Go to Extensions (Ctrl+Shift+X)
  3. Search and install extensions

Settings

Default settings location: /home/dba/.local/share/code-server/User/settings.json

{
  "editor.fontSize": 14,
  "editor.tabSize": 2,
  "editor.formatOnSave": true,
  "terminal.integrated.defaultProfile.linux": "bash",
  "python.defaultInterpreterPath": "/usr/bin/python3",
  "files.autoSave": "afterDelay"
}

Service Management

# Start VS Code server
pig start vscode

# Stop VS Code server
pig stop vscode

# Restart VS Code server
pig restart vscode

# View logs
pig logs vscode

Keyboard Shortcuts

ShortcutAction
Ctrl+Shift+PCommand palette
Ctrl+PQuick open file
Ctrl+Shift+EExplorer
Ctrl+Shift+FSearch
Ctrl+``Terminal
Ctrl+Shift+GGit

Troubleshooting

Connection Issues

# Check service status
systemctl status code-server

# Check port binding
ss -tlnp | grep 8080

# View logs
journalctl -u code-server -f

Extension Issues

# List installed extensions
code-server --list-extensions

# Reinstall extension
code-server --uninstall-extension EXTENSION_ID
code-server --install-extension EXTENSION_ID

See Also

4 - JupyterLab

JupyterLab configuration and details for Piglet Run.

Overview

Piglet Run includes JupyterLab for interactive computing and data analysis.

Access

Default URL: http://<ip>/jupyter

Configuration

File: /etc/piglet/jupyter.yml

jupyter:
  enabled: true
  port: 8888
  token: ${JUPYTER_TOKEN}

  # Notebook directory
  notebook_dir: /home/dba/notebooks

  # Allowed origins
  allow_origin: "*"

  # Kernels
  kernels:
    - python3
    - ir
    - julia

JupyterLab Configuration

File: /home/dba/.jupyter/jupyter_lab_config.py

c.ServerApp.ip = '127.0.0.1'
c.ServerApp.port = 8888
c.ServerApp.open_browser = False
c.ServerApp.notebook_dir = '/home/dba/notebooks'
c.ServerApp.token = ''
c.ServerApp.allow_origin = '*'

Available Kernels

KernelLanguageDescription
python3PythonIPython kernel
irRR kernel
juliaJuliaJulia kernel
bashBashBash kernel

Install Additional Kernels

# R kernel
R -e "IRkernel::installspec()"

# Julia kernel
julia -e 'using Pkg; Pkg.add("IJulia")'

Pre-installed Extensions

ExtensionDescription
jupyterlab-gitGit integration
jupyterlab-lspLanguage server protocol
jupyterlab-sqlSQL support

Install Extensions

pip install jupyterlab-git
jupyter labextension install @jupyterlab/git

Service Management

# Start Jupyter
pig start jupyter

# Stop Jupyter
pig stop jupyter

# Restart Jupyter
pig restart jupyter

# View logs
pig logs jupyter

Connecting to PostgreSQL

import psycopg2
import pandas as pd

# Connect to database
conn = psycopg2.connect(
    host="localhost",
    database="postgres",
    user="dba"
)

# Query data
df = pd.read_sql("SELECT * FROM my_table", conn)
df.head()

Using SQL Magic

%load_ext sql
%sql postgresql://dba@localhost/postgres

%%sql
SELECT * FROM pg_stat_activity LIMIT 5;

Keyboard Shortcuts

ShortcutAction
Shift+EnterRun cell
Ctrl+EnterRun cell, stay in cell
Alt+EnterRun cell, insert below
EscCommand mode
EnterEdit mode
AInsert cell above
BInsert cell below
DDDelete cell

Troubleshooting

Connection Issues

# Check service status
systemctl status jupyter

# Check port binding
ss -tlnp | grep 8888

# View logs
journalctl -u jupyter -f

Kernel Issues

# List available kernels
jupyter kernelspec list

# Reinstall kernel
python -m ipykernel install --user

See Also

5 - PostgreSQL

PostgreSQL database configuration and details for Piglet Run.

Overview

Piglet Run includes PostgreSQL 17 as the primary database with optimized defaults.

Connection Details

ParameterDefault Value
Hostlocalhost
Port5432
Userdba
Databasepostgres
Socket/var/run/postgresql

Connection Strings

Local Connection

psql -U dba -d postgres

TCP Connection

postgresql://dba@localhost:5432/postgres

With Password

postgresql://dba:password@localhost:5432/postgres

Configuration

File: /data/postgres/postgresql.conf

Memory Settings

# Memory
shared_buffers = 256MB
effective_cache_size = 768MB
work_mem = 4MB
maintenance_work_mem = 64MB
huge_pages = try

Connection Settings

# Connections
listen_addresses = 'localhost'
port = 5432
max_connections = 100
superuser_reserved_connections = 3

WAL Settings

# WAL
wal_level = replica
max_wal_size = 1GB
min_wal_size = 80MB
wal_buffers = 8MB
checkpoint_completion_target = 0.9

Logging

# Logging
log_destination = 'csvlog'
logging_collector = on
log_directory = 'pg_log'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
log_rotation_age = 1d
log_rotation_size = 100MB
log_statement = 'ddl'
log_min_duration_statement = 1000

Client Authentication

File: /data/postgres/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     trust
host    all             all             127.0.0.1/32            scram-sha-256
host    all             all             ::1/128                 scram-sha-256

Service Management

# Start PostgreSQL
pig start postgres

# Stop PostgreSQL
pig stop postgres

# Restart PostgreSQL
pig restart postgres

# Reload configuration
pig reload postgres

# View logs
pig logs postgres

Database Management

# Create database
pig db create mydb

# List databases
pig db list

# Drop database
pig db drop mydb

# Connect to database
pig db connect mydb

User Management

# Create user
pig user create myuser

# Grant privileges
psql -c "GRANT ALL ON DATABASE mydb TO myuser"

# Change password
pig user passwd myuser

Backup and Restore

# Full backup
pig backup db --full

# Point-in-time recovery
pig restore db --time "2024-01-15 14:30:00"

Performance Tuning

RAMshared_bufferseffective_cache_sizework_mem
4GB1GB3GB32MB
8GB2GB6GB64MB
16GB4GB12GB128MB
32GB8GB24GB256MB

Monitoring

# Connection statistics
psql -c "SELECT * FROM pg_stat_activity"

# Database size
psql -c "SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database"

# Table statistics
psql -c "SELECT * FROM pg_stat_user_tables"

See Also

6 - Nginx

Nginx web server configuration for Piglet Run.

Overview

Piglet Run uses Nginx as a reverse proxy and web server for all services.

Configuration

Main config: /etc/nginx/nginx.conf

Site configs: /etc/nginx/conf.d/

Default Configuration

File: /etc/nginx/conf.d/piglet.conf

# Piglet Run Nginx Configuration

upstream vscode {
    server 127.0.0.1:8080;
}

upstream jupyter {
    server 127.0.0.1:8888;
}

upstream grafana {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name _;

    # Homepage
    location / {
        root /www/piglet;
        index index.html;
    }

    # VS Code Server
    location /code {
        proxy_pass http://vscode;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # JupyterLab
    location /jupyter {
        proxy_pass http://jupyter;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    # Grafana
    location /ui {
        proxy_pass http://grafana;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

SSL Configuration

File: /etc/nginx/conf.d/piglet-ssl.conf

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/piglet/ssl/cert.pem;
    ssl_certificate_key /etc/piglet/ssl/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    # ... location blocks ...
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

Service Management

# Start Nginx
pig start nginx

# Stop Nginx
pig stop nginx

# Restart Nginx
pig restart nginx

# Reload configuration
pig reload nginx

# Test configuration
nginx -t

Custom Site Configuration

Create custom site config:

cat > /etc/nginx/conf.d/mysite.conf << 'EOF'
server {
    listen 80;
    server_name mysite.example.com;

    root /www/mysite;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
EOF

nginx -t && systemctl reload nginx

Proxy Configuration

WebSocket Support

location /ws {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;
}

Node.js Application

location /app {
    proxy_pass http://127.0.0.1:3001;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Logging

Access log: /var/log/nginx/access.log

Error log: /var/log/nginx/error.log

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;

Rate Limiting

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

location /api {
    limit_req zone=api burst=20 nodelay;
    proxy_pass http://backend;
}

Troubleshooting

# Test configuration
nginx -t

# Check error log
tail -f /var/log/nginx/error.log

# Check access log
tail -f /var/log/nginx/access.log

# View connections
ss -tlnp | grep nginx

See Also

7 - Grafana

Grafana monitoring dashboard configuration for Piglet Run.

Overview

Piglet Run includes Grafana for comprehensive monitoring and visualization.

Access

Default URL: http://<ip>/ui

Default credentials:

  • Username: admin
  • Password: (shown during installation)

Configuration

File: /etc/grafana/grafana.ini

[server]
http_port = 3000
root_url = %(protocol)s://%(domain)s/ui/
serve_from_sub_path = true

[security]
admin_user = admin
admin_password = ${GRAFANA_PASSWORD}

[auth.anonymous]
enabled = false

[dashboards]
default_home_dashboard_path = /var/lib/grafana/dashboards/home.json

[database]
type = postgres
host = localhost:5432
name = grafana
user = grafana

Pre-installed Dashboards

DashboardDescription
HomeSystem overview
PostgreSQLDatabase metrics
Node ExporterServer resources
NginxWeb server metrics
LogsLog viewer

Data Sources

Prometheus

apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    url: http://localhost:9090
    access: proxy
    isDefault: true

PostgreSQL

datasources:
  - name: PostgreSQL
    type: postgres
    url: localhost:5432
    database: postgres
    user: grafana
    secureJsonData:
      password: ${GRAFANA_DB_PASSWORD}

Loki (Logs)

datasources:
  - name: Loki
    type: loki
    url: http://localhost:3100
    access: proxy

Service Management

# Start Grafana
pig start grafana

# Stop Grafana
pig stop grafana

# Restart Grafana
pig restart grafana

# View logs
pig logs grafana

Creating Dashboards

Via UI

  1. Click “+” in left sidebar
  2. Select “Dashboard”
  3. Add panels with queries
  4. Save dashboard

Via Provisioning

Place JSON dashboard files in /var/lib/grafana/dashboards/

# /etc/grafana/provisioning/dashboards/default.yaml
apiVersion: 1
providers:
  - name: default
    folder: ''
    type: file
    options:
      path: /var/lib/grafana/dashboards

Alerting

Configure Email

[smtp]
enabled = true
host = smtp.example.com:587
user = alerts@example.com
password = ${SMTP_PASSWORD}
from_address = alerts@example.com

Create Alert Rule

  1. Edit panel query
  2. Go to “Alert” tab
  3. Set conditions
  4. Configure notifications

Useful Queries

PostgreSQL Connections

pg_stat_activity_count

CPU Usage

100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

Memory Usage

(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100

Disk Usage

(1 - node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100

API Access

Generate API key:

curl -X POST -H "Content-Type: application/json" \
  -d '{"name":"mykey", "role": "Admin"}' \
  http://admin:password@localhost:3000/api/auth/keys

Troubleshooting

# Check service status
systemctl status grafana-server

# View logs
journalctl -u grafana-server -f

# Test database connection
psql -U grafana -d grafana -c "SELECT 1"

See Also

8 - JuiceFS

JuiceFS distributed filesystem configuration for Piglet Run.

Overview

Piglet Run uses JuiceFS for distributed storage, enabling snapshots and fast cloning.

Architecture

JuiceFS consists of:

  • Metadata Engine: PostgreSQL stores file metadata
  • Object Storage: S3-compatible storage for data blocks
  • FUSE Client: Mounts filesystem locally

Configuration

File: /etc/piglet/juicefs.yml

juicefs:
  name: piglet
  metadata: postgres://dba@localhost:5432/juicefs
  storage: minio
  bucket: http://localhost:9000/piglet
  access_key: ${MINIO_ACCESS_KEY}
  secret_key: ${MINIO_SECRET_KEY}

  # Mount options
  mount_point: /data/jfs
  cache_dir: /var/cache/juicefs
  cache_size: 10240  # 10GB

Mount Configuration

File: /etc/juicefs/piglet.conf

[piglet]
meta = postgres://dba@localhost:5432/juicefs
storage = minio
bucket = http://localhost:9000/piglet
access-key = ${MINIO_ACCESS_KEY}
secret-key = ${MINIO_SECRET_KEY}

# Performance options
cache-dir = /var/cache/juicefs
cache-size = 10240
buffer-size = 300
prefetch = 3

Service Management

# Mount filesystem
pig mount jfs

# Unmount filesystem
pig umount jfs

# Check status
pig status jfs

# View statistics
juicefs stats /data/jfs

Commands

Format Filesystem

juicefs format \
  --storage minio \
  --bucket http://localhost:9000/pig \
  postgres://dba@localhost:5432/juicefs \
  piglet

Mount Filesystem

juicefs mount \
  postgres://dba@localhost:5432/juicefs \
  /data/jfs \
  --cache-dir /var/cache/juicefs \
  --cache-size 10240

Check Filesystem

juicefs fsck postgres://dba@localhost:5432/juicefs

Snapshot Operations

Create Snapshot

juicefs snapshot create /data/jfs snap-$(date +%Y%m%d)

List Snapshots

juicefs snapshot list /data/jfs

Restore Snapshot

juicefs snapshot restore /data/jfs snap-20240115

Delete Snapshot

juicefs snapshot delete /data/jfs snap-20240115

Clone Operations

# Clone directory
juicefs clone /data/jfs/source /data/jfs/dest

# Clone with snapshot
juicefs clone /data/jfs/.snapshots/snap-20240115 /data/jfs/restored

Performance Tuning

Cache Settings

# Increase cache size
juicefs config /data/jfs --cache-size 20480

# Enable writeback
juicefs config /data/jfs --writeback

Metadata Cache

# Entry cache TTL
juicefs mount ... --entry-cache 3 --dir-entry-cache 3 --attr-cache 3

Monitoring

Statistics

juicefs stats /data/jfs

Output:

usage: 10.2 GiB (1234567 inodes)
sessions: 1
trash: 0 (0 Bytes)

Prometheus Metrics

juicefs mount ... --metrics localhost:9567

Troubleshooting

# Check mount status
mount | grep juicefs

# View logs
journalctl -u juicefs -f

# Debug mode
juicefs mount --debug ...

# Repair filesystem
juicefs fsck --repair postgres://dba@localhost:5432/juicefs

See Also

9 - Extensions

PostgreSQL extensions available in Piglet Run.

Overview

Piglet Run includes 340+ PostgreSQL extensions from the Pigsty ecosystem.

Pre-installed Extensions

Core Extensions

ExtensionVersionDescription
pg_stat_statements1.10Track execution statistics
pgcrypto1.3Cryptographic functions
uuid-ossp1.1UUID generation
hstore1.8Key-value store
ltree1.2Hierarchical data
pg_trgm1.6Trigram matching

Vector & AI

ExtensionVersionDescription
pgvector0.7.0Vector similarity search
pgvectorscale0.2.0Vector indexing
pg_embedding0.3.6Embedding functions

Time Series

ExtensionVersionDescription
timescaledb2.14Time-series database
pg_partman5.0Partition management

Geospatial

ExtensionVersionDescription
postgis3.4Geographic objects
postgis_topology3.4Topology support
postgis_raster3.4Raster data
pgrouting3.6Routing algorithms
ExtensionVersionDescription
pg_jieba1.1Chinese word segmentation
zhparser2.2Chinese parser

Installing Extensions

Via SQL

-- Create extension
CREATE EXTENSION pgvector;

-- Create extension in specific schema
CREATE EXTENSION postgis SCHEMA public;

-- Update extension
ALTER EXTENSION pgvector UPDATE;

Via CLI

pig ext install pgvector
pig ext install postgis

Listing Extensions

Installed Extensions

SELECT * FROM pg_extension;

Available Extensions

SELECT * FROM pg_available_extensions ORDER BY name;

Extension Details

SELECT * FROM pg_available_extension_versions
WHERE name = 'pgvector';

Extension Configuration

pg_stat_statements

-- Enable tracking
ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';

-- Configure
ALTER SYSTEM SET pg_stat_statements.track = 'all';
ALTER SYSTEM SET pg_stat_statements.max = 10000;

pgvector

-- Create extension
CREATE EXTENSION vector;

-- Create vector column
CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    embedding vector(384)
);

-- Create index
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);

PostGIS

-- Create extension
CREATE EXTENSION postgis;

-- Create geometry column
CREATE TABLE locations (
    id SERIAL PRIMARY KEY,
    name TEXT,
    geom geometry(Point, 4326)
);

-- Spatial query
SELECT name FROM locations
WHERE ST_DWithin(geom, ST_MakePoint(-122.4, 37.8)::geography, 1000);

TimescaleDB

-- Create extension
CREATE EXTENSION timescaledb;

-- Create hypertable
CREATE TABLE metrics (
    time TIMESTAMPTZ NOT NULL,
    device_id INTEGER,
    value DOUBLE PRECISION
);

SELECT create_hypertable('metrics', 'time');

Managing Extensions

# List installed extensions
pig ext list

# Show extension info
pig ext info pgvector

# Remove extension
pig ext remove pgvector

See Also

10 - REST API

REST API reference for Piglet Run.

Overview

Piglet Run provides a REST API for programmatic access to all features.

Base URL

http://<ip>/api/v1

Authentication

API Key

curl -H "Authorization: Bearer YOUR_API_KEY" \
  http://localhost/api/v1/status

Generate API Key

pig api key create --name mykey

Endpoints

System

Get Status

GET /api/v1/status

Response:

{
  "status": "healthy",
  "version": "2.5.0",
  "uptime": 86400,
  "services": {
    "postgres": "running",
    "vscode": "running",
    "jupyter": "running"
  }
}

Get System Info

GET /api/v1/system

Response:

{
  "hostname": "piglet",
  "os": "Ubuntu 22.04",
  "cpu": 4,
  "memory": "8GB",
  "disk": "100GB"
}

Databases

List Databases

GET /api/v1/databases

Response:

{
  "databases": [
    {
      "name": "postgres",
      "owner": "dba",
      "size": "50MB"
    }
  ]
}

Create Database

POST /api/v1/databases
Content-Type: application/json

{
  "name": "mydb",
  "owner": "dba"
}

Delete Database

DELETE /api/v1/databases/{name}

Backups

List Backups

GET /api/v1/backups

Response:

{
  "backups": [
    {
      "id": "backup-20240115",
      "type": "full",
      "size": "1.2GB",
      "created_at": "2024-01-15T02:00:00Z"
    }
  ]
}

Create Backup

POST /api/v1/backups
Content-Type: application/json

{
  "type": "full",
  "databases": ["postgres"]
}

Restore Backup

POST /api/v1/backups/{id}/restore
Content-Type: application/json

{
  "target_time": "2024-01-15T14:30:00Z"
}

Services

List Services

GET /api/v1/services

Response:

{
  "services": [
    {
      "name": "postgres",
      "status": "running",
      "port": 5432
    },
    {
      "name": "vscode",
      "status": "running",
      "port": 8080
    }
  ]
}

Control Service

POST /api/v1/services/{name}/{action}

Actions: start, stop, restart

Snapshots

List Snapshots

GET /api/v1/snapshots

Create Snapshot

POST /api/v1/snapshots
Content-Type: application/json

{
  "name": "snap-20240115",
  "description": "Before upgrade"
}

Restore Snapshot

POST /api/v1/snapshots/{name}/restore

Users

List Users

GET /api/v1/users

Create User

POST /api/v1/users
Content-Type: application/json

{
  "username": "newuser",
  "password": "secure_password",
  "databases": ["mydb"]
}

Error Responses

{
  "error": {
    "code": "NOT_FOUND",
    "message": "Database not found",
    "details": {
      "database": "nonexistent"
    }
  }
}

Error Codes

CodeHTTP StatusDescription
UNAUTHORIZED401Invalid or missing API key
FORBIDDEN403Insufficient permissions
NOT_FOUND404Resource not found
CONFLICT409Resource already exists
INTERNAL_ERROR500Server error

Rate Limiting

  • Default: 100 requests per minute
  • Burst: 20 requests

Headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1704067200

SDK Examples

Python

import requests

api_key = "YOUR_API_KEY"
base_url = "http://localhost/api/v1"

headers = {"Authorization": f"Bearer {api_key}"}

# Get status
response = requests.get(f"{base_url}/status", headers=headers)
print(response.json())

# Create database
response = requests.post(
    f"{base_url}/databases",
    headers=headers,
    json={"name": "mydb", "owner": "dba"}
)

JavaScript

const apiKey = "YOUR_API_KEY";
const baseUrl = "http://localhost/api/v1";

// Get status
fetch(`${baseUrl}/status`, {
  headers: { Authorization: `Bearer ${apiKey}` }
})
  .then(res => res.json())
  .then(data => console.log(data));

See Also