storage

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: GPL-3.0 Imports: 7 Imported by: 0

Documentation

Overview

Package storage provides abstractions for the data access layer. It allows transpiled business logic to work with different backends: gRPC (DSL), PostgreSQL, MySQL, SQLite, SQL Server, or mocks.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound      = &RepositoryError{Op: "find", Err: errNotFound}
	ErrAlreadyExists = &RepositoryError{Op: "create", Err: errAlreadyExists}
	ErrInvalidInput  = &RepositoryError{Op: "validate", Err: errInvalidInput}
)

Common errors

Functions

func GenerateMethodName

func GenerateMethodName(pattern SelectPattern, info *SelectInfo) string

GenerateMethodName creates a repository method name from a SELECT pattern.

Types

type BackendCapabilities

type BackendCapabilities struct {
	// Supports transactions (Begin/Commit/Rollback)
	SupportsTransactions bool

	// Supports batch operations
	SupportsBatch bool

	// Supports streaming results
	SupportsStreaming bool

	// Supports prepared statements / query caching
	SupportsPrepared bool

	// Supports schema generation
	SupportsSchemaGen bool

	// Supports seed data generation
	SupportsSeedGen bool

	// Requires external dependencies (e.g., proto files for gRPC)
	RequiresExternalDeps bool
	ExternalDepTypes     []string // e.g., ["proto"]
}

BackendCapabilities describes what a backend supports.

type BackendConfig

type BackendConfig struct {
	Type      BackendType
	OutputDir string
	Package   string

	// For gRPC backend
	ProtoFiles   []string
	ProtoPackage string

	// For SQL backends
	ConnectionString string

	// Generation options
	GenerateSchema bool
	GenerateSeed   bool
	GenerateMocks  bool
	GenerateTests  bool
}

BackendConfig holds configuration for a backend generator.

type BackendGenerator

type BackendGenerator interface {
	// Name returns the backend identifier.
	Name() BackendType

	// Generate produces repository implementation files.
	Generate(ctx context.Context, spec *GenerationSpec) error
}

BackendGenerator is implemented by each backend to generate code.

type BackendType

type BackendType string

BackendType identifies the storage backend.

const (
	BackendGRPC      BackendType = "grpc"
	BackendPostgres  BackendType = "postgres"
	BackendMySQL     BackendType = "mysql"
	BackendSQLite    BackendType = "sqlite"
	BackendSQLServer BackendType = "sqlserver"
	BackendOracle    BackendType = "oracle"
	BackendMock      BackendType = "mock"
)

type BaseBackendGenerator

type BaseBackendGenerator struct {
	Config BackendConfig
}

BaseBackendGenerator provides common functionality for backend generators.

func (*BaseBackendGenerator) GenerateFileHeader

func (g *BaseBackendGenerator) GenerateFileHeader(w io.Writer, pkg string) error

GenerateFileHeader generates common file header.

type DMLTableStrategy

type DMLTableStrategy struct{}

func (*DMLTableStrategy) Match

func (s *DMLTableStrategy) Match(method *ProtoMethodInfo, proc *Procedure, ctx *MatchContext) *StrategyResult

func (*DMLTableStrategy) Name

func (s *DMLTableStrategy) Name() string

type DeleteInfo

type DeleteInfo struct {
	Table TableRef

	// WHERE clause
	WhereFields []WhereField

	// FROM clause (for DELETE ... FROM with JOINs)
	FromTables []TableRef
	Joins      []JoinInfo

	// OUTPUT clause
	OutputColumns []string
}

DeleteInfo contains parsed information from a DELETE statement.

type DeleteJoinStyle

type DeleteJoinStyle int

DeleteJoinStyle describes how a dialect handles DELETE with JOIN.

const (
	DeleteJoinNotSupported DeleteJoinStyle = iota // Must use subquery
	DeleteJoinFromClause                          // DELETE t FROM t JOIN o (SQL Server, MySQL)
	DeleteJoinUsing                               // DELETE FROM t USING o WHERE ... (PostgreSQL)
)

type DetectionError

type DetectionError struct {
	Procedure string
	Line      int
	Message   string
	SQL       string
	Err       error
}

DetectionError is a fatal issue for a specific operation.

type DetectionResult

type DetectionResult struct {
	// Source info
	Procedures []ProcedureInfo

	// Extracted data
	Operations   []Operation
	Models       []Model
	Repositories []Repository

	// Issues encountered during detection
	Warnings []DetectionWarning
	Errors   []DetectionError
}

DetectionResult contains all information extracted from procedures.

type DetectionWarning

type DetectionWarning struct {
	Procedure string
	Line      int
	Message   string
	SQL       string // Relevant SQL snippet
}

DetectionWarning is a non-fatal issue during detection.

type Detector

type Detector interface {
	// DetectOperations scans a procedure and returns all data operations found.
	// The proc parameter should be *ast.CreateProcedure from tsqlparser.
	DetectOperations(proc interface{}) ([]Operation, error)

	// DetectModels infers models from detected operations.
	DetectModels(ops []Operation) ([]Model, error)

	// DetectRepositories generates repository specs from operations and models.
	DetectRepositories(ops []Operation, models []Model) ([]Repository, error)
}

Detector analyzes T-SQL AST to extract data operations. The proc parameter is *ast.CreateProcedure from tsqlparser.

type DetectorConfig

type DetectorConfig struct {
	// Include operations that can't be fully parsed (as best-effort)
	IncludePartial bool

	// Track raw SQL for each operation (for debugging/reference)
	IncludeRawSQL bool

	// Infer optionality from SQL patterns (e.g., LEFT JOIN -> optional)
	InferOptionality bool
}

DetectorConfig configures the detector behavior.

type EnsembleMapper

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

EnsembleMapper uses multiple strategies to map proto methods to procedures.

func NewEnsembleMapper

func NewEnsembleMapper(proto *ProtoParseResult, procedures []*Procedure) *EnsembleMapper

NewEnsembleMapper creates a mapper with all available strategies.

func (*EnsembleMapper) GetStats

func (m *EnsembleMapper) GetStats() MappingStats

GetStats returns mapping statistics.

func (*EnsembleMapper) MapAll

