utils

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package utils provides common validation and utility functions

Package utils provides common utility functions used across the codebase.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContainsKeyword

func ContainsKeyword(sql string, keyword string) bool

ContainsKeyword checks if SQL contains a specific keyword (case-insensitive). Both sql and keyword are normalized to uppercase before comparison.

Example:

ContainsKeyword("create table foo", "CREATE") // true
ContainsKeyword("SELECT * FROM bar", "insert") // false

func ExtractAllBalancedParentheses

func ExtractAllBalancedParentheses(text string) []string

ExtractAllBalancedParentheses finds all balanced parentheses groups in the text. Returns a slice of strings, each containing a balanced parentheses group.

Example:

ExtractAllBalancedParentheses("foo(a) bar(b, c)") // ["(a)", "(b, c)"]

func ExtractBalancedParentheses

func ExtractBalancedParentheses(text string) string

ExtractBalancedParentheses extracts text within balanced parentheses from the given string. Starts from the first '(' and returns everything up to and including the matching ')'.

This is commonly used for:

  • Extracting RLS policy USING clauses
  • Extracting RLS policy WITH CHECK clauses
  • Extracting function parameters
  • Extracting composite type definitions

Example:

ExtractBalancedParentheses("USING (id = current_user_id())") // "(id = current_user_id())"
ExtractBalancedParentheses("FUNCTION foo(a INT, b INT) RETURNS") // "(a INT, b INT)"

Returns:

  • The balanced parentheses substring (including the parentheses)
  • Empty string if no balanced parentheses found

func ExtractFunctionName

func ExtractFunctionName(sql string) string

ExtractFunctionName extracts the function name from a CREATE FUNCTION statement. Handles both simple names and schema-qualified names.

Example:

ExtractFunctionName("CREATE FUNCTION auth.jwt() RETURNS ...") // "jwt"
ExtractFunctionName("CREATE OR REPLACE FUNCTION my_func() ...") // "my_func"

func ExtractIndexName

func ExtractIndexName(sql string) string

ExtractIndexName extracts the index name from a CREATE INDEX statement.

Example:

ExtractIndexName("CREATE INDEX idx_users_email ON users(email)") // "idx_users_email"
ExtractIndexName("CREATE UNIQUE INDEX CONCURRENTLY idx_pk ON t(id)") // "idx_pk"

func ExtractPolicyTargetTable

func ExtractPolicyTargetTable(sql string) string

ExtractPolicyTargetTable extracts the target table name from a CREATE POLICY statement. Pattern: CREATE POLICY ... ON [schema.]table

Example:

ExtractPolicyTargetTable("CREATE POLICY p1 ON public.users ...") // "public.users"
ExtractPolicyTargetTable("CREATE POLICY p1 ON users FOR SELECT ...") // "users"

func ExtractSchemaName

func ExtractSchemaName(sql string) string

ExtractSchemaName extracts the schema name from a CREATE SCHEMA statement.

Example:

ExtractSchemaName("CREATE SCHEMA IF NOT EXISTS auth") // "auth"
ExtractSchemaName("CREATE SCHEMA public AUTHORIZATION ...") // "public"

func ExtractTableName

func ExtractTableName(sql string) string

ExtractTableName extracts the table name from a CREATE TABLE or ALTER TABLE statement. Handles schema-qualified names and IF NOT EXISTS clauses.

Example:

ExtractTableName("CREATE TABLE public.users (...)") // "users"
ExtractTableName("CREATE TABLE IF NOT EXISTS accounts (...)") // "accounts"
ExtractTableName("ALTER TABLE users ADD COLUMN ...") // "users"

func HasBalancedParentheses

func HasBalancedParentheses(text string) bool

HasBalancedParentheses checks if the text has properly balanced parentheses. Returns true if all parentheses are balanced, false otherwise.

Example:

HasBalancedParentheses("(a (b c))") // true
HasBalancedParentheses("(a (b c)") // false

