MCPcopy
hub / github.com/gogf/gf / doMergeInsert

Method doMergeInsert

contrib/drivers/dm/dm_do_insert.go:68–164  ·  view source on GitHub ↗

doMergeInsert implements MERGE-based insert operations for DM database. When withUpdate is true, it performs upsert (insert or update). When withUpdate is false, it performs insert ignore (insert only when no conflict).

(
	ctx context.Context,
	link gdb.Link, table string, list gdb.List, option gdb.DoInsertOption, withUpdate bool,
)

Source from the content-addressed store, hash-verified

66// When withUpdate is true, it performs upsert (insert or update).
67// When withUpdate is false, it performs insert ignore (insert only when no conflict).
68func (d *Driver) doMergeInsert(
69 ctx context.Context,
70 link gdb.Link, table string, list gdb.List, option gdb.DoInsertOption, withUpdate bool,
71) (result sql.Result, err error) {
72 // If OnConflict is not specified, automatically get the primary key of the table
73 conflictKeys := option.OnConflict
74 if len(conflictKeys) == 0 {
75 primaryKeys, err := d.Core.GetPrimaryKeys(ctx, table)
76 if err != nil {
77 return nil, gerror.WrapCode(
78 gcode.CodeInternalError,
79 err,
80 `failed to get primary keys for table`,
81 )
82 }
83 foundPrimaryKey := false
84 for _, primaryKey := range primaryKeys {
85 for dataKey := range list[0] {
86 if strings.EqualFold(dataKey, primaryKey) {
87 foundPrimaryKey = true
88 break
89 }
90 }
91 if foundPrimaryKey {
92 break
93 }
94 }
95 if !foundPrimaryKey {
96 return nil, gerror.NewCodef(
97 gcode.CodeMissingParameter,
98 `Replace/Save/InsertIgnore operation requires conflict detection: `+
99 `either specify OnConflict() columns or ensure table '%s' has a primary key in the data`,
100 table,
101 )
102 }
103 // TODO consider composite primary keys.
104 conflictKeys = primaryKeys
105 }
106
107 var (
108 one = list[0]
109 oneLen = len(one)
110 charL, charR = d.GetChars()
111 conflictKeySet = gset.NewStrSet(false)
112
113 // queryHolders: Handle data with Holder that need to be merged
114 // queryValues: Handle data that need to be merged
115 // insertKeys: Handle valid keys that need to be inserted
116 // insertValues: Handle values that need to be inserted
117 // updateValues: Handle values that need to be updated (only when withUpdate=true)
118 queryHolders = make([]string, oneLen)
119 queryValues = make([]any, oneLen)
120 insertKeys = make([]string, oneLen)
121 insertValues = make([]string, oneLen)
122 updateValues []string
123 )
124
125 // conflictKeys slice type conv to set type

Callers 2

doSaveMethod · 0.95
doInsertIgnoreMethod · 0.95

Calls 12

GetCharsMethod · 0.95
DoExecMethod · 0.95
WrapCodeFunction · 0.92
NewCodefFunction · 0.92
NewStrSetFunction · 0.92
ToUpperFunction · 0.92
GetPrimaryKeysMethod · 0.80
parseSqlForMergeFunction · 0.70
AddMethod · 0.65
ContainsMethod · 0.65
RowsAffectedMethod · 0.45

Tested by

no test coverage detected