func (m *EnsembleMapper) MapAll() map[string]*MethodMapping

MapAll maps all proto methods using ensemble of strategies.

type ExecInfo

type ExecInfo struct {
	Procedure  string
	Schema     string
	Parameters []ExecParam
	ResultVar  string // Variable for EXEC @result = proc
}

ExecInfo contains parsed information from an EXEC/EXECUTE statement.

type ExecParam

type ExecParam struct {
	Name     string // Parameter name (if named)
	Position int    // Position (if positional)
	Variable string // Variable being passed
	Literal  string // Literal value
	IsOutput bool   // OUTPUT keyword
}

ExecParam describes a parameter in EXEC call.

type Field

type Field struct {
	// SQL metadata
	Name    string // SQL column name (e.g., "currency_code")
	SQLType string // Original SQL type (e.g., "VARCHAR(50)")

	// Go mapping
	GoName string // Go field name in PascalCase (e.g., "CurrencyCode")
	GoType string // Go type (e.g., "string", "*string", "int32", "decimal.Decimal")

	// Optionality
	Optionality Optionality

	// Proto mapping (for gRPC backend)
	ProtoField  string // Proto field name (e.g., "currency_code")
	ProtoNumber int    // Proto field number

	// Context
	IsKey      bool   // Is this field part of a key/WHERE clause?
	IsAssigned bool   // Is this field being assigned to a variable?
	Variable   string // T-SQL variable being assigned (e.g., "@CurrencyCode")
}

Field describes a field/column in a data operation.

type FieldMapping

type FieldMapping struct {
	ColumnName  string // SQL column name
	ColumnIndex int    // Position in result set
	ProtoField  string // Field name in response message
	ProtoType   string // Proto type
	GoType      string // Go type
}

FieldMapping maps a result column to a response field.

type GenerationOutput

type GenerationOutput struct {
	Files []OutputFile

	// For post-generation steps
	Commands []string // e.g., "go mod tidy", "go generate"
}

GenerationOutput is the result of a generation run.

type GenerationSpec

type GenerationSpec struct {
	// Source info
	SourceFiles []string // Original .sql files

	// Detected operations
	Operations []Operation

	// Generated models
	Models []Model

	// Generated repositories
	Repositories []Repository

	// Proto info (for gRPC backend)
	ProtoServices []ProtoServiceInfo

	// SQL to Proto mappings (for gRPC backend)
	ProtoMappings []SQLToProtoMapping

	// Configuration
	Config BackendConfig
}

GenerationSpec contains everything needed to generate backend code.

type Generator

type Generator interface {
	// GenerateInterfaces generates the repository interfaces (common for all backends).
	GenerateInterfaces(ctx context.Context, spec *GenerationSpec, w io.Writer) error

	// GenerateModels generates the model structs (common for all backends).
	GenerateModels(ctx context.Context, spec *GenerationSpec, w io.Writer) error

	// GenerateBackend generates backend-specific implementation.
	GenerateBackend(ctx context.Context, spec *GenerationSpec, backend BackendGenerator) error
}

Generator is the main interface for generating storage layer code.

type InsertInfo

type InsertInfo struct {
	Table   TableRef
	Columns []string

	// VALUES clause
	Values []InsertValue

	// SELECT clause (INSERT ... SELECT)
	SelectSource *SelectInfo

	// OUTPUT clause
	OutputColumns []string
	OutputInto    string // Variable or table
}

InsertInfo contains parsed information from an INSERT statement.

type InsertValue

type InsertValue struct {
	Column    string
	Variable  string // T-SQL variable
	Literal   string // Literal value
	IsDefault bool   // DEFAULT keyword
}

InsertValue describes a value in INSERT VALUES clause.

type JoinInfo

type JoinInfo struct {
	Type       string // INNER, LEFT, RIGHT, FULL, CROSS
	Table      TableRef
	OnLeft     string // Left side of ON condition
	OnRight    string // Right side of ON condition
	IsOptional bool   // LEFT/RIGHT/FULL joins produce optional results
}

JoinInfo describes a JOIN in a SELECT.

type MappingStats

type MappingStats struct {
	TotalMethods     int
	MappedMethods    int
	UnmappedMethods  int
	HighConfidence   int // > 0.8
	MediumConfidence int // 0.5 - 0.8
	LowConfidence    int // < 0.5
	ByService        map[string]ServiceMappingStats
}

MappingStats returns statistics about the mapping results.

type MatchContext

type MatchContext struct {
	ServiceName   string
	AllMessages   map[string]*ProtoMessageInfo
	AllProcedures []*Procedure
}

MatchContext provides shared context for all strategies.

type MatchStrategy

type MatchStrategy interface {
	Name() string
	Match(method *ProtoMethodInfo, proc *Procedure, context *MatchContext) *StrategyResult
}

MatchStrategy represents a single matching strategy.

type MethodMapping

type MethodMapping struct {
	ServiceName   string
	MethodName    string
	Procedure     *Procedure
	ParamMappings []ParamMapping
	ResultMapping *ResultMapping
	Confidence    float64 // 0.0 - 1.0 confidence score
	MatchReason   string  // Why this match was made
}

MethodMapping represents a mapping between a proto method and a stored procedure.

type MethodTemplate

type MethodTemplate struct {
	// Method signature
	Name     string
	Receiver string
	Params   []ParamTemplate
	Returns  []string

	// Implementation details
	Operation Operation
	Pattern   SelectPattern

	// SQL backend
	SQL        string   // Generated SQL
	ScanFields []string // Fields to scan into

	// gRPC backend
	GRPCMethod      string // Proto method name
	RequestMapping  map[string]string
	ResponseMapping map[string]string
}

MethodTemplate is data for generating a single method.

type Model

type Model struct {
	Name       string // Go struct name (e.g., "Currency")
	Table      string // Source table name
	Fields     []Field
	PrimaryKey []Field // Primary key fields
}

Model describes a generated Go struct for an entity.

type MySQLDialect

type MySQLDialect struct{}

MySQLDialect implements SQLDialect for MySQL/MariaDB.

func (MySQLDialect) BooleanLiteral

func (d MySQLDialect) BooleanLiteral(b bool) string

