database

package
v0.42.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package database defines supported database engines and their container configurations for one-click local provisioning via devx db spawn.

Index

Constants

This section is empty.

Variables

View Source
var CannedQueries = map[string]CannedQuery{
	"sizes": {
		Name:        "sizes",
		Description: "Table sizes and row counts",
		SQL: map[string]string{
			"postgres": `SELECT
	schemaname || '.' || relname AS "table",
	pg_size_pretty(pg_total_relation_size(relid)) AS "total_size",
	n_live_tup AS "estimated_rows"
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC;`,
			"mysql": `SELECT
	table_name AS 'table',
	CONCAT(ROUND(data_length / 1024, 2), ' KB') AS 'data_size',
	table_rows AS 'estimated_rows'
FROM information_schema.tables
WHERE table_schema = DATABASE()
ORDER BY data_length DESC;`,
		},
	},
	"recent": {
		Name:        "recent",
		Description: "Last 10 rows from each user table",
		SQL: map[string]string{

			"postgres": `SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name;`,
			"mysql": `SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
ORDER BY table_name;`,
		},
	},
	"missing-indexes": {
		Name:        "missing-indexes",
		Description: "Tables with no non-primary indexes (potential performance risk)",
		SQL: map[string]string{
			"postgres": `SELECT
	t.tablename AS "table",
	COALESCE(idx.index_count, 0) AS "index_count",
	CASE WHEN COALESCE(idx.index_count, 0) = 0
		THEN '⚠️  No indexes'
		ELSE '✓'
	END AS "status"
FROM pg_tables t
LEFT JOIN (
	SELECT tablename, COUNT(*) AS index_count
	FROM pg_indexes
	WHERE schemaname = 'public'
	GROUP BY tablename
) idx ON t.tablename = idx.tablename
WHERE t.schemaname = 'public'
ORDER BY COALESCE(idx.index_count, 0) ASC, t.tablename;`,
			"mysql": `SELECT
	t.table_name AS 'table',
	COALESCE(idx.index_count, 0) AS 'index_count',
	CASE WHEN COALESCE(idx.index_count, 0) = 0
		THEN 'No indexes'
		ELSE 'OK'
	END AS 'status'
FROM information_schema.tables t
LEFT JOIN (
	SELECT table_name, COUNT(DISTINCT index_name) AS index_count
	FROM information_schema.statistics
	WHERE table_schema = DATABASE()
	GROUP BY table_name
) idx ON t.table_name = idx.table_name
WHERE t.table_schema = DATABASE()
ORDER BY COALESCE(idx.index_count, 0) ASC, t.table_name;`,
		},
	},
	"nulls": {
		Name:        "nulls",
		Description: "Columns with high NULL ratios for a specific table",
		SQL: map[string]string{

			"postgres": `SELECT
	attname AS "column",
	n_live_tup AS "total_rows",
	null_frac AS "null_ratio",
	CASE
		WHEN null_frac > 0.5 THEN '⚠️  >50%% NULLs'
		WHEN null_frac > 0.1 THEN '~' || ROUND(null_frac * 100) || '%%'
		ELSE '✓ low'
	END AS "status"
FROM pg_stats
WHERE schemaname = 'public' AND tablename = '%s'
ORDER BY null_frac DESC;`,
			"mysql": `SELECT
	column_name AS 'column',
	is_nullable AS 'nullable',
	column_type AS 'type',
	column_default AS 'default_value'
FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = '%s'
ORDER BY ordinal_position;`,
		},
	},
}

CannedQueries is the registry of built-in diagnostic queries.

View Source
var Registry = map[string]Engine{
	"postgres": {
		Name:         "PostgreSQL",
		Image:        "docker.io/library/postgres:16-alpine",
		DefaultPort:  5432,
		InternalPort: 5432,
		VolumePath:   "/var/lib/postgresql/data",
		Env: map[string]string{
			"POSTGRES_USER":     "devx",
			"POSTGRES_PASSWORD": "devx",
			"POSTGRES_DB":       "devx",
		},
		ReadyLog:      "database system is ready to accept connections",
		ConnStringFmt: "postgresql://%s:%s@localhost:%d/%s",
	},
	"redis": {
		Name:          "Redis",
		Image:         "docker.io/library/redis:7-alpine",
		DefaultPort:   6379,
		InternalPort:  6379,
		VolumePath:    "/data",
		Env:           map[string]string{},
		ReadyLog:      "Ready to accept connections",
		ConnStringFmt: "redis://localhost:%d",
	},
	"mysql": {
		Name:         "MySQL",
		Image:        "docker.io/library/mysql:8",
		DefaultPort:  3306,
		InternalPort: 3306,
		VolumePath:   "/var/lib/mysql",
		Env: map[string]string{
			"MYSQL_ROOT_PASSWORD": "devx",
			"MYSQL_DATABASE":      "devx",
			"MYSQL_USER":          "devx",
			"MYSQL_PASSWORD":      "devx",
		},
		ReadyLog:      "ready for connections",
		ConnStringFmt: "mysql://%s:%s@localhost:%d/%s",
	},
	"mongo": {
		Name:         "MongoDB",
		Image:        "docker.io/library/mongo:7",
		DefaultPort:  27017,
		InternalPort: 27017,
		VolumePath:   "/data/db",
		Env: map[string]string{
			"MONGO_INITDB_ROOT_USERNAME": "devx",
			"MONGO_INITDB_ROOT_PASSWORD": "devx",
		},
		ReadyLog:      "Waiting for connections",
		ConnStringFmt: "mongodb://%s:%s@localhost:%d",
	},
}

