|
| 1 | +package database |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/icinga/icinga-go-library/driver" |
| 6 | + "golang.org/x/exp/slices" |
| 7 | + "reflect" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// QueryBuilder is an addon for the DB type that takes care of all the database statement building shenanigans. |
| 12 | +// Note: This type is designed primarily for one-off use (monouso) and subsequent disposal and should only be |
| 13 | +// used to generate a single database query type. |
| 14 | +type QueryBuilder struct { |
| 15 | + subject interface{} |
| 16 | + columns []string |
| 17 | + excludedColumns []string |
| 18 | +} |
| 19 | + |
| 20 | +// NewQB returns a fully initialized *QueryBuilder instance for the given subject/struct. |
| 21 | +func NewQB(subject interface{}) *QueryBuilder { |
| 22 | + return &QueryBuilder{subject: subject} |
| 23 | +} |
| 24 | + |
| 25 | +// SetColumns sets the DB columns to be used when building the statements. |
| 26 | +// When you do not want the columns to be extracted dynamically, you can use this method to specify them manually. |
| 27 | +func (qb *QueryBuilder) SetColumns(columns ...string) { |
| 28 | + qb.columns = columns |
| 29 | +} |
| 30 | + |
| 31 | +// Exclude excludes the given columns from all the database statements. |
| 32 | +func (qb *QueryBuilder) Exclude(columns ...string) { |
| 33 | + qb.excludedColumns = columns |
| 34 | +} |
| 35 | + |
| 36 | +// Delete returns a DELETE statement for the query builders subject filtered by ID. |
| 37 | +func (qb *QueryBuilder) Delete() string { |
| 38 | + return qb.DeleteBy("id") |
| 39 | +} |
| 40 | + |
| 41 | +// DeleteBy returns a DELETE statement for the query builders subject filtered by the given column. |
| 42 | +func (qb *QueryBuilder) DeleteBy(column string) string { |
| 43 | + return fmt.Sprintf(`DELETE FROM "%s" WHERE "%s" IN (?)`, TableName(qb.subject), column) |
| 44 | +} |
| 45 | + |
| 46 | +// Insert returns an INSERT INTO statement for the query builders subject. |
| 47 | +func (qb *QueryBuilder) Insert(db *DB) (string, int) { |
| 48 | + columns := qb.BuildColumns(db) |
| 49 | + |
| 50 | + return fmt.Sprintf( |
| 51 | + `INSERT INTO "%s" ("%s") VALUES (%s)`, |
| 52 | + TableName(qb.subject), |
| 53 | + strings.Join(columns, `", "`), |
| 54 | + fmt.Sprintf(":%s", strings.Join(columns, ", :")), |
| 55 | + ), len(columns) |
| 56 | +} |
| 57 | + |
| 58 | +// InsertIgnore returns an INSERT statement for the query builders subject for |
| 59 | +// which the database ignores rows that have already been inserted. |
| 60 | +func (qb *QueryBuilder) InsertIgnore(db *DB) (string, int) { |
| 61 | + columns := qb.BuildColumns(db) |
| 62 | + table := TableName(qb.subject) |
| 63 | + |
| 64 | + var clause string |
| 65 | + switch db.DriverName() { |
| 66 | + case driver.MySQL: |
| 67 | + // MySQL treats UPDATE id = id as a no-op. |
| 68 | + clause = fmt.Sprintf(`ON DUPLICATE KEY UPDATE "%s" = "%s"`, columns[0], columns[0]) |
| 69 | + case driver.PostgreSQL: |
| 70 | + clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO NOTHING", table) |
| 71 | + } |
| 72 | + |
| 73 | + return fmt.Sprintf( |
| 74 | + `INSERT INTO "%s" ("%s") VALUES (%s) %s`, |
| 75 | + table, |
| 76 | + strings.Join(columns, `", "`), |
| 77 | + fmt.Sprintf(":%s", strings.Join(columns, ", :")), |
| 78 | + clause, |
| 79 | + ), len(columns) |
| 80 | +} |
| 81 | + |
| 82 | +// Select returns a SELECT statement from the query builders subject for the specified columns struct. |
| 83 | +// When the query builders subject is of type Scoper, a WHERE clause is appended to the statement. |
| 84 | +// Note: Excluded columns have no influence on the result of this method, as you're explicitly providing |
| 85 | +// which columns are going to be selected. |
| 86 | +func (qb *QueryBuilder) Select(db *DB, columns interface{}) string { |
| 87 | + var scoper Scoper |
| 88 | + if sc, ok := qb.subject.(Scoper); ok { |
| 89 | + scoper = sc |
| 90 | + } |
| 91 | + |
| 92 | + return qb.SelectColumns(db, scoper, db.BuildColumns(columns)...) |
| 93 | +} |
| 94 | + |
| 95 | +// SelectColumns returns a SELECT statement from the query builders subject for the specified columns |
| 96 | +// filtered by the given scoper/column. Note: The scoper argument must be either of type Scoper or string. |
| 97 | +// Note: Excluded columns have no influence on the result of this method, as you're explicitly providing |
| 98 | +// which columns are going to be selected. |
| 99 | +func (qb *QueryBuilder) SelectColumns(db *DB, scoper interface{}, columns ...string) string { |
| 100 | + query := fmt.Sprintf(`SELECT "%s" FROM "%s"`, strings.Join(columns, `", "`), TableName(qb.subject)) |
| 101 | + where, placeholders := qb.Where(db, scoper) |
| 102 | + if placeholders > 0 { |
| 103 | + query += ` WHERE ` + where |
| 104 | + } |
| 105 | + |
| 106 | + return query |
| 107 | +} |
| 108 | + |
| 109 | +// Update returns an UPDATE statement for the query builders subject filter by ID column. |
| 110 | +func (qb *QueryBuilder) Update(db *DB) (string, int) { |
| 111 | + return qb.UpdateScoped(db, "id") |
| 112 | +} |
| 113 | + |
| 114 | +// UpdateScoped returns an UPDATE statement for the query builders subject filtered by the given column/scoper. |
| 115 | +// Note: The scoper argument must be either of type Scoper or string. |
| 116 | +func (qb *QueryBuilder) UpdateScoped(db *DB, scoper interface{}) (string, int) { |
| 117 | + columns := qb.BuildColumns(db) |
| 118 | + set := make([]string, 0, len(columns)) |
| 119 | + |
| 120 | + for _, col := range columns { |
| 121 | + set = append(set, fmt.Sprintf(`"%s" = :%s`, col, col)) |
| 122 | + } |
| 123 | + |
| 124 | + placeholders := len(columns) |
| 125 | + query := `UPDATE "%s" SET %s` |
| 126 | + if where, count := qb.Where(db, scoper); count > 0 { |
| 127 | + placeholders += count |
| 128 | + query += ` WHERE ` + where |
| 129 | + } |
| 130 | + |
| 131 | + return fmt.Sprintf(query, TableName(qb.subject), strings.Join(set, ", ")), placeholders |
| 132 | +} |
| 133 | + |
| 134 | +// Upsert returns an upsert statement for the query builders subject. |
| 135 | +func (qb *QueryBuilder) Upsert(db *DB) (string, int) { |
| 136 | + var updateColumns []string |
| 137 | + if upserter, ok := qb.subject.(Upserter); ok { |
| 138 | + updateColumns = db.BuildColumns(upserter.Upsert()) |
| 139 | + } else { |
| 140 | + updateColumns = qb.BuildColumns(db) |
| 141 | + } |
| 142 | + |
| 143 | + return qb.UpsertColumns(db, updateColumns...) |
| 144 | +} |
| 145 | + |
| 146 | +// UpsertColumns returns an upsert statement for the query builders subject and the specified update columns. |
| 147 | +func (qb *QueryBuilder) UpsertColumns(db *DB, updateColumns ...string) (string, int) { |
| 148 | + insertColumns := qb.BuildColumns(db) |
| 149 | + table := TableName(qb.subject) |
| 150 | + |
| 151 | + var clause, setFormat string |
| 152 | + switch db.DriverName() { |
| 153 | + case driver.MySQL: |
| 154 | + clause = "ON DUPLICATE KEY UPDATE" |
| 155 | + setFormat = `"%[1]s" = VALUES("%[1]s")` |
| 156 | + case driver.PostgreSQL: |
| 157 | + clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO UPDATE SET", table) |
| 158 | + setFormat = `"%[1]s" = EXCLUDED."%[1]s"` |
| 159 | + } |
| 160 | + |
| 161 | + set := make([]string, 0, len(updateColumns)) |
| 162 | + for _, col := range updateColumns { |
| 163 | + set = append(set, fmt.Sprintf(setFormat, col)) |
| 164 | + } |
| 165 | + |
| 166 | + return fmt.Sprintf( |
| 167 | + `INSERT INTO "%s" ("%s") VALUES (%s) %s %s`, |
| 168 | + table, |
| 169 | + strings.Join(insertColumns, `", "`), |
| 170 | + fmt.Sprintf(":%s", strings.Join(insertColumns, ", :")), |
| 171 | + clause, |
| 172 | + strings.Join(set, ", "), |
| 173 | + ), len(insertColumns) |
| 174 | +} |
| 175 | + |
| 176 | +// Where returns a WHERE clause with named placeholder conditions built from the |
| 177 | +// specified scoper/column combined with the AND operator. |
| 178 | +func (qb *QueryBuilder) Where(db *DB, subject interface{}) (string, int) { |
| 179 | + var columns []string |
| 180 | + t := reflect.TypeOf(subject) |
| 181 | + if t.Kind() == reflect.String { |
| 182 | + columns = []string{subject.(string)} |
| 183 | + } else if t.Kind() == reflect.Struct || t.Kind() == reflect.Pointer { |
| 184 | + if scoper, ok := subject.(Scoper); ok { |
| 185 | + return qb.Where(db, scoper.Scope()) |
| 186 | + } |
| 187 | + |
| 188 | + columns = db.BuildColumns(subject) |
| 189 | + } |
| 190 | + |
| 191 | + where := make([]string, 0, len(columns)) |
| 192 | + for _, col := range columns { |
| 193 | + where = append(where, fmt.Sprintf(`"%s" = :%s`, col, col)) |
| 194 | + } |
| 195 | + |
| 196 | + return strings.Join(where, ` AND `), len(columns) |
| 197 | +} |
| 198 | + |
| 199 | +// BuildColumns returns all the Query Builder columns (if specified), otherwise they are |
| 200 | +// determined dynamically using its subject. Additionally, it checks whether columns need |
| 201 | +// to be excluded and proceeds accordingly. |
| 202 | +func (qb *QueryBuilder) BuildColumns(db *DB) []string { |
| 203 | + var columns []string |
| 204 | + if len(qb.columns) > 0 { |
| 205 | + columns = qb.columns |
| 206 | + } else { |
| 207 | + columns = db.BuildColumns(qb.subject) |
| 208 | + } |
| 209 | + |
| 210 | + if len(qb.excludedColumns) > 0 { |
| 211 | + columns = slices.DeleteFunc(append([]string(nil), columns...), func(column string) bool { |
| 212 | + for _, exclude := range qb.excludedColumns { |
| 213 | + if exclude == column { |
| 214 | + return true |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + return false |
| 219 | + }) |
| 220 | + } |
| 221 | + |
| 222 | + return columns |
| 223 | +} |
0 commit comments