func (MySQLDialect) ConnectionStringFormat

func (d MySQLDialect) ConnectionStringFormat() string

func (MySQLDialect) DeleteJoinSyntax

func (d MySQLDialect) DeleteJoinSyntax() DeleteJoinStyle

func (MySQLDialect) DriverName

func (d MySQLDialect) DriverName() string

func (MySQLDialect) LastInsertIDMethod

func (d MySQLDialect) LastInsertIDMethod() string

func (MySQLDialect) LimitClause

func (d MySQLDialect) LimitClause(n int) string

func (MySQLDialect) LimitPosition

func (d MySQLDialect) LimitPosition() string

func (MySQLDialect) Name

func (d MySQLDialect) Name() string

func (MySQLDialect) NeedsFromDual

func (d MySQLDialect) NeedsFromDual() bool

func (MySQLDialect) NullSafeEqual

func (d MySQLDialect) NullSafeEqual(left, right string) string

func (MySQLDialect) OffsetFetchClause

func (d MySQLDialect) OffsetFetchClause(offset, limit int) string

func (MySQLDialect) Placeholder

func (d MySQLDialect) Placeholder(n int) string

func (MySQLDialect) QuoteIdentifier

func (d MySQLDialect) QuoteIdentifier(name string) string

func (MySQLDialect) StringConcat

func (d MySQLDialect) StringConcat(parts ...string) string

func (MySQLDialect) SupportsOutputClause

func (d MySQLDialect) SupportsOutputClause() bool

func (MySQLDialect) SupportsReturning

func (d MySQLDialect) SupportsReturning() bool

func (MySQLDialect) SupportsTableAliasAS

func (d MySQLDialect) SupportsTableAliasAS() bool

func (MySQLDialect) TableAlias

func (d MySQLDialect) TableAlias(table, alias string) string

func (MySQLDialect) TypeMapping

func (d MySQLDialect) TypeMapping(goType string) string

func (MySQLDialect) UpdateJoinSyntax

func (d MySQLDialect) UpdateJoinSyntax() UpdateJoinStyle

func (MySQLDialect) UpsertSyntax

func (d MySQLDialect) UpsertSyntax() UpsertStyle

type NamingConventionStrategy

type NamingConventionStrategy struct{}

func (*NamingConventionStrategy) Match

func (*NamingConventionStrategy) Name

func (s *NamingConventionStrategy) Name() string

type Operation

type Operation struct {
	// Operation details
	Type  OperationType
	Table string // Primary table name
	Alias string // Table alias (if used)

	// Fields involved
	Fields    []Field // SELECT columns or INSERT/UPDATE fields
	KeyFields []Field // WHERE clause fields

	// For INSERT with OUTPUT or SELECT INTO
	OutputFields []Field

	// Source tracking
	Procedure string // Source stored procedure name
	Line      int    // Line number in source SQL
	RawSQL    string // Original SQL statement (for reference)

	// For EXEC operations
	CalledProcedure string  // Name of called procedure
	Parameters      []Field // Parameters passed to called procedure
}

Operation describes a data operation detected in a stored procedure.

type OperationType

type OperationType int

OperationType represents the type of SQL operation detected.

const (
	OpSelect   OperationType = iota // SELECT statement
	OpInsert                        // INSERT statement
	OpUpdate                        // UPDATE statement
	OpDelete                        // DELETE statement
	OpExec                          // EXEC/EXECUTE (call another procedure)
	OpTruncate                      // TRUNCATE TABLE statement
)

func (OperationType) String

func (o OperationType) String() string

type Optionality

type Optionality int

Optionality indicates whether a field is required, optional, or computed.

const (
	Required Optionality = iota // Field must have a value (NOT NULL)
	Optional                    // Field may be nil/NULL
	Computed                    // Field is generated by DB (auto-increment, default, etc.)
)

func (Optionality) String

func (o Optionality) String() string

type OracleDialect

type OracleDialect struct{}

OracleDialect implements SQLDialect for Oracle Database.

func (OracleDialect) BooleanLiteral

func (d OracleDialect) BooleanLiteral(b bool) string

func (OracleDialect) ConnectionStringFormat

func (d OracleDialect) ConnectionStringFormat() string

func (OracleDialect) DeleteJoinSyntax

func (d OracleDialect) DeleteJoinSyntax() DeleteJoinStyle

func (OracleDialect) DriverName

func (d OracleDialect) DriverName() string

func (OracleDialect) LastInsertIDMethod

func (d OracleDialect) LastInsertIDMethod() string

func (OracleDialect) LimitClause

func (d OracleDialect) LimitClause(n int) string

func (OracleDialect) LimitPosition

func (d OracleDialect) LimitPosition() string

func (OracleDialect) Name

func (d OracleDialect) Name() string

func (OracleDialect) NeedsFromDual

func (d OracleDialect) NeedsFromDual() bool

func (OracleDialect) NullSafeEqual

func (d OracleDialect) NullSafeEqual(left, right string) string

func (OracleDialect) OffsetFetchClause

func (d OracleDialect) OffsetFetchClause(offset, limit int) string

func (OracleDialect) Placeholder

func (d OracleDialect) Placeholder(n int) string

func (OracleDialect) QuoteIdentifier

func (d OracleDialect) QuoteIdentifier(name string) string

func (OracleDialect) StringConcat

func (d OracleDialect) StringConcat(parts ...string) string

func (OracleDialect) SupportsOutputClause

func (d OracleDialect) SupportsOutputClause() bool

func (OracleDialect) SupportsReturning

func (d OracleDialect) SupportsReturning() bool

func (OracleDialect) SupportsTableAliasAS

func (d OracleDialect) SupportsTableAliasAS() bool

func (OracleDialect) TableAlias

func (d OracleDialect) TableAlias(table, alias string) string

func (OracleDialect) TypeMapping

func (d OracleDialect) TypeMapping(goType string) string

func (OracleDialect) UpdateJoinSyntax

func (d OracleDialect) UpdateJoinSyntax() UpdateJoinStyle

func (OracleDialect) UpsertSyntax

func (d OracleDialect) UpsertSyntax() UpsertStyle

type OutputFile

