### Install IntegreSQL locally Source: https://github.com/allaboutapps/integresql/blob/master/README.md Downloads and installs the IntegreSQL binary into the Go bin directory. ```bash # This installs the latest version of IntegreSQL into your $GOBIN go install github.com/allaboutapps/integresql/cmd/server@latest # you may want to rename the binary to integresql after installing: mv $GOBIN/server $GOBIN/integresql ``` -------------------------------- ### Start Development Container Source: https://github.com/allaboutapps/integresql/blob/master/README.md Builds and starts the development Docker container and opens an interactive shell. ```bash # Build the development Docker container, start it and open a shell ./docker-helper.sh --up ``` -------------------------------- ### Run IntegreSQL locally Source: https://github.com/allaboutapps/integresql/blob/master/README.md Sets required environment variables and starts the server process. ```bash export INTEGRESQL_PORT=5000 export PGHOST=127.0.0.1 export PGUSER=test export PGPASSWORD=testpass integresql ``` -------------------------------- ### Initialize and Setup Template with Go Client Source: https://context7.com/allaboutapps/integresql/llms.txt Demonstrates using the Go client to compute a migration hash, set up a template, and retrieve an isolated test database. Requires the integresql-client-go package. ```go package test import ( "context" "database/sql" "crypto/md5" "fmt" "io" "os" "path/filepath" integresql "github.com/allaboutapps/integresql-client-go" ) // ComputeMigrationsHash generates a hash from all migration files func ComputeMigrationsHash(migrationsDir string) (string, error) { h := md5.New() err := filepath.Walk(migrationsDir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return err } f, err := os.Open(path) if err != nil { return err } defer f.Close() if _, err := io.Copy(h, f); err != nil { return err } return nil }) if err != nil { return "", err } return fmt.Sprintf("%x", h.Sum(nil)), nil } // SetupTestDatabase initializes the template and returns a test database func SetupTestDatabase(ctx context.Context) (*sql.DB, error) { client, err := integresql.DefaultClientFromEnv() if err != nil { return nil, fmt.Errorf("failed to create integresql client: %w", err) } // Compute hash from migration files hash, err := ComputeMigrationsHash("./migrations") if err != nil { return nil, fmt.Errorf("failed to compute migrations hash: %w", err) } // Setup template (idempotent - safe for parallel test runners) err = client.SetupTemplateWithDBClient(ctx, hash, func(db *sql.DB) error { // Apply migrations if err := applyMigrations(db); err != nil { return fmt.Errorf("failed to apply migrations: %w", err) } // Seed test fixtures if err := seedFixtures(db); err != nil { return fmt.Errorf("failed to seed fixtures: %w", err) } return nil }) if err != nil { return nil, fmt.Errorf("failed to setup template: %w", err) } // Get isolated test database from pool testDB, err := client.GetTestDatabase(ctx, hash) if err != nil { return nil, fmt.Errorf("failed to get test database: %w", err) } // Connect to the test database db, err := sql.Open("postgres", testDB.Config.ConnectionString()) if err != nil { return nil, fmt.Errorf("failed to connect to test database: %w", err) } return db, nil } func applyMigrations(db *sql.DB) error { // Your migration logic here (e.g., golang-migrate, goose, etc.) _, err := db.Exec(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS posts ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), title VARCHAR(255) NOT NULL, content TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); `) return err } func seedFixtures(db *sql.DB) error { _, err := db.Exec(` INSERT INTO users (email, name) VALUES ('test@example.com', 'Test User'), ('admin@example.com', 'Admin User'); `) return err } ``` -------------------------------- ### Test and Run Server Source: https://github.com/allaboutapps/integresql/blob/master/README.md Executes project tests and starts the IntegreSQL server using environment configurations. ```bash # Execute tests make test # Run IntegreSQL server with config from environment integresql ``` -------------------------------- ### Run IntegreSQL with Docker Source: https://github.com/allaboutapps/integresql/blob/master/README.md Starts the IntegreSQL container with required environment variables and port mapping. ```bash docker run -d --name integresql -e INTEGRESQL_PORT=5000 -p 5000:5000 ghcr.io/allaboutapps/integresql: ``` -------------------------------- ### Go Client Library Usage: Initialize and Setup Template Source: https://context7.com/allaboutapps/integresql/llms.txt The Go client library provides a convenient way to interact with IntegreSQL. The SetupTemplate function handles the full template initialization flow including checking for existing templates. ```go package test import ( "context" "database/sql" "crypto/md5" "fmt" "io" "os" "path/filepath" integresql "github.com/allaboutapps/integresql-client-go" ) // ComputeMigrationsHash generates a hash from all migration files func ComputeMigrationsHash(migrationsDir string) (string, error) { h := md5.New() err := filepath.Walk(migrationsDir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return err } f, err := os.Open(path) if err != nil { return err } defer f.Close() if _, err := io.Copy(h, f); err != nil { return err } return nil }) if err != nil { return "", err } return fmt.Sprintf("%x", h.Sum(nil)), nil } // SetupTestDatabase initializes the template and returns a test database func SetupTestDatabase(ctx context.Context) (*sql.DB, error) { client, err := integresql.DefaultClientFromEnv() if err != nil { return nil, fmt.Errorf("failed to create integresql client: %w", err) } // Compute hash from migration files hash, err := ComputeMigrationsHash("./migrations") if err != nil { return nil, fmt.Errorf("failed to compute migrations hash: %w", err) } // Setup template (idempotent - safe for parallel test runners) err = client.SetupTemplateWithDBClient(ctx, hash, func(db *sql.DB) error { // Apply migrations if err := applyMigrations(db); err != nil { return fmt.Errorf("failed to apply migrations: %w", err) } // Seed test fixtures if err := seedFixtures(db); err != nil { return fmt.Errorf("failed to seed fixtures: %w", err) } return nil }) if err != nil { return nil, fmt.Errorf("failed to setup template: %w", err) } // Get isolated test database from pool testDB, err := client.GetTestDatabase(ctx, hash) if err != nil { return nil, fmt.Errorf("failed to get test database: %w", err) } // Connect to the test database db, err := sql.Open("postgres", testDB.Config.ConnectionString()) if err != nil { return nil, fmt.Errorf("failed to connect to test database: %w", err) } return db, nil } func applyMigrations(db *sql.DB) error { // Your migration logic here (e.g., golang-migrate, goose, etc.) _, err := db.Exec(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS posts ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), title VARCHAR(255) NOT NULL, content TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); `) return err } func seedFixtures(db *sql.DB) error { _, err := db.Exec(` INSERT INTO users (email, name) VALUES ('test@example.com', 'Test User'), ('admin@example.com', 'Admin User'); `) return err } ``` -------------------------------- ### Benchmark Report: Small Project Strategy Source: https://github.com/allaboutapps/integresql/blob/master/README.md A performance report for a test suite with 280 tests, detailing replica switching and setup times. ```bash --- ----------------------------------- --- replicas switched: 280 avg=26ms min=11ms max=447ms replicas awaited: 1 prebuffer=8 avg=417ms max=417ms background replicas: 288 avg=423ms min=105ms max=2574ms - warm up template (cold): 40% 5151ms * truncate: 8% 980ms * migrate: 26% 3360ms * seed: 4% 809ms - switching: 60% 7461ms * disconnect: 2% 322ms * switch replica: 6% 775ms - resolve next: 2% 358ms - await next: 3% 417ms * reinitialize: 50% 6364ms strategy related time: --- 12612ms vs total executed time: 11% 111094ms --- --------------------------------- --- ``` -------------------------------- ### Configure GitHub Actions for IntegreSQL Source: https://github.com/allaboutapps/integresql/blob/master/README.md Example workflow configuration for running IntegreSQL alongside a PostgreSQL service in CI/CD. ```yaml jobs: build-test: runs-on: ubuntu-latest services: postgres: image: postgres: env: POSTGRES_DB: "development" POSTGRES_USER: "dbuser" POSTGRES_PASSWORD: "dbpass" options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432 integresql: image: ghcr.io/allaboutapps/integresql: env: PGHOST: "postgres" PGUSER: "dbuser" PGPASSWORD: "dbpass" ``` -------------------------------- ### Benchmark Report for Database Strategy Source: https://github.com/allaboutapps/integresql/blob/master/README.md This report outlines the performance metrics of a database strategy, detailing time spent on various operations like replica switching, warm-up, and migration. It highlights the impact of cold starts versus cached templates. ```bash --- -------------------------------- --- replicas switched: 50 avg=11ms min=1ms max=445ms replicas awaited: 1 prebuffer=8 avg=436ms max=436ms background replicas: 58 avg=272ms min=41ms max=474ms - warm up template (cold): 82% 2675ms * truncate: 62% 2032ms * migrate: 18% 594ms * seed: 1% 45ms - switching: 17% 571ms * disconnect: 1% 42ms * switch replica: 14% 470ms - resolve next: 1% 34ms - await next: 13% 436ms * reinitialize: 1% 57ms strategy related time: --- 3246ms vs total executed time: 20% 15538ms --- ------------------------------ --- ``` -------------------------------- ### Get Test Database Source: https://context7.com/allaboutapps/integresql/llms.txt Retrieves an isolated test database instance from the pool for a specific template hash. ```bash # Get an isolated test database for your test curl -X GET http://localhost:5000/api/v1/templates/abc123def456/tests ``` -------------------------------- ### GET /api/v1/templates/{hash}/tests Source: https://context7.com/allaboutapps/integresql/llms.txt Retrieves an isolated test database from the pool for the given template hash. ```APIDOC ## GET /api/v1/templates/{hash}/tests ### Description Retrieves an isolated test database from the pool for the given template hash. The returned database is a fresh copy of the template. ### Method GET ### Endpoint /api/v1/templates/{hash}/tests ### Parameters #### Path Parameters - **hash** (string) - Required - The unique hash of the template ### Response #### Success Response (200) - **database** (object) - Contains templateHash and connection config - **id** (integer) - The ID of the test database ``` -------------------------------- ### Get New Test Database Source: https://github.com/allaboutapps/integresql/blob/master/README.md This sequence diagram illustrates the normal flow for obtaining a new, isolated, and pre-populated test database for each test case. The Testrunner requests a database from IntegreSQL, which returns an existing one from a pool, ready for direct connection and use. ```mermaid sequenceDiagram Note right of You: ... loop Each test Note right of Testrunner: Before each test, get a new isolated test database
from the pool for the template hash. Testrunner->>IntegreSQL: GetTestDatabase: GET /api/v1/templates/:hash/tests Note over Testrunner,IntegreSQL: Blocks until the template is finalized Note right of IntegreSQL: The test databases for the template pool
were already created and are simply returned. IntegreSQL-->>Testrunner: StatusOK: 200 Note over Testrunner,PostgreSQL: Your runner now has a fully isolated PostgreSQL database
from our already migrated/seeded template database to use within your test. Testrunner->>PostgreSQL: Directly connect to the test database. Note over Testrunner,PostgreSQL: Run your test code! Testrunner-xPostgreSQL: Disconnect from the test database Note over Testrunner,PostgreSQL: Your test is finished. end ``` -------------------------------- ### Discard Template Database Source: https://context7.com/allaboutapps/integresql/llms.txt Removes a template database and all its associated test databases from the pool. Use this when a template setup failed during migrations/fixtures, or when you need to force recreation of a template. ```APIDOC ## DELETE /api/v1/templates/{templateId} ### Description Removes a template database and all its associated test databases from the pool. ### Method DELETE ### Endpoint `/api/v1/templates/{templateId}` ### Parameters #### Path Parameters - **templateId** (string) - Required - The ID of the template to discard. ### Response #### Success Response (204 No Content) - Template and all test databases removed. #### Error Response (404 Not Found) - Template not found. #### Error Response (503 Service Unavailable) - IntegreSQL cannot connect to PostgreSQL. ``` -------------------------------- ### Initialize and Build Project Source: https://github.com/allaboutapps/integresql/blob/master/README.md Downloads dependencies and tools, then generates, formats, builds, and vets the executable. ```bash # Init dependencies/tools make init # Build executable (generate, format, build, vet) make ``` -------------------------------- ### Initialize Template Database Source: https://context7.com/allaboutapps/integresql/llms.txt Creates a new template database identified by a unique hash derived from migration and fixture files. ```bash # Initialize a new template database with a hash curl -X POST http://localhost:5000/api/v1/templates \ -H "Content-Type: application/json" \ -d '{"hash": "abc123def456"}' ``` -------------------------------- ### Integrate IntegreSQL in Go Tests Source: https://context7.com/allaboutapps/integresql/llms.txt Use TestMain to initialize the template and a helper function to retrieve isolated database instances for parallel tests. ```go package user_test import ( "context" "database/sql" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var ( testClient *integresql.Client testHash string ) func TestMain(m *testing.M) { ctx := context.Background() var err error testClient, err = integresql.DefaultClientFromEnv() if err != nil { panic(err) } testHash, err = ComputeMigrationsHash("./migrations") if err != nil { panic(err) } // Setup template once for all tests err = testClient.SetupTemplateWithDBClient(ctx, testHash, func(db *sql.DB) error { return applyMigrations(db) }) if err != nil { panic(err) } os.Exit(m.Run()) } func getTestDB(t *testing.T) *sql.DB { ctx := context.Background() testDB, err := testClient.GetTestDatabase(ctx, testHash) require.NoError(t, err) db, err := sql.Open("postgres", testDB.Config.ConnectionString()) require.NoError(t, err) t.Cleanup(func() { db.Close() }) return db } func TestCreateUser(t *testing.T) { t.Parallel() // Safe to run in parallel - each test has isolated DB db := getTestDB(t) result, err := db.Exec( "INSERT INTO users (email, name) VALUES ($1, $2)", "new@example.com", "New User", ) require.NoError(t, err) rowsAffected, err := result.RowsAffected() require.NoError(t, err) assert.Equal(t, int64(1), rowsAffected) } func TestListUsers(t *testing.T) { t.Parallel() db := getTestDB(t) rows, err := db.Query("SELECT id, email, name FROM users ORDER BY id") require.NoError(t, err) defer rows.Close() var users []struct { ID int Email string Name string } for rows.Next() { var u struct { ID int Email string Name string } err := rows.Scan(&u.ID, &u.Email, &u.Name) require.NoError(t, err) users = append(users, u) } // Each test sees only the seeded data - isolated from TestCreateUser assert.Len(t, users, 2) // Only seeded users } ``` -------------------------------- ### Benchmark Report: Node.js Implementation Source: https://github.com/allaboutapps/integresql/blob/master/README.md A performance report for the previous native Node.js implementation of the storage helper strategy. ```bash # Previous Node.js implementation --- ----------------------------------- --- replicas switched: 563 avg=14ms min=6ms max=316ms replicas awaited: 1 prebuffer=8 avg=301ms max=301ms background replicas: 571 avg=-ms min=-ms max=1180ms - warm up: 32% 4041ms * drop/cache check: 4% 561ms * migrate/cache reuse: 25% 3177ms * fixtures: 2% 302ms * special: 0% 0ms * create pool: 0% 1ms - switching: 67% 8294ms * disconnect: 1% 139ms * switch slave: 4% 591ms - resolve next: 2% 290ms - await next: 2% 301ms * reinitialize: 61% 7563ms strategy related time: 12335ms vs total executed time: 11% 106184ms --- --------------------------------- --- Done in 106.60s. ``` -------------------------------- ### POST /api/v1/templates Source: https://context7.com/allaboutapps/integresql/llms.txt Initializes a new PostgreSQL template database identified by a unique hash. ```APIDOC ## POST /api/v1/templates ### Description Creates a new PostgreSQL template database identified by a unique hash. The hash should be computed from all files that affect database structure. ### Method POST ### Endpoint /api/v1/templates ### Request Body - **hash** (string) - Required - Unique hash computed from migration/fixture files ### Request Example { "hash": "abc123def456" } ### Response #### Success Response (200) - **database** (object) - Contains templateHash and connection config #### Response Example { "database": { "templateHash": "abc123def456", "config": { "host": "localhost", "port": 5432, "username": "postgres", "password": "postgres", "database": "integresql_template_abc123def456" } } } ``` -------------------------------- ### Set IntegreSQL Environment Variables Source: https://context7.com/allaboutapps/integresql/llms.txt Configure server-level settings such as address, port, and debug endpoints. ```bash # Server Configuration export INTEGRESQL_ADDRESS="" # Listen address (empty = all interfaces) export INTEGRESQL_PORT=5000 # Server port export INTEGRESQL_DEBUG_ENDPOINTS=false # Enable pprof debug endpoints at /debug/* ``` -------------------------------- ### PUT /api/v1/templates/{hash} Source: https://context7.com/allaboutapps/integresql/llms.txt Marks a template database as ready for use after migrations and fixtures have been applied. ```APIDOC ## PUT /api/v1/templates/{hash} ### Description Marks a template database as ready for use after migrations and fixtures have been applied. This triggers the creation of the initial pool of test databases. ### Method PUT ### Endpoint /api/v1/templates/{hash} ### Parameters #### Path Parameters - **hash** (string) - Required - The unique hash of the template ``` -------------------------------- ### Finalize Template Database Source: https://context7.com/allaboutapps/integresql/llms.txt Marks a template as ready for use, triggering the creation of the test database pool. ```bash # Finalize the template after applying migrations curl -X PUT http://localhost:5000/api/v1/templates/abc123def456 ``` -------------------------------- ### Configure IntegreSQL with Docker Compose Source: https://github.com/allaboutapps/integresql/blob/master/README.md Defines a service stack including the main application, IntegreSQL, and a PostgreSQL database with performance optimizations for local testing. ```yaml version: "3.4" services: # Your main service image service: depends_on: - postgres - integresql environment: PGDATABASE: &PGDATABASE "development" PGUSER: &PGUSER "dbuser" PGPASSWORD: &PGPASSWORD "9bed16f749d74a3c8bfbced18a7647f5" PGHOST: &PGHOST "postgres" PGPORT: &PGPORT "5432" PGSSLMODE: &PGSSLMODE "disable" # optional: env for integresql client testing # see https://github.com/allaboutapps/integresql-client-go # INTEGRESQL_CLIENT_BASE_URL: "http://integresql:5000/api" # [...] additional main service setup integresql: image: ghcr.io/allaboutapps/integresql: ports: - "5000:5000" depends_on: - postgres environment: PGHOST: *PGHOST PGUSER: *PGUSER PGPASSWORD: *PGPASSWORD postgres: image: postgres:12.2-alpine # should be the same version as used live # ATTENTION # fsync=off, synchronous_commit=off and full_page_writes=off # gives us a major speed up during local development and testing (~30%), # however you should NEVER use these settings in PRODUCTION unless # you want to have CORRUPTED data. # DO NOT COPY/PASTE THIS BLINDLY. # YOU HAVE BEEN WARNED. # Apply some performance improvements to pg as these guarantees are not needed while running locally command: "postgres -c 'shared_buffers=128MB' -c 'fsync=off' -c 'synchronous_commit=off' -c 'full_page_writes=off' -c 'max_connections=100' -c 'client_min_messages=warning'" expose: - "5432" ports: - "5432:5432" environment: POSTGRES_DB: *PGDATABASE POSTGRES_USER: *PGUSER POSTGRES_PASSWORD: *PGPASSWORD volumes: - pgvolume:/var/lib/postgresql/data volumes: pgvolume: # declare a named volume to persist DB data ``` -------------------------------- ### Configure IntegreSQL Environment Variables Source: https://context7.com/allaboutapps/integresql/llms.txt Set these environment variables to define PostgreSQL connections, database naming conventions, pool sizing, and logging behavior. ```bash export PGHOST="127.0.0.1" # PostgreSQL host export PGPORT=5432 # PostgreSQL port export PGUSER="postgres" # PostgreSQL username export PGPASSWORD="" # PostgreSQL password export INTEGRESQL_PGDATABASE="postgres" # Database for manager operations export INTEGRESQL_ROOT_TEMPLATE="template0" # PostgreSQL template to use # Database Naming export INTEGRESQL_DB_PREFIX="integresql" # Prefix for all managed databases export INTEGRESQL_TEMPLATE_DB_PREFIX="template" # Prefix for template databases export INTEGRESQL_TEST_DB_PREFIX="test" # Prefix for test databases # Test Database Credentials (optional, defaults to manager credentials) export INTEGRESQL_TEST_PGUSER="" # Username for test databases export INTEGRESQL_TEST_PGPASSWORD="" # Password for test databases # Pool Configuration export INTEGRESQL_TEST_INITIAL_POOL_SIZE=4 # Initial test databases per template export INTEGRESQL_TEST_MAX_POOL_SIZE=16 # Maximum test databases per template export INTEGRESQL_POOL_MAX_PARALLEL_TASKS=4 # Max parallel recreation tasks # Timing Configuration export INTEGRESQL_TEST_DB_RETRY_RECREATE_SLEEP_MIN_MS=250 # Min retry sleep export INTEGRESQL_TEST_DB_RETRY_RECREATE_SLEEP_MAX_MS=3000 # Max retry sleep export INTEGRESQL_TEST_DB_MINIMAL_LIFETIME_MS=250 # Min lifetime before FIFO recreation export INTEGRESQL_TEMPLATE_FINALIZE_TIMEOUT_MS=60000 # Template finalization timeout export INTEGRESQL_TEST_DB_GET_TIMEOUT_MS=60000 # Get test database timeout export INTEGRESQL_ECHO_REQUEST_TIMEOUT_MS=60000 # HTTP request timeout # Logging export INTEGRESQL_LOGGER_LEVEL="info" # Log level: trace, debug, info, warn, error export INTEGRESQL_LOGGER_REQUEST_LEVEL="info" # Request log level export INTEGRESQL_LOGGER_PRETTY_PRINT_CONSOLE=false # Pretty print logs (dev mode) export INTEGRESQL_LOGGER_LOG_REQUEST_BODY=false export INTEGRESQL_LOGGER_LOG_REQUEST_HEADER=false export INTEGRESQL_LOGGER_LOG_REQUEST_QUERY=false export INTEGRESQL_LOGGER_LOG_RESPONSE_BODY=false export INTEGRESQL_LOGGER_LOG_RESPONSE_HEADER=false # Echo Framework export INTEGRESQL_ECHO_DEBUG=false export INTEGRESQL_ECHO_ENABLE_CORS_MIDDLEWARE=true export INTEGRESQL_ECHO_ENABLE_LOGGER_MIDDLEWARE=true export INTEGRESQL_ECHO_ENABLE_RECOVER_MIDDLEWARE=true export INTEGRESQL_ECHO_ENABLE_REQUEST_ID_MIDDLEWARE=true export INTEGRESQL_ECHO_ENABLE_TRAILING_SLASH_MIDDLEWARE=true export INTEGRESQL_ECHO_ENABLE_REQUEST_TIMEOUT_MIDDLEWARE=true ``` -------------------------------- ### Integrate IntegreSQL with GitHub Actions Source: https://context7.com/allaboutapps/integresql/llms.txt Use this workflow configuration to run parallel tests by spinning up a PostgreSQL service and the IntegreSQL container. ```yaml name: Test on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15-alpine env: POSTGRES_USER: testuser POSTGRES_PASSWORD: testpass POSTGRES_DB: testdb ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 integresql: image: ghcr.io/allaboutapps/integresql:v1.1.0 env: PGHOST: postgres PGUSER: testuser PGPASSWORD: testpass INTEGRESQL_TEST_INITIAL_POOL_SIZE: "8" INTEGRESQL_TEST_MAX_POOL_SIZE: "32" ports: - 5000:5000 steps: - uses: actions/checkout@v4 - name: Set up Go uses: actions/setup-go@v5 with: go-version: '1.21' - name: Run tests env: INTEGRESQL_CLIENT_BASE_URL: "http://localhost:5000/api" PGHOST: localhost PGUSER: testuser PGPASSWORD: testpass run: | go test -v -race -parallel 8 ./... ``` -------------------------------- ### POST /api/v1/templates/{hash}/tests/{id}/recreate Source: https://context7.com/allaboutapps/integresql/llms.txt Manually triggers recreation of a specific test database from the template. ```APIDOC ## POST /api/v1/templates/{hash}/tests/{id}/recreate ### Description Manually triggers recreation of a specific test database from the template and returns it to the pool. ### Method POST ### Endpoint /api/v1/templates/{hash}/tests/{id}/recreate ### Parameters #### Path Parameters - **hash** (string) - Required - The unique hash of the template - **id** (integer) - Required - The ID of the test database ``` -------------------------------- ### Pull IntegreSQL Docker Image Source: https://github.com/allaboutapps/integresql/blob/master/README.md Use this command to pull the IntegreSQL Docker image from GitHub Packages. Replace `` with the desired version. ```bash docker pull ghcr.io/allaboutapps/integresql: ``` -------------------------------- ### Recreate Test Database Source: https://context7.com/allaboutapps/integresql/llms.txt Manually triggers the recreation of a test database from the template, useful after data-mutating tests. ```bash # Manually recreate a test database after a test that modified data curl -X POST http://localhost:5000/api/v1/templates/abc123def456/tests/1/recreate ``` -------------------------------- ### Manually Recreate Test Database Source: https://github.com/allaboutapps/integresql/blob/master/README.md This sequence diagram illustrates the optional manual recreation of a test database. After a test, if you wish to bypass the default FIFO auto-cleaning and immediately have a fresh database based on the template, you can use this endpoint. This is particularly useful for managing parallel testing scenarios with varying test durations. ```mermaid sequenceDiagram Note right of You: ... loop Each test Testrunner->>IntegreSQL: GetTestDatabase: GET /api/v1/templates/:hash/tests IntegreSQL-->>Testrunner: StatusOK: 200 Testrunner->>PostgreSQL: Directly connect to the test database. Note over Testrunner,PostgreSQL: Run your test code! Testrunner-xPostgreSQL: Disconnect from the test database Note over Testrunner,PostgreSQL: Your test is finished.
As you don't want to wait for FIFO autocleaning, you can manually recreate the test database. Testrunner->>IntegreSQL: RecreateTestDatabase: POST /api/v1/templates/:hash/tests/:id/recreate IntegreSQL-->>Testrunner: StatusOK: 200 end ``` -------------------------------- ### Configure IntegreSQL with Docker Compose Source: https://context7.com/allaboutapps/integresql/llms.txt Define the IntegreSQL service alongside PostgreSQL with health checks and pool management settings. ```yaml version: "3.8" services: app: build: . depends_on: integresql: condition: service_started postgres: condition: service_healthy environment: # Application database config PGHOST: postgres PGPORT: "5432" PGUSER: &pguser "appuser" PGPASSWORD: &pgpass "secretpassword" PGDATABASE: "development" PGSSLMODE: "disable" # IntegreSQL client config INTEGRESQL_CLIENT_BASE_URL: "http://integresql:5000/api" integresql: image: ghcr.io/allaboutapps/integresql:v1.1.0 ports: - "5000:5000" depends_on: postgres: condition: service_healthy environment: INTEGRESQL_PORT: "5000" PGHOST: postgres PGPORT: "5432" PGUSER: *pguser PGPASSWORD: *pgpass # Pool configuration INTEGRESQL_TEST_INITIAL_POOL_SIZE: "4" INTEGRESQL_TEST_MAX_POOL_SIZE: "16" INTEGRESQL_POOL_MAX_PARALLEL_TASKS: "4" # Timeout configuration INTEGRESQL_TEMPLATE_FINALIZE_TIMEOUT_MS: "60000" INTEGRESQL_TEST_DB_GET_TIMEOUT_MS: "60000" # Logging INTEGRESQL_LOGGER_LEVEL: "info" INTEGRESQL_LOGGER_PRETTY_PRINT_CONSOLE: "true" postgres: image: postgres:15-alpine ports: - "5432:5432" environment: POSTGRES_USER: *pguser POSTGRES_PASSWORD: *pgpass POSTGRES_DB: "development" # Performance optimizations for testing (DO NOT USE IN PRODUCTION) command: > postgres -c shared_buffers=128MB -c fsync=off -c synchronous_commit=off -c full_page_writes=off -c max_connections=200 -c client_min_messages=warning volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U appuser"] interval: 5s timeout: 5s retries: 5 volumes: pgdata: ``` -------------------------------- ### Mermaid Sequence Diagram for IntegreSQL Workflow Source: https://github.com/allaboutapps/integresql/blob/master/README.md This diagram illustrates the sequence of interactions between the test runner, IntegreSQL, and PostgreSQL during the test execution process. ```mermaid sequenceDiagram You->>Testrunner: Start tests Testrunner->>IntegreSQL: New template database IntegreSQL->>PostgreSQL: PostgreSQL-->>IntegreSQL: IntegreSQL-->>Testrunner: Testrunner->>PostgreSQL: Connect to template database, apply all migrations, seed all fixtures, ..., disconnect. PostgreSQL-->>Testrunner: Testrunner->>IntegreSQL: Finalize the template database IntegreSQL-->>Testrunner: Note over Testrunner,PostgreSQL: Your test runner can now get isolated test databases for this hash from the pool! loop Each test Testrunner->>IntegreSQL: Get test database (looks like template database) Testrunner->>PostgreSQL: Note over Testrunner,PostgreSQL: Run your test code in an isolated test database! Testrunner-xPostgreSQL: Disconnect from the test database. end ``` -------------------------------- ### POST /api/v1/templates/{hash}/tests/{id}/unlock Source: https://context7.com/allaboutapps/integresql/llms.txt Returns a test database directly to the pool without recreating it. ```APIDOC ## POST /api/v1/templates/{hash}/tests/{id}/unlock ### Description Returns a test database directly to the pool without recreating it. Use this after read-only tests where no database mutations occurred. ### Method POST ### Endpoint /api/v1/templates/{hash}/tests/{id}/unlock ### Parameters #### Path Parameters - **hash** (string) - Required - The unique hash of the template - **id** (integer) - Required - The ID of the test database ``` -------------------------------- ### Unlock Test Database Source: https://context7.com/allaboutapps/integresql/llms.txt Returns a test database to the pool without recreation, suitable for read-only test operations. ```bash # Return a test database to the pool after a read-only test curl -X POST http://localhost:5000/api/v1/templates/abc123def456/tests/1/unlock ``` -------------------------------- ### Reset All Templates via REST API Source: https://context7.com/allaboutapps/integresql/llms.txt Administrative endpoint to remove all tracked templates and test databases. Typically used for development or infrastructure resets. ```bash curl -X DELETE http://localhost:5000/api/v1/admin/templates ``` -------------------------------- ### Manually Unlock Test Database Source: https://github.com/allaboutapps/integresql/blob/master/README.md This sequence diagram shows the optional process of manually unlocking a test database after a read-only test. It returns the database directly to the pool without cleaning, making it immediately available. This is useful when no modifications were made to the database during the test. ```mermaid sequenceDiagram Note right of You: ... loop Each test Testrunner->>IntegreSQL: GetTestDatabase: GET /api/v1/templates/:hash/tests IntegreSQL-->>Testrunner: StatusOK: 200 Testrunner->>PostgreSQL: Directly connect to the test database. Note over Testrunner,PostgreSQL: Run your **readonly** test code! Testrunner-xPostgreSQL: Disconnect from the test database Note over Testrunner,PostgreSQL: Your **readonly** test is finished.
As you did not modify the test database, you can unlock it again
(immediately available in the pool again). Testrunner->>IntegreSQL: ReturnTestDatabase: POST /api/v1/templates/:hash/tests/:id/unlock
(previously and soft-deprecated DELETE /api/v1/templates/:hash/tests/:id) IntegreSQL-->>Testrunner: StatusOK: 200 end ``` -------------------------------- ### Reset All Templates (Admin) Source: https://context7.com/allaboutapps/integresql/llms.txt Removes all tracked templates and test databases. This is an administrative endpoint for cleanup operations, typically used during development or when resetting the entire test infrastructure. ```APIDOC ## DELETE /api/v1/admin/templates ### Description Removes all tracked templates and test databases. This is an administrative endpoint for cleanup operations. ### Method DELETE ### Endpoint `/api/v1/admin/templates` ### Response #### Success Response (204 No Content) - All templates and test databases removed. #### Error Response (500 Internal Server Error) - Failed to reset - check PostgreSQL connectivity. ``` -------------------------------- ### Discard Template Database via REST API Source: https://context7.com/allaboutapps/integresql/llms.txt Removes a specific template and its associated test databases. Use this for cleanup or to force recreation of a template. ```bash curl -X DELETE http://localhost:5000/api/v1/templates/abc123def456 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.