| 1 |
// Copyright (c) 2024 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package dbutil |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"regexp" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// Array is an interface for small fixed-size arrays. |
| 16 |
// It exists because generics can't specify array sizes: https://github.com/golang/go/issues/44253 |
| 17 |
type Array interface { |
| 18 |
[0]any | [1]any | [2]any | [3]any | [4]any | [5]any | [6]any | [7]any | [8]any | [9]any | |
| 19 |
[10]any | [11]any | [12]any | [13]any | [14]any | [15]any | [16]any | [17]any | [18]any | [19]any | |
| 20 |
[20]any | [21]any | [22]any | [23]any | [24]any | [25]any | [26]any | [27]any | [28]any | [29]any |
| 21 |
} |
| 22 |
|
| 23 |
// MassInsertable represents a struct that contains dynamic values for a mass insert query. |
| 24 |
type MassInsertable[T Array] interface { |
| 25 |
GetMassInsertValues() T |
| 26 |
} |
| 27 |
|
| 28 |
// MassInsertBuilder contains pre-validated templates for building mass insert SQL queries. |
| 29 |
type MassInsertBuilder[Item MassInsertable[DynamicParams], StaticParams Array, DynamicParams Array] struct { |
| 30 |
queryTemplate string |
| 31 |
placeholderTemplate string |
| 32 |
} |
| 33 |
|
| 34 |
// NewMassInsertBuilder creates a new MassInsertBuilder that can build mass insert database queries. |
| 35 |
// |
| 36 |
// Parameters in mass insert queries are split into two types: static parameters |
| 37 |
// and dynamic parameters. Static parameters are the same for all items being |
| 38 |
// inserted, while dynamic parameters are different for each item. |
| 39 |
// |
| 40 |
// The given query should be a normal INSERT query for a single row. It can also |
| 41 |
// have ON CONFLICT clauses, as long as the clause uses `excluded` instead of |
| 42 |
// positional parameters. |
| 43 |
// |
| 44 |
// The placeholder template is used to replace the `VALUES` part of the given |
| 45 |
// query. It should contain a positional placeholder ($1, $2, ...) for each |
| 46 |
// static placeholder, and a fmt directive (`$%d`) for each dynamic placeholder. |
| 47 |
// |
| 48 |
// The given query and placeholder template are validated here and the function |
| 49 |
// will panic if they're invalid (e.g. if the `VALUES` part of the insert query |
| 50 |
// can't be found, or if the placeholder template doesn't have the right things). |
| 51 |
// The idea is to use this function to populate a global variable with the mass |
| 52 |
// insert builder, so the panic will happen at startup if the query or |
| 53 |
// placeholder template are invalid (instead of returning an error when trying |
| 54 |
// to use the query later). |
| 55 |
// |
| 56 |
// Example: |
| 57 |
// |
| 58 |
// type Message struct { |
| 59 |
// ChatID int |
| 60 |
// RemoteID string |
| 61 |
// MXID id.EventID |
| 62 |
// Timestamp time.Time |
| 63 |
// } |
| 64 |
// |
| 65 |
// func (msg *Message) GetMassInsertValues() [3]any { |
| 66 |
// return [3]any{msg.RemoteID, msg.MXID, msg.Timestamp.UnixMilli()} |
| 67 |
// } |
| 68 |
// |
| 69 |
// const insertMessageQuery = `INSERT INTO message (chat_id, remote_id, mxid, timestamp) VALUES ($1, $2, $3, $4)` |
| 70 |
// var massInsertMessageBuilder = dbutil.NewMassInsertBuilder[Message, [2]any](insertMessageQuery, "($1, $%d, $%d, $%d, $%d)") |
| 71 |
// |
| 72 |
// func DoMassInsert(ctx context.Context, messages []*Message) error { |
| 73 |
// query, params := massInsertMessageBuilder.Build([1]any{messages[0].ChatID}, messages) |
| 74 |
// return db.Exec(ctx, query, params...) |
| 75 |
// } |
| 76 |
func NewMassInsertBuilder[Item MassInsertable[DynamicParams], StaticParams Array, DynamicParams Array]( |
| 77 |
singleInsertQuery, placeholderTemplate string, |
| 78 |
) *MassInsertBuilder[Item, StaticParams, DynamicParams] { |
| 79 |
var dyn DynamicParams |
| 80 |
var stat StaticParams |
| 81 |
totalParams := len(dyn) + len(stat) |
| 82 |
mainQueryVariablePlaceholderParts := make([]string, totalParams) |
| 83 |
for i := 0; i < totalParams; i++ { |
| 84 |
mainQueryVariablePlaceholderParts[i] = fmt.Sprintf(`\$%d`, i+1) |
| 85 |
} |
| 86 |
mainQueryVariablePlaceholderRegex := regexp.MustCompile(fmt.Sprintf(`\(\s*%s\s*\)`, strings.Join(mainQueryVariablePlaceholderParts, `\s*,\s*`))) |
| 87 |
queryPlaceholders := mainQueryVariablePlaceholderRegex.FindAllString(singleInsertQuery, -1) |
| 88 |
if len(queryPlaceholders) == 0 { |
| 89 |
panic(fmt.Errorf("invalid insert query: placeholders not found")) |
| 90 |
} else if len(queryPlaceholders) > 1 { |
| 91 |
panic(fmt.Errorf("invalid insert query: multiple placeholders found")) |
| 92 |
} |
| 93 |
for i := 0; i < len(stat); i++ { |
| 94 |
if !strings.Contains(placeholderTemplate, fmt.Sprintf("$%d", i+1)) { |
| 95 |
panic(fmt.Errorf("invalid placeholder template: static placeholder $%d not found", i+1)) |
| 96 |
} |
| 97 |
} |
| 98 |
if strings.Contains(placeholderTemplate, fmt.Sprintf("$%d", len(stat)+1)) { |
| 99 |
panic(fmt.Errorf("invalid placeholder template: non-static placeholder $%d found", len(stat)+1)) |
| 100 |
} |
| 101 |
fmtParams := make([]any, len(dyn)) |
| 102 |
for i := 0; i < len(dyn); i++ { |
| 103 |
fmtParams[i] = fmt.Sprintf("$%d", len(stat)+i+1) |
| 104 |
} |
| 105 |
formattedPlaceholder := fmt.Sprintf(placeholderTemplate, fmtParams...) |
| 106 |
if strings.Contains(formattedPlaceholder, "!(EXTRA string=") { |
| 107 |
panic(fmt.Errorf("invalid placeholder template: extra string found")) |
| 108 |
} |
| 109 |
for i := 0; i < len(dyn); i++ { |
| 110 |
if !strings.Contains(formattedPlaceholder, fmt.Sprintf("$%d", len(stat)+i+1)) { |
| 111 |
panic(fmt.Errorf("invalid placeholder template: dynamic placeholder $%d not found", len(stat)+i+1)) |
| 112 |
} |
| 113 |
} |
| 114 |
return &MassInsertBuilder[Item, StaticParams, DynamicParams]{ |
| 115 |
queryTemplate: strings.Replace(singleInsertQuery, queryPlaceholders[0], "%s", 1), |
| 116 |
placeholderTemplate: placeholderTemplate, |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// Build constructs a ready-to-use mass insert SQL query using the prepared templates in this builder. |
| 121 |
// |
| 122 |
// This method always only produces one query. If there are lots of items, |
| 123 |
// chunking them beforehand may be required to avoid query parameter limits. |
| 124 |
// For example, SQLite (3.32+) has a limit of 32766 parameters by default, |
| 125 |
// while Postgres allows up to 65535. To find out if there are too many items, |
| 126 |
// divide the maximum number of parameters by the number of dynamic columns in |
| 127 |
// your data and subtract the number of static columns. |
| 128 |
// |
| 129 |
// Example of chunking input data: |
| 130 |
// |
| 131 |
// var mib dbutil.MassInsertBuilder |
| 132 |
// var db *dbutil.Database |
| 133 |
// func MassInsert(ctx context.Context, ..., data []T) error { |
| 134 |
// return db.DoTxn(ctx, nil, func(ctx context.Context) error { |
| 135 |
// for _, chunk := range exslices.Chunk(data, 100) { |
| 136 |
// query, params := mib.Build(staticParams) |
| 137 |
// _, err := db.Exec(ctx, query, params...) |
| 138 |
// if err != nil { |
| 139 |
// return err |
| 140 |
// } |
| 141 |
// } |
| 142 |
// return nil |
| 143 |
// } |
| 144 |
// } |
| 145 |
func (mib *MassInsertBuilder[Item, StaticParams, DynamicParams]) Build(static StaticParams, data []Item) (query string, params []any) { |
| 146 |
var itemValues DynamicParams |
| 147 |
params = make([]any, len(static)+len(itemValues)*len(data)) |
| 148 |
placeholders := make([]string, len(data)) |
| 149 |
for i := 0; i < len(static); i++ { |
| 150 |
params[i] = static[i] |
| 151 |
} |
| 152 |
fmtParams := make([]any, len(itemValues)) |
| 153 |
for i, item := range data { |
| 154 |
baseIndex := len(static) + len(itemValues)*i |
| 155 |
itemValues = item.GetMassInsertValues() |
| 156 |
for j := 0; j < len(itemValues); j++ { |
| 157 |
params[baseIndex+j] = itemValues[j] |
| 158 |
fmtParams[j] = baseIndex + j + 1 |
| 159 |
} |
| 160 |
placeholders[i] = fmt.Sprintf(mib.placeholderTemplate, fmtParams...) |
| 161 |
} |
| 162 |
query = fmt.Sprintf(mib.queryTemplate, strings.Join(placeholders, ", ")) |
| 163 |
return |
| 164 |
} |