type OutputFile struct {
	Path    string
	Content []byte
	Mode    int // File mode (e.g., 0644)
}

OutputFile describes a file to be generated.

type ParamMapping

type ParamMapping struct {
	ProtoField string // Field name in request message
	ProtoType  string // Proto type
	ProcParam  string // Parameter name in procedure (without @)
	ProcType   string // SQL type
	GoType     string // Go type to use
	IsOptional bool   // Proto field is optional
	HasDefault bool   // Proc param has default
}

ParamMapping maps a proto request field to a procedure parameter.

type ParamTemplate

type ParamTemplate struct {
	Name string
	Type string
}

ParamTemplate describes a method parameter.

type ParameterSignatureStrategy

type ParameterSignatureStrategy struct{}

func (*ParameterSignatureStrategy) Match

func (*ParameterSignatureStrategy) Name

type PostgresDialect

type PostgresDialect struct{}

PostgresDialect implements SQLDialect for PostgreSQL.

func (PostgresDialect) BooleanLiteral

func (d PostgresDialect) BooleanLiteral(b bool) string

func (PostgresDialect) ConnectionStringFormat

func (d PostgresDialect) ConnectionStringFormat() string

func (PostgresDialect) DeleteJoinSyntax

func (d PostgresDialect) DeleteJoinSyntax() DeleteJoinStyle

func (PostgresDialect) DriverName

func (d PostgresDialect) DriverName() string

func (PostgresDialect) LastInsertIDMethod

func (d PostgresDialect) LastInsertIDMethod() string

func (PostgresDialect) LimitClause

func (d PostgresDialect) LimitClause(n int) string

func (PostgresDialect) LimitPosition

func (d PostgresDialect) LimitPosition() string

func (PostgresDialect) Name

func (d PostgresDialect) Name() string

func (PostgresDialect) NeedsFromDual

func (d PostgresDialect) NeedsFromDual() bool

func (PostgresDialect) NullSafeEqual

func (d PostgresDialect) NullSafeEqual(left, right string) string

func (PostgresDialect) OffsetFetchClause

func (d PostgresDialect) OffsetFetchClause(offset, limit int) string

func (PostgresDialect) Placeholder

func (d PostgresDialect) Placeholder(n int) string

func (PostgresDialect) QuoteIdentifier

func (d PostgresDialect) QuoteIdentifier(name string) string

func (PostgresDialect) StringConcat

func (d PostgresDialect) StringConcat(parts ...string) string

func (PostgresDialect) SupportsOutputClause

func (d PostgresDialect) SupportsOutputClause() bool

func (PostgresDialect) SupportsReturning

func (d PostgresDialect) SupportsReturning() bool

func (PostgresDialect) SupportsTableAliasAS

func (d PostgresDialect) SupportsTableAliasAS() bool

func (PostgresDialect) TableAlias

func (d PostgresDialect) TableAlias(table, alias string) string

func (PostgresDialect) TypeMapping

func (d PostgresDialect) TypeMapping(goType string) string

func (PostgresDialect) UpdateJoinSyntax

func (d PostgresDialect) UpdateJoinSyntax() UpdateJoinStyle

func (PostgresDialect) UpsertSyntax

func (d PostgresDialect) UpsertSyntax() UpsertStyle

type ProcParameter

type ProcParameter struct {
	Name         string // Without @ prefix
	SQLType      string // BIGINT, NVARCHAR(255), etc.
	GoType       string // Mapped Go type
	IsOutput     bool   // OUTPUT parameter
	HasDefault   bool   // Has default value
	DefaultValue string // Default value if any
	Position     int    // Parameter order (0-indexed)
}

ProcParameter represents a stored procedure parameter.

type Procedure

type Procedure struct {
	Name       string
	Parameters []ProcParameter
	Operations []Operation // DML operations inside the procedure
	ResultSets []ResultSet // Expected result sets from SELECT statements
	RawSQL     string      // Original SQL for reference
}

Procedure represents a parsed stored procedure.

type ProcedureExtractor

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

ProcedureExtractor extracts procedure metadata from T-SQL.

func NewProcedureExtractor

func NewProcedureExtractor() *ProcedureExtractor

NewProcedureExtractor creates a new extractor.

func (*ProcedureExtractor) ExtractAll

func (e *ProcedureExtractor) ExtractAll(sql string) ([]*Procedure, error)

ExtractAll extracts all procedures from SQL content.

func (*ProcedureExtractor) ExtractProcedure

func (e *ProcedureExtractor) ExtractProcedure(sql string) (*Procedure, error)

ExtractProcedure parses a CREATE PROCEDURE statement.

type ProcedureInfo

type ProcedureInfo struct {
	Name       string
	Schema     string
	Parameters []ProcedureParam
	SourceFile string
	SourceLine int
}

ProcedureInfo contains metadata about a parsed procedure.

type ProcedureParam

type ProcedureParam struct {
	Name         string
	SQLType      string
	GoType       string
	IsOutput     bool
	HasDefault   bool
	DefaultValue string
}

ProcedureParam describes a stored procedure parameter.

type ProtoEnumInfo

type ProtoEnumInfo struct {
	Name    string
	Values  []ProtoEnumValue
	Comment string
}

ProtoEnumInfo describes a protobuf enum.

type ProtoEnumValue

type ProtoEnumValue struct {
	Name    string
	Number  int
	Comment string
}

ProtoEnumValue describes an enum value.

type ProtoFieldInfo

type ProtoFieldInfo struct {
	Name      string // Field name in proto (e.g., "currency_code")
	Number    int    // Field number
	ProtoType string // Proto type (e.g., "string", "int32", "message")
	GoType    string // Generated Go type (e.g., "string", "*string", "int32", "*int32")

	// Optionality - critical for NULL handling
	IsOptional bool // Has 'optional' keyword in proto3
	IsRepeated bool // Is repeated field (generates slice)

	// For message types
	IsMessage   bool   // Is this field a message type?
	MessageType string // Full message type name (e.g., "originations.v1.dsl.Currency")

	// For map types
	IsMap      bool
	MapKeyType string
	MapValType string

	// For enums
	IsEnum   bool
	EnumType string

	// Metadata
	Comment string // Field comment from proto
}