Registry of all supported database engines.

Functions

func DeleteSnapshot added in v0.18.0

func DeleteSnapshot(engine, snapshotName string) error

DeleteSnapshot removes a snapshot's tar and metadata files.

func ExtractSchema added in v0.39.0

func ExtractSchema(runtime, engineName string) (string, error)

ExtractSchema extracts the DDL (schema-only) from a running devx database container. For PostgreSQL, it uses pg_dump -s. For MySQL, it uses mysqldump --no-data.

func IsSynthesizable added in v0.39.0

func IsSynthesizable(engine string) bool

IsSynthesizable checks if an engine supports schema extraction.

func PipeSQL added in v0.39.0

func PipeSQL(runtime, engineName, sql string) error

PipeSQL pipes raw SQL into a running devx database container via stdin.

func RenderTable added in v0.42.0

func RenderTable(result *QueryResult) string

RenderTable prints query results as a styled terminal table.

func RestoreSnapshot added in v0.18.0

func RestoreSnapshot(rt provider.ContainerRuntime, engine, snapshotName string) error

func SanitizeLLMSQL added in v0.39.0

func SanitizeLLMSQL(raw string) string

SanitizeLLMSQL strips markdown code block wrappers from LLM output and ensures the SQL is wrapped in a transaction if not already.

func SnapshotDir added in v0.18.0

func SnapshotDir() string

SnapshotDir returns the directory where snapshots are stored.

func SupportedEngines

func SupportedEngines() []string

SupportedEngines returns a sorted list of engine names.

func SynthesizableEngines added in v0.39.0

func SynthesizableEngines() []string

SynthesizableEngines returns the list of engines that support DDL extraction for AI-driven synthetic data generation.

Types

type CannedQuery added in v0.42.0

type CannedQuery struct {
	Name        string            // Short name for the query (e.g., "sizes")
	Description string            // Human-readable description
	SQL         map[string]string // Engine-specific SQL (keyed by engine name)
}

CannedQuery defines a pre-built diagnostic query.

type Engine

type Engine struct {
	Name          string            // Human-readable name
	Image         string            // Container image
	DefaultPort   int               // Default port on the host
	InternalPort  int               // Port inside the container
	VolumePath    string            // Data directory inside the container
	Env           map[string]string // Default environment variables
	ReadyLog      string            // Log line that indicates the DB is ready
	ConnStringFmt string            // printf format for the connection string: host, port, user, pass, dbname
}

Engine holds the container configuration for a database engine.

func (Engine) ConnString

func (e Engine) ConnString(port int) string

ConnString returns the formatted connection string for a given engine.

type QueryResult added in v0.42.0

type QueryResult struct {
	Headers []string   // Column names
	Rows    [][]string // Row data
	SQL     string     // The SQL that was executed
}

QueryResult holds the output of an executed SQL query.

func ExecuteQuery added in v0.42.0

func ExecuteQuery(runtime, engineName, sql string, readOnly bool) (*QueryResult, error)

ExecuteQuery runs a SQL query against a running devx database container. If readOnly is true, the query is wrapped in a read-only transaction.

func ExecuteReadOnlyQuery added in v0.42.0

func ExecuteReadOnlyQuery(runtime, engineName, sql string) (*QueryResult, error)

ExecuteReadOnlyQuery runs a SQL query inside a read-only transaction against a running devx database container and returns the parsed results.

type SnapshotMeta added in v0.18.0

type SnapshotMeta struct {
	Name      string    `json:"name"`
	Engine    string    `json:"engine"`
	Volume    string    `json:"volume"`
	CreatedAt time.Time `json:"created_at"`
	SizeBytes int64     `json:"size_bytes"`
}

SnapshotMeta holds metadata about a database snapshot.

func CreateSnapshot added in v0.18.0

func CreateSnapshot(rt provider.ContainerRuntime, engine, snapshotName string) (*SnapshotMeta, error)

CreateSnapshot exports the named volume for the given engine into a tar archive. It uses the container runtime (podman, docker, nerdctl).

func ListSnapshots added in v0.18.0

func ListSnapshots(engine string) ([]SnapshotMeta, error)

ListSnapshots returns all snapshots for a given engine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL