Newer
Older
EnvoyControlPlane / internal / pkg / storage / strategy.go
package storage

import (
	"database/sql"
	"errors"
	"fmt"
	"strings"
)

// =============================================================================
// I. STRATEGY INTERFACE & FACTORY
// =============================================================================

// SQLStrategy abstracts all database-specific SQL generation and logic.
// This is the core of the Strategy Pattern implementation.
type SQLStrategy interface {
	DriverName() string
	// Placeholder returns the correct placeholder string for the nth argument (e.g., $1 or ?).
	Placeholder(n int) string
	InitSchemaSQL() string

	// Save methods: Generate the full INSERT/UPDATE query using the provided placeholders.
	SaveCertificateSQL(placeholders []string) string
	SaveSecretSQL(placeholders []string) string
	SaveClusterSQL(placeholders []string) string
	SaveListenerSQL(placeholders []string) string
	SaveExtensionConfigSQL(placeholders []string) string

	// Dialect-specific functions (e.g., now() vs CURRENT_TIMESTAMP)
	GetTimeNow() string
	GetTrueValue() string
	GetFalseValue() string

	// Dump/Restore Logic
	DumpSelectFields(table string) string
	ScanRawRow(rows *sql.Rows, row *RawRow, table string) error
	RestoreRawRowSQL(table string) string
	ClearTableSQL(table string) string
}

// NewSQLStrategy is the factory function to create the correct strategy implementation.
func NewSQLStrategy(driver string) (SQLStrategy, error) {
	switch strings.ToLower(driver) {
	case "postgres":
		return &PostgresStrategy{}, nil
	case "sqlite", "sqlite3":
		return &SQLiteStrategy{}, nil
	// Add support for new databases here!
	case "mysql":
		return nil, errors.New("MySQL strategy not yet implemented")
	default:
		return nil, fmt.Errorf("unsupported database driver: %s", driver)
	}
}