ProtoFieldInfo describes a field in a protobuf message.

func (*ProtoFieldInfo) IsNullable

func (f *ProtoFieldInfo) IsNullable() bool

IsNullable returns true if the field can represent NULL. In proto3: optional scalar fields, message fields, and repeated fields can be "null".

type ProtoFile

type ProtoFile struct {
	Path      string // File path
	Package   string // Package declaration
	GoPackage string // go_package option

	Imports []string // Import statements

	Services []ProtoServiceInfo
	Messages []ProtoMessageInfo
	Enums    []ProtoEnumInfo
}

ProtoFile represents a parsed .proto file.

func (*ProtoFile) GetMessage

func (f *ProtoFile) GetMessage(name string) *ProtoMessageInfo

GetMessage returns a message by name, or nil if not found.

func (*ProtoFile) GetService

func (f *ProtoFile) GetService(name string) *ProtoServiceInfo

GetService returns a service by name, or nil if not found.

type ProtoMessageInfo

type ProtoMessageInfo struct {
	Name     string // Message name (e.g., "GetCurrencyByCodeRequest")
	FullName string // Full name with package (e.g., "originations.v1.dsl.GetCurrencyByCodeRequest")
	Package  string // Package name
	Fields   []ProtoFieldInfo
	Comment  string // Message comment

	// Nested types
	NestedMessages []ProtoMessageInfo
	NestedEnums    []ProtoEnumInfo
}

ProtoMessageInfo describes a protobuf message.

func (*ProtoMessageInfo) GetField

func (m *ProtoMessageInfo) GetField(name string) *ProtoFieldInfo

GetField returns a field by name, or nil if not found.

func (*ProtoMessageInfo) GetOptionalFields

func (m *ProtoMessageInfo) GetOptionalFields() []ProtoFieldInfo

GetOptionalFields returns only optional fields.

func (*ProtoMessageInfo) GetRequiredFields

func (m *ProtoMessageInfo) GetRequiredFields() []ProtoFieldInfo

GetRequiredFields returns only required (non-optional) fields.

type ProtoMethodInfo

type ProtoMethodInfo struct {
	Name     string // Method name (e.g., "GetCurrencyByCode")
	FullName string // Full name with service (e.g., "CatalogService.GetCurrencyByCode")

	// Request/Response
	RequestType  string            // Request message type name
	ResponseType string            // Response message type name
	Request      *ProtoMessageInfo // Parsed request message
	Response     *ProtoMessageInfo // Parsed response message

	// Streaming
	ClientStreaming bool
	ServerStreaming bool

	// Metadata
	Comment string

	// Inferred operation type
	InferredOp OperationType // Inferred from method name (Get* -> SELECT, Create* -> INSERT, etc.)
}

ProtoMethodInfo describes an RPC method in a service.

func (*ProtoMethodInfo) InferOperationType

func (m *ProtoMethodInfo) InferOperationType() OperationType

InferOperationType guesses the operation type from method name.

type ProtoParseResult

type ProtoParseResult struct {
	Files []ProtoFile

	// Flattened indexes for quick lookup
	AllServices map[string]*ProtoServiceInfo // service name -> service
	AllMessages map[string]*ProtoMessageInfo // message name -> message
	AllMethods  map[string]*ProtoMethodInfo  // "Service.Method" -> method
}

ProtoParseResult contains all parsed proto information.

func NewProtoParseResult

func NewProtoParseResult(files []ProtoFile) *ProtoParseResult

NewProtoParseResult creates an indexed parse result.

func (*ProtoParseResult) FindMethodsForTable

func (r *ProtoParseResult) FindMethodsForTable(tableName string, opType OperationType) []*ProtoMethodInfo

FindMethodsForTable finds proto methods that might correspond to operations on a table.

type ProtoServiceInfo

type ProtoServiceInfo struct {
	Name     string // Service name (e.g., "CatalogService")
	FullName string // Full name with package
	Package  string // Package name
	Methods  []ProtoMethodInfo
	Comment  string
}

ProtoServiceInfo describes a gRPC service.

func (*ProtoServiceInfo) GetMethod

func (s *ProtoServiceInfo) GetMethod(name string) *ProtoMethodInfo

GetMethod returns a method by name, or nil if not found.

func (*ProtoServiceInfo) GetMethodsByOperation

func (s *ProtoServiceInfo) GetMethodsByOperation(op OperationType) []ProtoMethodInfo

GetMethodsByOperation returns methods matching an operation type.

type ProtoToSQLMapper

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

ProtoToSQLMapper maps proto service methods to stored procedures.

func NewProtoToSQLMapper

func NewProtoToSQLMapper(proto *ProtoParseResult, procedures []*Procedure) *ProtoToSQLMapper

NewProtoToSQLMapper creates a new mapper.

func (*ProtoToSQLMapper) GetMapping

func (m *ProtoToSQLMapper) GetMapping(serviceName, methodName string) *MethodMapping

GetMapping returns the mapping for a specific method.

func (*ProtoToSQLMapper) GetStats

func (m *ProtoToSQLMapper) GetStats() MappingStats

GetStats returns mapping statistics.

func (*ProtoToSQLMapper) MapAll

func (m *ProtoToSQLMapper) MapAll() map[string]*MethodMapping

MapAll attempts to map all proto methods to stored procedures.

type Repository

type Repository struct {
	Name    string // Interface name (e.g., "CurrencyRepository")
	Entity  string // Entity name (e.g., "Currency")
	Table   string // Source table
	Methods []RepositoryMethod
}

Repository describes a repository interface for an entity.

type RepositoryError

type RepositoryError struct {
	Op     string // Operation that failed
	Entity string // Entity type
	Key    string // Key value (if applicable)
	Err    error  // Underlying error
}

Error types for repositories

func (*RepositoryError) Error

func (e *RepositoryError) Error() string

func (*RepositoryError) Unwrap

func (e *RepositoryError) Unwrap() error

type RepositoryMethod

type RepositoryMethod struct {
	Name        string // Method name (e.g., "GetByCode")
	Operation   Operation
	InputFields []Field // Method parameters
	OutputType  string  // Return type (e.g., "*Currency", "[]Currency")
	ReturnsMany bool    // Returns slice vs single entity
}