func HasClause

func HasClause(sql string, clause string) bool

HasClause checks if SQL contains a specific SQL clause (case-insensitive). Adds a space after the clause to avoid partial matches.

Example:

HasClause("CREATE TABLE users (...)", "CREATE TABLE") // true
HasClause("ALTER TABLE users ADD", "ALTER") // true
HasClause("SELECT * FROM altered", "ALTER") // false (no space after)

func HasVolatilityMarker

func HasVolatilityMarker(sql string) bool

HasVolatilityMarker checks if SQL contains a PostgreSQL function volatility marker. Returns true if IMMUTABLE, STABLE, or VOLATILE is found in the string.

Used by plugin transformation systems to avoid adding duplicate volatility markers.

func IsDDLOperation

func IsDDLOperation(op types.Operation) bool

IsDDLOperation checks if an operation is a DDL operation (CREATE, ALTER, DROP)

func IsDDLStatement

func IsDDLStatement(sql string) bool

IsDDLStatement checks if SQL is a Data Definition Language statement. Returns true for CREATE, ALTER, DROP, TRUNCATE.

func IsDMLOperation

func IsDMLOperation(op types.Operation) bool

IsDMLOperation checks if an operation is a DML operation (INSERT, UPDATE, DELETE)

func IsDMLStatement

func IsDMLStatement(sql string) bool

IsDMLStatement checks if SQL is a Data Manipulation Language statement. Returns true for INSERT, UPDATE, DELETE, SELECT.

func IsSecurityOperation

func IsSecurityOperation(op types.Operation) bool

IsSecurityOperation checks if an operation is a security operation (GRANT, REVOKE)

func IsValidCategory

func IsValidCategory(c types.Category) bool

IsValidCategory checks if a Category is valid

func IsValidObjectType

func IsValidObjectType(t types.ObjectType) bool

IsValidObjectType checks if an ObjectType is valid

func IsValidOperation

func IsValidOperation(op types.Operation) bool

IsValidOperation checks if an Operation is valid

func NormalizeObjectName

func NormalizeObjectName(name string) string

NormalizeObjectName normalizes database object names (tables, columns, functions) by converting to lowercase and trimming whitespace. This provides consistent object name comparison across the codebase.

func NormalizeSQLWhitespace

func NormalizeSQLWhitespace(sql string) string

NormalizeSQLWhitespace collapses multiple spaces into single spaces and removes leading/trailing whitespace. Using precompiled pattern for performance.

func SetDefaultLogger

func SetDefaultLogger(logger *Logger)

SetDefaultLogger sets the global default logger

func StripOutermostParentheses

func StripOutermostParentheses(text string) string

StripOutermostParentheses removes the outermost pair of parentheses if present. If the text doesn't start and end with matching parentheses, returns the original text.

Example:

StripOutermostParentheses("(id = 1)") // "id = 1"
StripOutermostParentheses("((id = 1))") // "(id = 1)"
StripOutermostParentheses("id = 1") // "id = 1"

func TrimSQLComments

func TrimSQLComments(sql string) string

TrimSQLComments removes single-line SQL comments (--) from the beginning of a string. Multi-line comments (/* */) are not handled.

Example:

TrimSQLComments("-- Comment\nCREATE TABLE") // "CREATE TABLE"
TrimSQLComments("CREATE TABLE") // "CREATE TABLE"

func ValidCategories

func ValidCategories() []types.Category

ValidCategories returns all valid Category values

func ValidObjectTypes

func ValidObjectTypes() []types.ObjectType

ValidObjectTypes returns all valid ObjectType values

func ValidOperations

func ValidOperations() []types.Operation

ValidOperations returns all valid Operation values

func ValidateCategory

func ValidateCategory(c types.Category) error

ValidateCategory returns an error if the Category is invalid

func ValidateObjectType

func ValidateObjectType(t types.ObjectType) error

ValidateObjectType returns an error if the ObjectType is invalid

func ValidateOperation

func ValidateOperation(op types.Operation) error

ValidateOperation returns an error if the Operation is invalid

Types

type LogLevel

type LogLevel int

LogLevel represents the severity of a log message

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelFatal
)

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of a log level

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is a simple structured logger for pgsquash

func GetDefaultLogger

func GetDefaultLogger() *Logger

GetDefaultLogger returns the global default logger

func NewLogger

func NewLogger(minLevel LogLevel, output io.Writer) *Logger

NewLogger creates a new logger with the specified minimum level

func (*Logger) Debug

func (l *Logger) Debug(format string, args ...any)

Debug logs a debug message

func (*Logger) Error

func (l *Logger) Error(format string, args ...any)

Error logs an error message

func (*Logger) Fatal

func (l *Logger) Fatal(format string, args ...any)

Fatal logs a fatal message Deprecated: excessive process termination. Use Error instead and handle returns.

func (*Logger) Info

func (l *Logger) Info(format string, args ...any)

Info logs an info message

func (*Logger) StandardLogger

func (l *Logger) StandardLogger(level LogLevel) *log.Logger

StandardLogger returns a stdlib log.Logger that writes to this logger

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...any)

Warn logs a warning message

func (*Logger) WithPrefix

func (l *Logger) WithPrefix(prefix string) *Logger

WithPrefix creates a new logger with a prefix

type PublicationAddTableTarget

type PublicationAddTableTarget struct {
	Publication string
	Schema      string
	Table       string
}

PublicationAddTableTarget captures the publication and relation targeted by an ALTER PUBLICATION ... ADD TABLE statement.

func ParsePublicationAddTable

func ParsePublicationAddTable(sql string) (PublicationAddTableTarget, bool)

ParsePublicationAddTable parses ALTER PUBLICATION ... ADD TABLE statements.

Supported forms include quoted identifiers, schema-qualified relations, and multiline SQL.

type WarningManager

type WarningManager struct {
	// contains filtered or unexported fields
}

WarningManager handles deduplication and categorization of warnings

func NewWarningManager

func NewWarningManager() *WarningManager

NewWarningManager creates a new warning manager

func (*WarningManager) AddRawWarning

func (wm *WarningManager) AddRawWarning(message string)

AddRawWarning adds a raw warning string and categorizes it automatically

func (*WarningManager) AddRawWarnings

func (wm *WarningManager) AddRawWarnings(messages []string)

AddRawWarnings adds multiple raw warning strings

func (*WarningManager) AddWarning

func (wm *WarningManager) AddWarning(warning *errors.StructuredError)

AddWarning adds a warning with deduplication Accepts errors.StructuredError

func (*WarningManager) Count

func (wm *WarningManager) Count() int

Count returns the total number of unique warnings

func (*WarningManager) CountBySeverity

func (wm *WarningManager) CountBySeverity() map[errors.Severity]int

CountBySeverity returns counts grouped by severity

func (*WarningManager) FormatWarnings

func (wm *WarningManager) FormatWarnings() string

FormatWarnings returns a formatted string representation of all warnings

func (*WarningManager) GetWarnings

func (wm *WarningManager) GetWarnings() []*errors.StructuredError

GetWarnings returns all warnings sorted by severity and category

func (*WarningManager) GetWarningsByCategory

func (wm *WarningManager) GetWarningsByCategory() map[errors.Category][]*errors.StructuredError

GetWarningsByCategory returns warnings grouped by category

func (*WarningManager) GetWarningsBySeverity

func (wm *WarningManager) GetWarningsBySeverity() map[errors.Severity][]*errors.StructuredError

GetWarningsBySeverity returns warnings grouped by severity

func (*WarningManager) HasCriticalWarnings

func (wm *WarningManager) HasCriticalWarnings() bool

HasCriticalWarnings returns true if any critical warnings exist

Jump to

Keyboard shortcuts

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