2
0

generated.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package executor
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/danfragoso/pizzasql-next/pkg/parser"
  6. "github.com/danfragoso/pizzasql-next/pkg/storage"
  7. )
  8. // generatedColumnExpr resolves a column's generated expression, if any.
  9. func (e *Executor) generatedColumnExpr(col storage.Column) (parser.Expr, bool, error) {
  10. if col.GeneratedExpr == "" {
  11. return nil, false, nil
  12. }
  13. expr, err := parseStoredExpr(col.GeneratedExpr)
  14. if err != nil {
  15. return nil, false, err
  16. }
  17. return expr, true, nil
  18. }
  19. // applyGeneratedColumns recomputes and stores every generated column value on
  20. // row. It runs after the base columns of an INSERT/UPDATE have been resolved so
  21. // STORED generated values are materialized in the durable row.
  22. func (e *Executor) applyGeneratedColumns(schema *storage.Schema, row storage.Row) error {
  23. for _, col := range schema.Columns {
  24. expr, ok, err := e.generatedColumnExpr(col)
  25. if err != nil {
  26. return err
  27. }
  28. if !ok {
  29. continue
  30. }
  31. val, err := e.evalExpr(expr, row)
  32. if err != nil {
  33. return fmt.Errorf("evaluating generated column %s: %w", col.Name, err)
  34. }
  35. row[col.Name] = val
  36. }
  37. normalizeStoredValues(row)
  38. return nil
  39. }
  40. // normalizeStoredValues converts executor-internal value types (currently the
  41. // JSON1 subtype) into the plain scalar types the storage codec persists.
  42. func normalizeStoredValues(row storage.Row) {
  43. for k, v := range row {
  44. if jt, ok := v.(jsonText); ok {
  45. row[k] = string(jt)
  46. }
  47. }
  48. }
  49. // generatedColumnSet returns the lowercased names of generated columns.
  50. func generatedColumnSet(schema *storage.Schema) map[string]bool {
  51. set := make(map[string]bool)
  52. for _, col := range schema.Columns {
  53. if col.GeneratedExpr != "" {
  54. set[strings.ToLower(col.Name)] = true
  55. }
  56. }
  57. return set
  58. }
  59. // ensureGeneratedRowID assigns the primary key of a row before generated-column
  60. // evaluation when the key is an engine-generated INTEGER PRIMARY KEY, so a
  61. // generated expression that references the auto-incrementing id (the common
  62. // `stored = id + 1` shape) does not see NULL. Tables without an explicit
  63. // integer primary key are left to the storage layer, which assigns the hidden
  64. // _rowid_ during the insert.
  65. func (e *Executor) ensureGeneratedRowID(tableName string, schema *storage.Schema, row storage.Row) error {
  66. if schema.PrimaryKey == "" || schema.PrimaryKey == "_rowid_" {
  67. return nil
  68. }
  69. if v, ok := lookupRowValue(row, schema.PrimaryKey); ok && v != nil {
  70. return nil
  71. }
  72. pkCol, ok := schema.GetColumn(schema.PrimaryKey)
  73. if !ok || !isIntegerColumnType(pkCol.Type) {
  74. return nil
  75. }
  76. id, err := e.schema.GetNextRowID(tableName)
  77. if err != nil {
  78. return err
  79. }
  80. row[schema.PrimaryKey] = id
  81. return nil
  82. }
  83. // lookupRowValue resolves a row value case-insensitively.
  84. func lookupRowValue(row storage.Row, name string) (interface{}, bool) {
  85. if v, ok := row[name]; ok {
  86. return v, true
  87. }
  88. for k, v := range row {
  89. if strings.EqualFold(k, name) {
  90. return v, true
  91. }
  92. }
  93. return nil, false
  94. }
  95. // isIntegerColumnType reports whether a declared type has integer affinity.
  96. func isIntegerColumnType(typeName string) bool {
  97. return strings.Contains(strings.ToUpper(typeName), "INT")
  98. }
  99. // conflictMatcher describes one uniqueness constraint used to resolve an
  100. // INSERT conflict. index is nil for the primary key.
  101. type conflictMatcher struct {
  102. name string
  103. index *storage.Index
  104. primaryKey bool
  105. }
  106. // insertConflictMatchers returns the constraints that should be replaced for an
  107. // INSERT. A statement-level INSERT OR REPLACE replaces on every uniqueness
  108. // constraint; otherwise only indexes declaring ON CONFLICT REPLACE are
  109. // replaced.
  110. func (e *Executor) insertConflictMatchers(tableName string, schema *storage.Schema, stmtReplace bool) ([]conflictMatcher, error) {
  111. var matchers []conflictMatcher
  112. if stmtReplace {
  113. matchers = append(matchers, conflictMatcher{name: schema.PrimaryKey, primaryKey: true})
  114. }
  115. indexes, err := e.schema.ListTableIndexes(tableName)
  116. if err != nil {
  117. return nil, err
  118. }
  119. for _, idx := range indexes {
  120. if !idx.Unique {
  121. continue
  122. }
  123. if !stmtReplace && !strings.EqualFold(idx.OnConflict, "REPLACE") {
  124. continue
  125. }
  126. matchers = append(matchers, conflictMatcher{name: idx.Name, index: idx})
  127. }
  128. return matchers, nil
  129. }
  130. // matcherConflicts returns the durable/overlay rows that the candidate would
  131. // conflict with on a single matcher, using a primary-key point read or an
  132. // index-key lookup rather than a full table scan.
  133. func (e *Executor) matcherConflicts(tableName string, schema *storage.Schema, m conflictMatcher, candidate storage.Row) ([]storage.Row, error) {
  134. if m.primaryKey {
  135. pkValue, ok := lookupRowValue(candidate, schema.PrimaryKey)
  136. if !ok || pkValue == nil {
  137. return nil, nil
  138. }
  139. row, err := e.session.GetByPK(tableName, fmt.Sprintf("%v", pkValue))
  140. if err == storage.ErrKeyNotFound {
  141. return nil, nil
  142. }
  143. if err != nil {
  144. return nil, err
  145. }
  146. return []storage.Row{row}, nil
  147. }
  148. isNull, err := e.table.IndexValueContainsNull(m.index, candidate)
  149. if err != nil {
  150. return nil, err
  151. }
  152. if isNull {
  153. return nil, nil
  154. }
  155. key, err := e.table.IndexRowKey(m.index, candidate)
  156. if err != nil {
  157. return nil, err
  158. }
  159. return e.session.SelectByIndexKey(tableName, m.index, key)
  160. }
  161. // hasAnyInsertConflict checks every uniqueness constraint. SQLite's
  162. // statement-level OR IGNORE and targetless DO NOTHING apply to any conflict,
  163. // not just the primary key.
  164. func (e *Executor) hasAnyInsertConflict(tableName string, schema *storage.Schema, candidate storage.Row) (bool, error) {
  165. matchers := []conflictMatcher{{name: schema.PrimaryKey, primaryKey: true}}
  166. indexes, err := e.schema.ListTableIndexes(tableName)
  167. if err != nil {
  168. return false, err
  169. }
  170. for _, index := range indexes {
  171. if index.Unique {
  172. matchers = append(matchers, conflictMatcher{name: index.Name, index: index})
  173. }
  174. }
  175. for _, matcher := range matchers {
  176. rows, err := e.matcherConflicts(tableName, schema, matcher, candidate)
  177. if err != nil {
  178. return false, err
  179. }
  180. if len(rows) > 0 {
  181. return true, nil
  182. }
  183. }
  184. return false, nil
  185. }
  186. // resolveInsertConflicts removes existing rows that conflict with candidate on
  187. // any constraint that resolves to REPLACE. It runs inside the statement's
  188. // atomic DML block so the deletes and the subsequent insert commit together.
  189. func (e *Executor) resolveInsertConflicts(tableName string, schema *storage.Schema, candidate storage.Row, stmtReplace bool) error {
  190. matchers, err := e.insertConflictMatchers(tableName, schema, stmtReplace)
  191. if err != nil {
  192. return err
  193. }
  194. if len(matchers) == 0 {
  195. return nil
  196. }
  197. // Collect matching rows through point/index lookups, then delete them by
  198. // primary key. A row may match several constraints, so deduplicate.
  199. toDelete := make(map[string]storage.Row)
  200. for _, m := range matchers {
  201. rows, err := e.matcherConflicts(tableName, schema, m, candidate)
  202. if err != nil {
  203. return err
  204. }
  205. for _, row := range rows {
  206. toDelete[fmt.Sprintf("%v", row[schema.PrimaryKey])] = row
  207. }
  208. }
  209. if len(toDelete) == 0 {
  210. return nil
  211. }
  212. for _, row := range toDelete {
  213. if _, deleted, derr := e.session.DeleteByPK(tableName, fmt.Sprintf("%v", row[schema.PrimaryKey])); derr != nil {
  214. return derr
  215. } else if !deleted {
  216. return fmt.Errorf("ON CONFLICT REPLACE row disappeared during delete")
  217. }
  218. }
  219. return nil
  220. }