RepositoryMethod describes a method on a repository interface.

type RepositoryTemplate

type RepositoryTemplate struct {
	// Interface info
	InterfaceName string
	EntityName    string
	TableName     string

	// Methods to generate
	Methods []MethodTemplate

	// Backend specific
	Dialect SQLDialect

	// Proto info (for gRPC backend)
	GRPCClient  string // Client field name
	GRPCService string // Service name in proto
}

RepositoryTemplate is data for generating a single repository implementation.

type ResultColumn

type ResultColumn struct {
	Name    string // Column name or alias
	SQLType string // If determinable
	GoType  string // Mapped Go type
	Source  string // Table.Column if identifiable
}

ResultColumn represents a column in a result set.

type ResultMapping

type ResultMapping struct {
	ResponseType    string // Proto response message name
	ResultSetIndex  int    // Which result set (0-indexed)
	NestedFieldName string // If response wraps a nested message, the field name (e.g., "customer")
	NestedTypeName  string // If response wraps a nested message, the type name (e.g., "Customer")
	IsRepeated      bool   // If true, response field is repeated (requires Query + loop, not QueryRow)
	FieldMappings   []FieldMapping
}

ResultMapping maps procedure results to proto response message.

type ResultSet

type ResultSet struct {
	Columns   []ResultColumn
	FromTable string // Primary table if identifiable
}

ResultSet represents columns returned by a SELECT statement.

type SQLDetector

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

SQLDetector implements the Detector interface for T-SQL.

func NewSQLDetector

func NewSQLDetector(config DetectorConfig) *SQLDetector

NewSQLDetector creates a new SQL operation detector.

func (*SQLDetector) DetectFromSQL

func (d *SQLDetector) DetectFromSQL(sql string) ([]Operation, error)

DetectFromSQL parses raw SQL and detects operations. It handles both CREATE PROCEDURE statements and raw DML statements.

func (*SQLDetector) DetectModels

func (d *SQLDetector) DetectModels(ops []Operation) ([]Model, error)

DetectModels infers models from detected operations.

func (*SQLDetector) DetectOperations

func (d *SQLDetector) DetectOperations(proc interface{}) ([]Operation, error)

DetectOperations scans a procedure and returns all data operations found.

func (*SQLDetector) DetectRepositories

func (d *SQLDetector) DetectRepositories(ops []Operation, models []Model) ([]Repository, error)

DetectRepositories generates repository specs from operations and models.

func (*SQLDetector) GetErrors

func (d *SQLDetector) GetErrors() []DetectionError

GetErrors returns detection errors.

func (*SQLDetector) GetWarnings

func (d *SQLDetector) GetWarnings() []DetectionWarning

GetWarnings returns detection warnings.

type SQLDialect

type SQLDialect interface {
	// Name returns the dialect name.
	Name() string

	// Placeholder returns the parameter placeholder for position n.
	// PostgreSQL: $1, $2, $3...
	// MySQL/SQLite: ?
	// Oracle: :1, :2, :3...
	// SQL Server: @p1, @p2, @p3...
	Placeholder(n int) string

	// QuoteIdentifier quotes an identifier (table/column name).
	// PostgreSQL: "name"
	// MySQL: `name`
	// SQL Server: [name]
	QuoteIdentifier(name string) string

	// TableAlias returns how to write a table alias.
	// PostgreSQL/MySQL/SQLite/SQL Server: "table AS alias" or "table alias"
	// Oracle: "table alias" (AS is forbidden!)
	TableAlias(table, alias string) string

	// SupportsTableAliasAS returns whether AS keyword is allowed for table aliases.
	// All except Oracle: true
	// Oracle: false
	SupportsTableAliasAS() bool

	// LastInsertIDMethod returns the method to get last insert ID.
	// PostgreSQL: RETURNING id
	// MySQL: LAST_INSERT_ID()
	// SQLite: last_insert_rowid()
	// SQL Server: SCOPE_IDENTITY() or OUTPUT clause
	// Oracle: RETURNING INTO
	LastInsertIDMethod() string

	// SupportsReturning returns whether INSERT ... RETURNING is supported.
	// PostgreSQL, SQLite 3.35+: true
	// MySQL, Oracle (without INTO): false
	// SQL Server: false (uses OUTPUT instead)
	SupportsReturning() bool

	// SupportsOutputClause returns whether OUTPUT clause is supported (SQL Server).
	SupportsOutputClause() bool

	// BooleanLiteral returns how to represent true/false.
	BooleanLiteral(b bool) string

	// LimitClause returns how to limit results.
	// PostgreSQL/MySQL/SQLite: LIMIT n
	// SQL Server: TOP n (in SELECT)
	// Oracle: FETCH FIRST n ROWS ONLY
	LimitClause(n int) string

	// LimitPosition returns where LIMIT goes.
	// Most: "end" (after WHERE/ORDER BY)
	// SQL Server: "select" (TOP after SELECT keyword)
	LimitPosition() string

	// OffsetFetchClause returns SQL standard OFFSET/FETCH syntax (if supported).
	// Returns empty string if not supported.
	OffsetFetchClause(offset, limit int) string

	// NullSafeEqual returns a null-safe equality operator or function.
	// PostgreSQL: IS NOT DISTINCT FROM
	// MySQL: <=>
	// SQLite: IS
	// Others: (a = b OR (a IS NULL AND b IS NULL))
	NullSafeEqual(left, right string) string

	// StringConcat returns how to concatenate strings.
	// PostgreSQL/SQLite/Oracle: ||
	// SQL Server: +
	// MySQL: CONCAT() function
	StringConcat(parts ...string) string

	// UpdateJoinSyntax returns how UPDATE with JOIN is written.
	// SQL Server: UPDATE t SET ... FROM t JOIN o ON ...
	// PostgreSQL: UPDATE t SET ... FROM o WHERE t.id = o.id
	// MySQL: UPDATE t JOIN o ON ... SET t.col = ...
	// SQLite/Oracle: subquery or not supported
	UpdateJoinSyntax() UpdateJoinStyle

	// DeleteJoinSyntax returns how DELETE with JOIN is written.
	// SQL Server: DELETE t FROM t JOIN o ON ...
	// PostgreSQL: DELETE FROM t USING o WHERE ...
	// MySQL: DELETE t FROM t JOIN o ON ...
	// SQLite/Oracle: subquery
	DeleteJoinSyntax() DeleteJoinStyle

	// UpsertSyntax returns how UPSERT/MERGE is written.
	UpsertSyntax() UpsertStyle

	// NeedsFromDual returns whether SELECT without FROM needs FROM DUAL.
	// Oracle: true
	// Others: false
	NeedsFromDual() bool

	// TypeMapping returns the native type for a Go type.
	TypeMapping(goType string) string

	// DriverName returns the database/sql driver name.
	DriverName() string

	// ConnectionStringFormat returns a sample connection string format.
	ConnectionStringFormat() string
}

