2
0

generated.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. // Only a single-column INTEGER PRIMARY KEY is generated before evaluation; a
  67. // composite key is never a rowid alias.
  68. if !schema.IsSingleColumnPrimaryKey() || schema.UsesSyntheticRowID() {
  69. return nil
  70. }
  71. if v, ok := lookupRowValue(row, schema.PrimaryKey); ok && v != nil {
  72. return nil
  73. }
  74. pkCol, ok := schema.GetColumn(schema.PrimaryKey)
  75. if !ok || !isIntegerColumnType(pkCol.Type) {
  76. return nil
  77. }
  78. id, err := e.session.GetNextRowID(tableName)
  79. if err != nil {
  80. return err
  81. }
  82. row[schema.PrimaryKey] = id
  83. return nil
  84. }
  85. // lookupRowValue resolves a row value case-insensitively.
  86. func lookupRowValue(row storage.Row, name string) (interface{}, bool) {
  87. if v, ok := row[name]; ok {
  88. return v, true
  89. }
  90. for k, v := range row {
  91. if strings.EqualFold(k, name) {
  92. return v, true
  93. }
  94. }
  95. return nil, false
  96. }
  97. // isIntegerColumnType reports whether a declared type has integer affinity.
  98. func isIntegerColumnType(typeName string) bool {
  99. return strings.Contains(strings.ToUpper(typeName), "INT")
  100. }
  101. // conflictMatcher describes one uniqueness constraint used to resolve an
  102. // INSERT conflict. index is nil for the primary key.
  103. type conflictMatcher struct {
  104. index *storage.Index
  105. primaryKey bool
  106. }
  107. // insertConflictMatchers returns the constraints that should be replaced for an
  108. // INSERT. A statement-level INSERT OR REPLACE replaces on every uniqueness
  109. // constraint; otherwise only indexes declaring ON CONFLICT REPLACE are
  110. // replaced.
  111. func (e *Executor) insertConflictMatchers(tableName string, schema *storage.Schema, stmtReplace bool) ([]conflictMatcher, error) {
  112. var matchers []conflictMatcher
  113. if stmtReplace {
  114. matchers = append(matchers, conflictMatcher{primaryKey: true})
  115. }
  116. indexes, err := e.session.ListTableIndexes(tableName)
  117. if err != nil {
  118. return nil, err
  119. }
  120. for _, idx := range indexes {
  121. if !idx.Unique {
  122. continue
  123. }
  124. if !stmtReplace && !strings.EqualFold(idx.OnConflict, "REPLACE") {
  125. continue
  126. }
  127. matchers = append(matchers, conflictMatcher{index: idx})
  128. }
  129. return matchers, nil
  130. }
  131. // matcherConflicts returns the durable/overlay rows that the candidate would
  132. // conflict with on a single matcher, using a primary-key point read or an
  133. // index-key lookup rather than a full table scan.
  134. func (e *Executor) matcherConflicts(tableName string, schema *storage.Schema, m conflictMatcher, candidate storage.Row) ([]storage.Row, error) {
  135. if m.primaryKey {
  136. pk, err := schema.PrimaryKeyForRow(candidate)
  137. if err != nil {
  138. // A missing or NULL key component cannot conflict; the insert fails
  139. // its NOT NULL constraint instead.
  140. return nil, nil
  141. }
  142. row, err := e.session.GetByPK(tableName, pk)
  143. if err == storage.ErrKeyNotFound {
  144. return nil, nil
  145. }
  146. if err != nil {
  147. return nil, err
  148. }
  149. return []storage.Row{row}, nil
  150. }
  151. isNull, err := e.table.IndexValueContainsNull(m.index, candidate)
  152. if err != nil {
  153. return nil, err
  154. }
  155. if isNull {
  156. return nil, nil
  157. }
  158. key, err := e.table.IndexRowKey(m.index, candidate)
  159. if err != nil {
  160. return nil, err
  161. }
  162. return e.session.SelectByIndexKey(tableName, m.index, key)
  163. }
  164. // hasAnyInsertConflict checks every uniqueness constraint. SQLite's
  165. // statement-level OR IGNORE and targetless DO NOTHING apply to any conflict,
  166. // not just the primary key.
  167. func (e *Executor) hasAnyInsertConflict(tableName string, schema *storage.Schema, candidate storage.Row) (bool, error) {
  168. matchers := []conflictMatcher{{primaryKey: true}}
  169. indexes, err := e.session.ListTableIndexes(tableName)
  170. if err != nil {
  171. return false, err
  172. }
  173. for _, index := range indexes {
  174. if index.Unique {
  175. matchers = append(matchers, conflictMatcher{index: index})
  176. }
  177. }
  178. for _, matcher := range matchers {
  179. rows, err := e.matcherConflicts(tableName, schema, matcher, candidate)
  180. if err != nil {
  181. return false, err
  182. }
  183. if len(rows) > 0 {
  184. return true, nil
  185. }
  186. }
  187. return false, nil
  188. }
  189. // resolveInsertConflicts removes existing rows that conflict with candidate on
  190. // any constraint that resolves to REPLACE. It runs inside the statement's
  191. // atomic DML block so the deletes and the subsequent insert commit together.
  192. func (e *Executor) resolveInsertConflicts(tableName string, schema *storage.Schema, candidate storage.Row, stmtReplace bool) error {
  193. matchers, err := e.insertConflictMatchers(tableName, schema, stmtReplace)
  194. if err != nil {
  195. return err
  196. }
  197. if len(matchers) == 0 {
  198. return nil
  199. }
  200. // Collect matching rows through point/index lookups, then delete them by
  201. // primary key. A row may match several constraints, so deduplicate.
  202. toDelete := make(map[string]storage.Row)
  203. for _, m := range matchers {
  204. rows, err := e.matcherConflicts(tableName, schema, m, candidate)
  205. if err != nil {
  206. return err
  207. }
  208. for _, row := range rows {
  209. pk, err := schema.PrimaryKeyForRow(row)
  210. if err != nil {
  211. return err
  212. }
  213. toDelete[pk] = row
  214. }
  215. }
  216. if len(toDelete) == 0 {
  217. return nil
  218. }
  219. for pk := range toDelete {
  220. if _, deleted, derr := e.session.DeleteByPK(tableName, pk); derr != nil {
  221. return derr
  222. } else if !deleted {
  223. return fmt.Errorf("ON CONFLICT REPLACE row disappeared during delete")
  224. }
  225. }
  226. return nil
  227. }