|
| 1 | +// Package gosqlxgorm provides a GORM plugin that parses each executed query |
| 2 | +// with GoSQLX and records extracted metadata (tables, columns, statement type). |
| 3 | +package gosqlxgorm |
| 4 | + |
| 5 | +import ( |
| 6 | + "regexp" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "sync" |
| 10 | + |
| 11 | + "github.com/ajitpratap0/GoSQLX/pkg/gosqlx" |
| 12 | + "github.com/ajitpratap0/GoSQLX/pkg/sql/ast" |
| 13 | + "github.com/ajitpratap0/GoSQLX/pkg/sql/keywords" |
| 14 | + "gorm.io/gorm" |
| 15 | +) |
| 16 | + |
| 17 | +// reQuestionMark replaces GORM's ? positional placeholders. |
| 18 | +var reQuestionMark = regexp.MustCompile(`\?`) |
| 19 | + |
| 20 | +// QueryRecord holds metadata about a single recorded GORM query. |
| 21 | +type QueryRecord struct { |
| 22 | + SQL string |
| 23 | + Tables []string |
| 24 | + Columns []string |
| 25 | + Type string // SELECT, INSERT, UPDATE, DELETE, ... |
| 26 | + ParseOK bool |
| 27 | +} |
| 28 | + |
| 29 | +// PluginStats is the aggregate of all queries observed since initialization. |
| 30 | +type PluginStats struct { |
| 31 | + TotalQueries int |
| 32 | + ParseErrors int |
| 33 | + Queries []QueryRecord |
| 34 | +} |
| 35 | + |
| 36 | +// defaultMaxHistory is the default maximum number of query records kept. |
| 37 | +const defaultMaxHistory = 1000 |
| 38 | + |
| 39 | +// PluginOptions configures the GORM plugin behavior. |
| 40 | +type PluginOptions struct { |
| 41 | + // MaxHistory limits the number of query records kept. Zero uses the default (1000). |
| 42 | + MaxHistory int |
| 43 | + // OnParseError is called when GoSQLX fails to parse a query. Optional. |
| 44 | + OnParseError func(sql string, err error) |
| 45 | +} |
| 46 | + |
| 47 | +// Plugin is a GORM plugin that parses each executed query with GoSQLX |
| 48 | +// and records extracted metadata (tables, columns, statement type). |
| 49 | +type Plugin struct { |
| 50 | + mu sync.Mutex |
| 51 | + queries []QueryRecord |
| 52 | + maxHistory int |
| 53 | + onParseError func(sql string, err error) |
| 54 | +} |
| 55 | + |
| 56 | +// NewPlugin returns a new GoSQLX GORM plugin with default options. |
| 57 | +func NewPlugin() *Plugin { |
| 58 | + return &Plugin{maxHistory: defaultMaxHistory} |
| 59 | +} |
| 60 | + |
| 61 | +// NewPluginWithOptions returns a new GoSQLX GORM plugin configured with opts. |
| 62 | +func NewPluginWithOptions(opts PluginOptions) *Plugin { |
| 63 | + mh := opts.MaxHistory |
| 64 | + if mh <= 0 { |
| 65 | + mh = defaultMaxHistory |
| 66 | + } |
| 67 | + return &Plugin{ |
| 68 | + maxHistory: mh, |
| 69 | + onParseError: opts.OnParseError, |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// Name implements gorm.Plugin. |
| 74 | +func (p *Plugin) Name() string { return "gosqlx" } |
| 75 | + |
| 76 | +// Initialize implements gorm.Plugin by registering after-callbacks. |
| 77 | +func (p *Plugin) Initialize(db *gorm.DB) error { |
| 78 | + db.Callback().Query().After("gorm:query").Register("gosqlx:after_query", p.afterStatement) |
| 79 | + db.Callback().Create().After("gorm:create").Register("gosqlx:after_create", p.afterStatement) |
| 80 | + db.Callback().Update().After("gorm:update").Register("gosqlx:after_update", p.afterStatement) |
| 81 | + db.Callback().Delete().After("gorm:delete").Register("gosqlx:after_delete", p.afterStatement) |
| 82 | + db.Callback().Raw().After("gorm:raw").Register("gosqlx:after_raw", p.afterStatement) |
| 83 | + return nil |
| 84 | +} |
| 85 | + |
| 86 | +func (p *Plugin) afterStatement(db *gorm.DB) { |
| 87 | + // Guard against nil Statement — this can happen during initialization callbacks. |
| 88 | + if db.Statement == nil { |
| 89 | + return |
| 90 | + } |
| 91 | + sql := db.Statement.SQL.String() |
| 92 | + if sql == "" { |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + rec := QueryRecord{SQL: sql} |
| 97 | + |
| 98 | + // Normalize GORM-generated SQL for GoSQLX compatibility: |
| 99 | + // 1. Replace backtick-quoted identifiers with double-quoted identifiers |
| 100 | + // (GORM SQLite/MySQL driver uses backticks; GoSQLX standard mode uses double-quotes). |
| 101 | + // 2. Replace ? positional placeholders with $N (PostgreSQL style). |
| 102 | + normalized := normalizeSQLForParsing(sql) |
| 103 | + |
| 104 | + // Try PostgreSQL dialect (handles double-quoted identifiers and $N placeholders), |
| 105 | + // then fall back to standard SQL parsing. |
| 106 | + tree, err := gosqlx.ParseWithDialect(normalized, keywords.DialectPostgreSQL) |
| 107 | + if err != nil { |
| 108 | + tree, err = gosqlx.Parse(normalized) |
| 109 | + } |
| 110 | + if err != nil { |
| 111 | + rec.ParseOK = false |
| 112 | + if p.onParseError != nil { |
| 113 | + p.onParseError(sql, err) |
| 114 | + } |
| 115 | + } else { |
| 116 | + rec.ParseOK = true |
| 117 | + rec.Tables = gosqlx.ExtractTables(tree) |
| 118 | + rec.Columns = gosqlx.ExtractColumns(tree) |
| 119 | + if tree != nil && len(tree.Statements) > 0 { |
| 120 | + rec.Type = stmtTypeName(tree.Statements[0]) |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + p.mu.Lock() |
| 125 | + p.queries = append(p.queries, rec) |
| 126 | + if len(p.queries) > p.maxHistory { |
| 127 | + // Trim oldest entries to stay within the limit. |
| 128 | + excess := len(p.queries) - p.maxHistory |
| 129 | + copy(p.queries, p.queries[excess:]) |
| 130 | + p.queries = p.queries[:p.maxHistory] |
| 131 | + } |
| 132 | + p.mu.Unlock() |
| 133 | +} |
| 134 | + |
| 135 | +// normalizeSQLForParsing converts GORM-generated SQL into a form that GoSQLX |
| 136 | +// can parse: backtick identifiers become double-quoted, and ? placeholders |
| 137 | +// become $N placeholders. |
| 138 | +func normalizeSQLForParsing(sql string) string { |
| 139 | + // Replace backtick-quoted identifiers with double-quoted identifiers. |
| 140 | + sql = strings.ReplaceAll(sql, "`", "\"") |
| 141 | + // Replace ? positional placeholders with $N. |
| 142 | + n := 0 |
| 143 | + sql = reQuestionMark.ReplaceAllStringFunc(sql, func(string) string { |
| 144 | + n++ |
| 145 | + return "$" + strconv.Itoa(n) |
| 146 | + }) |
| 147 | + return sql |
| 148 | +} |
| 149 | + |
| 150 | +// Stats returns a snapshot of all recorded queries. |
| 151 | +func (p *Plugin) Stats() PluginStats { |
| 152 | + p.mu.Lock() |
| 153 | + defer p.mu.Unlock() |
| 154 | + var errCount int |
| 155 | + for _, q := range p.queries { |
| 156 | + if !q.ParseOK { |
| 157 | + errCount++ |
| 158 | + } |
| 159 | + } |
| 160 | + qs := make([]QueryRecord, len(p.queries)) |
| 161 | + copy(qs, p.queries) |
| 162 | + return PluginStats{ |
| 163 | + TotalQueries: len(p.queries), |
| 164 | + ParseErrors: errCount, |
| 165 | + Queries: qs, |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +// Reset clears all recorded queries. |
| 170 | +func (p *Plugin) Reset() { |
| 171 | + p.mu.Lock() |
| 172 | + p.queries = p.queries[:0] |
| 173 | + p.mu.Unlock() |
| 174 | +} |
| 175 | + |
| 176 | +// stmtTypeName returns a human-readable SQL statement type name. |
| 177 | +func stmtTypeName(stmt ast.Statement) string { |
| 178 | + switch stmt.(type) { |
| 179 | + case *ast.SelectStatement: |
| 180 | + return "SELECT" |
| 181 | + case *ast.InsertStatement: |
| 182 | + return "INSERT" |
| 183 | + case *ast.UpdateStatement: |
| 184 | + return "UPDATE" |
| 185 | + case *ast.DeleteStatement: |
| 186 | + return "DELETE" |
| 187 | + default: |
| 188 | + return "OTHER" |
| 189 | + } |
| 190 | +} |
0 commit comments