SQLDialect describes SQL dialect differences for SQL backends.

func GetDialect

func GetDialect(backend BackendType) SQLDialect

GetDialect returns the SQLDialect for a backend type.

type SQLServerDialect

type SQLServerDialect struct{}

SQLServerDialect implements SQLDialect for Microsoft SQL Server.

func (SQLServerDialect) BooleanLiteral

func (d SQLServerDialect) BooleanLiteral(b bool) string

func (SQLServerDialect) ConnectionStringFormat

func (d SQLServerDialect) ConnectionStringFormat() string

func (SQLServerDialect) DeleteJoinSyntax

func (d SQLServerDialect) DeleteJoinSyntax() DeleteJoinStyle

func (SQLServerDialect) DriverName

func (d SQLServerDialect) DriverName() string

func (SQLServerDialect) LastInsertIDMethod

func (d SQLServerDialect) LastInsertIDMethod() string

func (SQLServerDialect) LimitClause

func (d SQLServerDialect) LimitClause(n int) string

func (SQLServerDialect) LimitPosition

func (d SQLServerDialect) LimitPosition() string

func (SQLServerDialect) Name

func (d SQLServerDialect) Name() string

func (SQLServerDialect) NeedsFromDual

func (d SQLServerDialect) NeedsFromDual() bool

func (SQLServerDialect) NullSafeEqual

func (d SQLServerDialect) NullSafeEqual(left, right string) string

func (SQLServerDialect) OffsetFetchClause

func (d SQLServerDialect) OffsetFetchClause(offset, limit int) string

func (SQLServerDialect) Placeholder

func (d SQLServerDialect) Placeholder(n int) string

func (SQLServerDialect) QuoteIdentifier

func (d SQLServerDialect) QuoteIdentifier(name string) string

func (SQLServerDialect) StringConcat

func (d SQLServerDialect) StringConcat(parts ...string) string

func (SQLServerDialect) SupportsOutputClause

func (d SQLServerDialect) SupportsOutputClause() bool

func (SQLServerDialect) SupportsReturning

func (d SQLServerDialect) SupportsReturning() bool

func (SQLServerDialect) SupportsTableAliasAS

func (d SQLServerDialect) SupportsTableAliasAS() bool

func (SQLServerDialect) TableAlias

func (d SQLServerDialect) TableAlias(table, alias string) string

func (SQLServerDialect) TypeMapping

func (d SQLServerDialect) TypeMapping(goType string) string

func (SQLServerDialect) UpdateJoinSyntax

func (d SQLServerDialect) UpdateJoinSyntax() UpdateJoinStyle

func (SQLServerDialect) UpsertSyntax

func (d SQLServerDialect) UpsertSyntax() UpsertStyle

type SQLToProtoMapping

type SQLToProtoMapping struct {
	// Source SQL
	Operation Operation

	// Target Proto
	Service     string // Service name
	Method      string // Method name
	ProtoMethod *ProtoMethodInfo

	// Field mappings: SQL column/variable -> Proto field
	RequestMapping  map[string]string // SQL field -> Request proto field
	ResponseMapping map[string]string // Response proto field -> SQL variable

	// Confidence score for automatic matching (0.0 - 1.0)
	Confidence float64

	// If confidence < 1.0, reasons for uncertainty
	MatchNotes []string
}

SQLToProtoMapping describes how a SQL operation maps to a proto method.

func (*SQLToProtoMapping) IsHighConfidence

func (m *SQLToProtoMapping) IsHighConfidence() bool

IsHighConfidence returns true if the mapping is reliable.

type SQLiteDialect

type SQLiteDialect struct{}

SQLiteDialect implements SQLDialect for SQLite.

func (SQLiteDialect) BooleanLiteral

func (d SQLiteDialect) BooleanLiteral(b bool) string

func (SQLiteDialect) ConnectionStringFormat

func (d SQLiteDialect) ConnectionStringFormat() string

func (SQLiteDialect) DeleteJoinSyntax

func (d SQLiteDialect) DeleteJoinSyntax() DeleteJoinStyle

func (SQLiteDialect) DriverName

func (d SQLiteDialect) DriverName() string

func (SQLiteDialect) LastInsertIDMethod

func (d SQLiteDialect) LastInsertIDMethod() string

func (SQLiteDialect) LimitClause

func (d SQLiteDialect) LimitClause(n int) string

func (SQLiteDialect) LimitPosition

func (d SQLiteDialect) LimitPosition() string

func (SQLiteDialect) Name

func (d SQLiteDialect) Name() string

func (SQLiteDialect) NeedsFromDual

func (d SQLiteDialect) NeedsFromDual() bool

func (SQLiteDialect) NullSafeEqual

func (d SQLiteDialect) NullSafeEqual(left, right string) string

func (SQLiteDialect) OffsetFetchClause

func (d SQLiteDialect) OffsetFetchClause(offset, limit int) string

func (SQLiteDialect) Placeholder

func (d SQLiteDialect) Placeholder(n int) string

func (SQLiteDialect) QuoteIdentifier

func (d SQLiteDialect) QuoteIdentifier(name string) string

func (SQLiteDialect) StringConcat

func (d SQLiteDialect) StringConcat(parts ...string) string

func (SQLiteDialect) SupportsOutputClause

func (d SQLiteDialect) SupportsOutputClause() bool

func (SQLiteDialect) SupportsReturning

func (d SQLiteDialect) SupportsReturning() bool

