Overview
The Engine is the main entry point for ChameleonDB. It loads the schema from the Schema Vault, manages database connections, and provides access to query and mutation APIs.
Initialization
NewEngine()
Creates a new engine instance with automatic schema loading from the vault.
func NewEngine() (*Engine, error)
Behavior:
- Loads schema from
.chameleon/state/schema.merged.cham (or configured path)
- Verifies vault integrity before loading
- Returns error if vault is not initialized or integrity check fails
- Ready to use immediately after creation
Example:
import (
"context"
"log"
"github.com/chameleon-db/chameleondb/chameleon/pkg/engine"
)
func main() {
ctx := context.Background()
// Initialize engine (loads schema from vault)
eng, err := engine.NewEngine()
if err != nil {
log.Fatal(err)
}
defer eng.Close()
// Connect to database
config := engine.ConnectorConfig{
Host: "localhost",
Port: 5432,
Database: "mydb",
User: "postgres",
Password: "secret",
}
if err := eng.Connect(ctx, config); err != nil {
log.Fatal(err)
}
// Ready to query and mutate
users, _ := eng.Query("User").Execute(ctx)
log.Printf("Found %d users\n", users.Count())
}
Connection Management
Connect()
Establishes a connection to the PostgreSQL database.
func (e *Engine) Connect(ctx context.Context, config ConnectorConfig) error
Context for the connection operation
Database connection configuration
ConnectorConfig Fields:
Host
string
default:"localhost"
PostgreSQL server hostname
Maximum number of connections in the pool
Minimum number of connections in the pool
MaxIdleTime
time.Duration
default:"5m"
Maximum time a connection can be idle
Example with connection string:
import "os"
func connectFromEnv(eng *engine.Engine) error {
connStr := os.Getenv("DATABASE_URL")
// postgresql://user:password@host:5432/dbname
config, err := engine.ParseConnectionString(connStr)
if err != nil {
return err
}
return eng.Connect(context.Background(), config)
}
Close()
Closes the database connection pool.
Example:
eng, _ := engine.NewEngine()
defer eng.Close() // Always close when done
Ping()
Verifies the database connection is alive.
func (e *Engine) Ping(ctx context.Context) error
Example:
if err := eng.Ping(ctx); err != nil {
log.Printf("Database connection lost: %v", err)
}
IsConnected()
Returns true if the engine is connected to a database.
func (e *Engine) IsConnected() bool
Configuration
ParseConnectionString()
Parses a PostgreSQL connection URL into a ConnectorConfig.
func ParseConnectionString(connStr string) (ConnectorConfig, error)
Supported formats:
postgresql://user:password@host:port/dbname
postgres://user:password@host:port/dbname
Example:
config, err := engine.ParseConnectionString(
"postgresql://admin:secret@db.example.com:5432/production",
)
if err != nil {
log.Fatal(err)
}
eng.Connect(ctx, config)
DefaultConfig()
Returns sensible default configuration values.
func DefaultConfig() ConnectorConfig
Returns:
ConnectorConfig{
Host: "localhost",
Port: 5432,
Database: "chameleon",
User: "postgres",
Password: "",
MaxConns: 10,
MinConns: 2,
MaxIdleTime: 5 * time.Minute,
}
Schema Access
GetSchema()
Returns the currently loaded schema.
func (e *Engine) GetSchema() *Schema
Example:
schema := eng.GetSchema()
for _, entity := range schema.Entities {
log.Printf("Entity: %s\n", entity.Name)
}
Version()
Returns the ChameleonDB engine version.
func (e *Engine) Version() string
Example:
log.Printf("ChameleonDB version: %s\n", eng.Version())
Debug Mode
WithDebug()
Enables debug output for all operations.
func (e *Engine) WithDebug(level DebugLevel) *Engine
Debug Levels:
No debug output (default)
Show generated SQL queries
Show SQL + execution time + row counts
Show SQL + EXPLAIN output (future)
Example:
import "github.com/chameleon-db/chameleondb/chameleon/pkg/engine"
eng := engine.NewEngine()
eng.WithDebug(engine.DebugTrace)
// All queries now show debug output
eng.Query("User").Execute(ctx)
// Output:
// [SQL]
// SELECT * FROM users
//
// [TRACE] Query on User: 2.3ms, 5 rows
Environment variable:
# Enable SQL debug
export CHAMELEON_DEBUG=1
# Enable full trace
export CHAMELEON_DEBUG=trace
# Enable EXPLAIN (future)
export CHAMELEON_DEBUG=explain
Error Handling
Common Errors
The Schema Vault hasn’t been initialized. Run chameleon init first.
Schema vault has been tampered with. Run chameleon verify to investigate.
Attempted to query/mutate without calling Connect() first.
Example error handling:
eng, err := engine.NewEngine()
if err != nil {
if strings.Contains(err.Error(), "vault not initialized") {
log.Fatal("Run 'chameleon init' to initialize the vault")
}
if strings.Contains(err.Error(), "integrity check failed") {
log.Fatal("Schema integrity violation detected")
}
log.Fatal(err)
}
Complete Example
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/chameleon-db/chameleondb/chameleon/pkg/engine"
)
func main() {
ctx := context.Background()
// 1. Initialize engine
eng, err := engine.NewEngine()
if err != nil {
log.Fatalf("Failed to initialize engine: %v", err)
}
defer eng.Close()
// 2. Connect to database
connStr := os.Getenv("DATABASE_URL")
config, err := engine.ParseConnectionString(connStr)
if err != nil {
log.Fatalf("Invalid connection string: %v", err)
}
if err := eng.Connect(ctx, config); err != nil {
log.Fatalf("Failed to connect: %v", err)
}
// 3. Verify connection
if err := eng.Ping(ctx); err != nil {
log.Fatalf("Database not responding: %v", err)
}
fmt.Printf("Connected to ChameleonDB %s\n", eng.Version())
// 4. Ready to use
users, err := eng.Query("User").Execute(ctx)
if err != nil {
log.Fatalf("Query failed: %v", err)
}
fmt.Printf("Found %d users\n", users.Count())
}
See Also