func (SQLiteDialect) SupportsTableAliasAS

func (d SQLiteDialect) SupportsTableAliasAS() bool

func (SQLiteDialect) TableAlias

func (d SQLiteDialect) TableAlias(table, alias string) string

func (SQLiteDialect) TypeMapping

func (d SQLiteDialect) TypeMapping(goType string) string

func (SQLiteDialect) UpdateJoinSyntax

func (d SQLiteDialect) UpdateJoinSyntax() UpdateJoinStyle

func (SQLiteDialect) UpsertSyntax

func (d SQLiteDialect) UpsertSyntax() UpsertStyle

type SelectColumn

type SelectColumn struct {
	Name       string // Column name or alias
	SourceName string // Original column name (if aliased)
	Table      string // Source table (if known)
	Expression string // Full expression (for computed columns)
	IsComputed bool   // Is this a computed expression?
}

SelectColumn describes a column in a SELECT.

type SelectInfo

type SelectInfo struct {
	// Columns being selected
	Columns []SelectColumn

	// Tables involved
	Tables []TableRef

	// WHERE clause fields
	WhereFields []WhereField

	// Variables being assigned (SELECT @var = col)
	Assignments []VariableAssignment

	// Aggregates present
	HasAggregates bool

	// DISTINCT keyword
	IsDistinct bool

	// TOP clause
	TopCount int

	// JOINs
	Joins []JoinInfo
}

SelectInfo contains parsed information from a SELECT statement.

type SelectPattern

type SelectPattern int

SelectPattern identifies common SELECT patterns for repository method naming.

const (
	PatternUnknown  SelectPattern = iota
	PatternGetByID                // SELECT ... WHERE id = @id
	PatternGetByKey               // SELECT ... WHERE unique_key = @key
	PatternGetAll                 // SELECT ... (no WHERE)
	PatternGetByFK                // SELECT ... WHERE foreign_key = @fk
	PatternSearch                 // SELECT ... WHERE name LIKE @pattern
	PatternExists                 // SELECT 1 WHERE ... (existence check)
	PatternCount                  // SELECT COUNT(*) ...
	PatternGetMany                // SELECT ... WHERE id IN (...)
)

func IdentifySelectPattern

func IdentifySelectPattern(info *SelectInfo) SelectPattern

IdentifySelectPattern analyzes a SELECT to determine its pattern.

type ServiceMappingStats

type ServiceMappingStats struct {
	ServiceName   string
	TotalMethods  int
	MappedMethods int
	Mappings      []*MethodMapping
}

type StrategyResult

type StrategyResult struct {
	Matched    bool
	Score      float64 // 0.0 to 1.0
	Reason     string
	Confidence float64 // How confident the strategy is in its own result
}

StrategyResult is the output of a single strategy.

type TableRef

type TableRef struct {
	Name   string
	Schema string
	Alias  string
}

TableRef describes a table reference in FROM clause.

type TemplateData

type TemplateData struct {
	// Package info
	Package string
	Imports []string

	// Generation info
	GeneratedBy string
	SourceFiles []string

	// Content
	Models       []Model
	Repositories []Repository
	Operations   []Operation

	// Backend specific
	Backend BackendType
	Dialect SQLDialect

	// Proto info (for gRPC)
	ProtoPackage  string
	ProtoServices []ProtoServiceInfo
	ProtoMappings []SQLToProtoMapping
}

TemplateData is passed to code generation templates.

type UnitOfWorkSpec

type UnitOfWorkSpec struct {
	Repositories    []Repository
	HasTransactions bool
}

UnitOfWorkSpec describes the unit of work interface.

type UpdateAssignment

type UpdateAssignment struct {
	Column     string
	Variable   string
	Literal    string
	Expression string // For computed updates
}

UpdateAssignment describes a SET assignment in UPDATE.

type UpdateInfo

type UpdateInfo struct {
	Table TableRef

	// SET clause
	Assignments []UpdateAssignment

	// WHERE clause
	WhereFields []WhereField

	// FROM clause (for UPDATE ... FROM)
	FromTables []TableRef
	Joins      []JoinInfo

	// OUTPUT clause
	OutputColumns []string
}

UpdateInfo contains parsed information from an UPDATE statement.

type UpdateJoinStyle

type UpdateJoinStyle int

UpdateJoinStyle describes how a dialect handles UPDATE with JOIN.

const (
	UpdateJoinNotSupported UpdateJoinStyle = iota // Must use subquery
	UpdateJoinFromClause                          // UPDATE t SET ... FROM t JOIN o (SQL Server)
	UpdateJoinFromWhere                           // UPDATE t SET ... FROM o WHERE t.id = o.id (PostgreSQL)
	UpdateJoinDirect                              // UPDATE t JOIN o SET ... (MySQL)
)

type UpsertStyle

type UpsertStyle int

UpsertStyle describes how a dialect handles UPSERT operations.

const (
	UpsertNotSupported   UpsertStyle = iota // No native support
	UpsertMerge                             // MERGE statement (SQL Server, Oracle, PostgreSQL 15+)
	UpsertOnConflict                        // INSERT ... ON CONFLICT (PostgreSQL 9.5+, SQLite 3.24+)
	UpsertOnDuplicateKey                    // INSERT ... ON DUPLICATE KEY UPDATE (MySQL)
)

type VariableAssignment

type VariableAssignment struct {
	Variable string // T-SQL variable (e.g., "@Name")
	Column   string // Column being assigned
	Table    string // Source table
}

VariableAssignment describes a SELECT INTO variable assignment.

type VerbEntityStrategy

type VerbEntityStrategy struct{}

func (*VerbEntityStrategy) Match

func (*VerbEntityStrategy) Name

func (s *VerbEntityStrategy) Name() string

type WhereField

type WhereField struct {
	Column      string
	Table       string // Table name or alias
	Operator    string // =, <>, <, >, LIKE, IN, IS NULL, etc.
	Variable    string // T-SQL variable (e.g., "@CustomerID")
	Literal     string // Literal value (if not variable)
	IsNullCheck bool   // IS NULL or IS NOT NULL
}

WhereField describes a field used in WHERE clause.

Jump to

Keyboard shortcuts

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