1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
|
//go:build linux && cgo && !agent
package db
import (
"errors"
"fmt"
"go/ast"
"go/types"
"slices"
"strings"
"golang.org/x/tools/go/packages"
"github.com/lxc/incus/v6/cmd/generate-database/file"
"github.com/lxc/incus/v6/cmd/generate-database/lex"
)
// Stmt generates a particular database query statement.
type Stmt struct {
entity string // Name of the database entity
kind string // Kind of statement to generate
config map[string]string // Configuration parameters
localPath string
pkgs []*types.Package // Package to perform for struct declaration lookups
defs map[*ast.Ident]types.Object // Defs maps identifiers to the objects they define
registeredSQLStmts map[string]string // Lookup for SQL statements registered during this execution, which are therefore not included in the parsed package information
}
// NewStmt return a new statement code snippet for running the given kind of
// query against the given database entity.
func NewStmt(localPath string, parsedPkgs []*packages.Package, entity, kind string, config map[string]string, registeredSQLStmts map[string]string) (*Stmt, error) {
defs := map[*ast.Ident]types.Object{}
for _, pkg := range parsedPkgs {
for k, v := range pkg.TypesInfo.Defs {
_, ok := defs[k]
if ok {
return nil, fmt.Errorf("Entity definition already exists: %q: %q", pkg.Name, v.Name())
}
defs[k] = v
}
}
pkgTypes, err := parsePkgDecls(entity, kind, parsedPkgs)
if err != nil {
return nil, err
}
stmt := &Stmt{
localPath: localPath,
entity: entity,
kind: kind,
config: config,
pkgs: pkgTypes,
defs: defs,
registeredSQLStmts: registeredSQLStmts,
}
return stmt, nil
}
// Generate plumbing and wiring code for the desired statement.
func (s *Stmt) Generate(buf *file.Buffer) error {
kind := strings.Split(s.kind, "-by-")[0]
switch kind {
case "objects":
return s.objects(buf)
case "names":
return s.names(buf)
case "delete":
return s.delete(buf)
case "create":
return s.create(buf, false)
case "create-or-replace":
return s.create(buf, true)
case "id":
return s.id(buf)
case "rename":
return s.rename(buf)
case "update":
return s.update(buf)
default:
return fmt.Errorf("Unknown statement '%s'", s.kind)
}
}
// GenerateSignature is not used for statements.
func (s *Stmt) GenerateSignature(buf *file.Buffer) error {
return nil
}
func (s *Stmt) objects(buf *file.Buffer) error {
if strings.HasPrefix(s.kind, "objects-by") {
return s.objectsBy(buf)
}
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return err
}
table := mapping.TableName(s.entity, s.config["table"])
boiler := stmts["objects"]
fields := mapping.ColumnFields()
columns := make([]string, len(fields))
for i, field := range fields {
column, err := field.SelectColumn(mapping, table)
if err != nil {
return err
}
columns[i] = column
}
orderBy := []string{}
orderByFields := []*Field{}
for _, field := range fields {
if field.Config.Get("order") != "" {
orderByFields = append(orderByFields, field)
}
}
if len(orderByFields) < 1 {
orderByFields = mapping.NaturalKey()
}
for _, field := range orderByFields {
column, err := field.OrderBy(mapping, table)
if err != nil {
return err
}
orderBy = append(orderBy, column)
}
joinFields := mapping.ScalarFields()
joins := make([]string, 0, len(joinFields))
for _, field := range joinFields {
join, err := field.JoinClause(mapping, table)
if err != nil {
return err
}
if !slices.Contains(joins, join) {
joins = append(joins, join)
}
}
table += strings.Join(joins, "")
sql := fmt.Sprintf(boiler, strings.Join(columns, ", "), table, strings.Join(orderBy, ", "))
kind := strings.ReplaceAll(s.kind, "-", "_")
stmtName := stmtCodeVar(s.entity, kind)
if mapping.Type == ReferenceTable || mapping.Type == MapTable {
buf.L("const %s = `%s`", stmtName, sql)
} else {
s.register(buf, stmtName, sql)
}
return nil
}
// objectsBy parses the variable declaration produced by the 'objects' function, and appends a WHERE clause to its SQL
// string using the objects-by-<FIELD> field suffixes, and then creates a new variable declaration.
// Strictly, it will look for variables of the form 'var <entity>Objects = <database>.RegisterStmt(`SQL String`)'.
func (s *Stmt) objectsBy(buf *file.Buffer) error {
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return err
}
where := []string{}
filters := strings.Split(s.kind[len("objects-by-"):], "-and-")
sqlString, err := ParseStmt(stmtCodeVar(s.entity, "objects"), s.defs, s.registeredSQLStmts)
if err != nil {
return err
}
queryParts := strings.SplitN(sqlString, "ORDER BY", 2)
joinStr := " JOIN"
if strings.Contains(queryParts[0], " LEFT JOIN") {
joinStr = " LEFT JOIN"
}
preJoin, _, _ := strings.Cut(queryParts[0], joinStr)
_, tableName, _ := strings.Cut(preJoin, "FROM ")
tableName, _, _ = strings.Cut(tableName, "\n")
for _, filter := range filters {
field, err := mapping.FilterFieldByName(filter)
if err != nil {
return err
}
table, columnName, err := field.SQLConfig()
if err != nil {
return err
}
var column string
if table != "" && columnName != "" {
if field.IsScalar() {
column = columnName
} else {
column = table + "." + columnName
}
} else if field.IsScalar() {
column = lex.SnakeCase(field.Name)
} else {
column = mapping.FieldColumnName(field.Name, tableName)
}
coalesce, ok := field.Config["coalesce"]
if ok {
// Ensure filters operate on the coalesced value for fields using coalesce setting.
where = append(where, fmt.Sprintf("coalesce(%s, %s) = ? ", column, coalesce[0]))
} else {
where = append(where, fmt.Sprintf("%s = ? ", column))
}
}
queryParts[0] = fmt.Sprintf("%sWHERE ( %s)", queryParts[0], strings.Join(where, "AND "))
sqlString = strings.Join(queryParts, "\n ORDER BY")
s.register(buf, stmtCodeVar(s.entity, "objects", filters...), sqlString)
return nil
}
func (s *Stmt) names(buf *file.Buffer) error {
if strings.HasPrefix(s.kind, "names-by") {
return s.namesBy(buf)
}
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return err
}
if len(mapping.NaturalKey()) > 1 {
return errors.New("Can't return names for composite key objects")
}
table := mapping.TableName(s.entity, s.config["table"])
boiler := stmts["names"]
field := mapping.NaturalKey()[0]
column, err := field.SelectColumn(mapping, table)
if err != nil {
return err
}
orderByField := field
if field.Config.Get("order") != "" {
orderByField = field
}
orderBy, err := orderByField.OrderBy(mapping, table)
if err != nil {
return err
}
sql := fmt.Sprintf(boiler, column, table, orderBy)
kind := strings.ReplaceAll(s.kind, "-", "_")
stmtName := stmtCodeVar(s.entity, kind)
s.register(buf, stmtName, sql)
return nil
}
func (s *Stmt) namesBy(buf *file.Buffer) error {
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return err
}
if len(mapping.NaturalKey()) > 1 {
return errors.New("Can't return names for composite key objects")
}
where := []string{}
filters := strings.Split(s.kind[len("names-by-"):], "-and-")
sqlString, err := ParseStmt(stmtCodeVar(s.entity, "names"), s.defs, s.registeredSQLStmts)
if err != nil {
return err
}
queryParts := strings.SplitN(sqlString, "ORDER BY", 2)
_, tableName, _ := strings.Cut(queryParts[0], "FROM ")
tableName, _, _ = strings.Cut(tableName, "\n")
joins := []string{}
for _, filter := range filters {
field, err := mapping.FilterFieldByName(filter)
if err != nil {
return err
}
table, columnName, err := field.SQLConfig()
if err != nil {
return err
}
var column string
if table != "" && columnName != "" {
if field.IsScalar() {
column = columnName
} else {
column = table + "." + columnName
}
} else if field.IsScalar() {
join, err := field.JoinClause(mapping, tableName)
if err != nil {
return err
}
if !slices.Contains(joins, join) {
joins = append(joins, join)
}
column = field.joinConfig()
} else {
column = mapping.FieldColumnName(field.Name, tableName)
}
coalesce, ok := field.Config["coalesce"]
if ok {
// Ensure filters operate on the coalesced value for fields using coalesce setting.
where = append(where, fmt.Sprintf("coalesce(%s, %s) = ? ", column, coalesce[0]))
} else {
where = append(where, fmt.Sprintf("%s = ? ", column))
}
}
join := ""
if len(joins) > 0 {
join = strings.TrimLeftFunc(strings.Join(joins, ""), func(r rune) bool {
return r == ' ' || r == '\n'
})
join += "\n "
}
queryParts[0] = fmt.Sprintf("%s%sWHERE ( %s)", queryParts[0], join, strings.Join(where, "AND "))
sqlString = strings.Join(queryParts, "\n ORDER BY")
s.register(buf, stmtCodeVar(s.entity, "names", filters...), sqlString)
return nil
}
func (s *Stmt) create(buf *file.Buffer, replace bool) error {
entityCreate := lex.PascalCase(s.entity)
mapping, err := Parse(s.localPath, s.pkgs, entityCreate, s.kind)
if err != nil {
return fmt.Errorf("Parse entity struct: %w", err)
}
table := mapping.TableName(s.entity, s.config["table"])
all := mapping.ColumnFields("ID") // This exclude the ID column, which is autogenerated.
columns := make([]string, 0, len(all))
values := make([]string, 0, len(all))
for _, field := range all {
column, value, err := field.InsertColumn(mapping, table, s.defs, s.registeredSQLStmts)
if err != nil {
return err
}
if column == "" && value == "" {
continue
}
columns = append(columns, column)
values = append(values, value)
}
tmpl := stmts[s.kind]
if replace {
tmpl = stmts["replace"]
}
sql := fmt.Sprintf(tmpl, table, strings.Join(columns, ", "), strings.Join(values, ", "))
kind := strings.Replace(s.kind, "-", "_", -2)
stmtName := stmtCodeVar(s.entity, kind)
if mapping.Type == ReferenceTable || mapping.Type == MapTable {
buf.L("const %s = `%s`", stmtName, sql)
} else {
s.register(buf, stmtName, sql)
}
return nil
}
func (s *Stmt) id(buf *file.Buffer) error {
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return fmt.Errorf("Parse entity struct: %w", err)
}
table := mapping.TableName(s.entity, s.config["table"])
nk := mapping.NaturalKey()
where := make([]string, 0, len(nk))
joins := make([]string, 0, len(nk))
for _, field := range nk {
tableName, columnName, err := field.SQLConfig()
if err != nil {
return err
}
var column string
if field.IsScalar() {
column = field.joinConfig()
join, err := field.JoinClause(mapping, table)
if !slices.Contains(joins, join) {
joins = append(joins, join)
}
if err != nil {
return err
}
} else if tableName != "" && columnName != "" {
column = tableName + "." + columnName
} else {
column = mapping.FieldColumnName(field.Name, table)
}
where = append(where, fmt.Sprintf("%s = ?", column))
}
sql := fmt.Sprintf(stmts[s.kind], table, table+strings.Join(joins, ""), strings.Join(where, " AND "))
stmtName := stmtCodeVar(s.entity, "ID")
s.register(buf, stmtName, sql)
return nil
}
func (s *Stmt) rename(buf *file.Buffer) error {
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return err
}
table := mapping.TableName(s.entity, s.config["table"])
nk := mapping.NaturalKey()
updates := make([]string, 0, len(nk))
for _, field := range nk {
column, value, err := field.InsertColumn(mapping, table, s.defs, s.registeredSQLStmts)
if err != nil {
return err
}
if column == "" && value == "" {
continue
}
updates = append(updates, fmt.Sprintf("%s = %s", column, value))
}
updatedAt := ""
for _, field := range mapping.Fields {
if field.Config.Has("update_timestamp") {
updatedAt = fmt.Sprintf(", %s = ?", field.Column())
break
}
}
sql := fmt.Sprintf(stmts[s.kind], table, updatedAt, strings.Join(updates, " AND "))
kind := strings.ReplaceAll(s.kind, "-", "_")
stmtName := stmtCodeVar(s.entity, kind)
s.register(buf, stmtName, sql)
return nil
}
func (s *Stmt) update(buf *file.Buffer) error {
entityUpdate := lex.PascalCase(s.entity)
mapping, err := Parse(s.localPath, s.pkgs, entityUpdate, s.kind)
if err != nil {
return fmt.Errorf("Parse entity struct: %w", err)
}
table := mapping.TableName(s.entity, s.config["table"])
all := mapping.ColumnFields("ID") // This exclude the ID column, which is autogenerated.
updates := make([]string, 0, len(all))
for _, field := range all {
column, value, err := field.InsertColumn(mapping, table, s.defs, s.registeredSQLStmts)
if err != nil {
return err
}
if column == "" && value == "" {
continue
}
updates = append(updates, fmt.Sprintf("%s = %s", column, value))
}
sql := fmt.Sprintf(stmts[s.kind], table, strings.Join(updates, ", "), "id = ?")
kind := strings.ReplaceAll(s.kind, "-", "_")
stmtName := stmtCodeVar(s.entity, kind)
s.register(buf, stmtName, sql)
return nil
}
func (s *Stmt) delete(buf *file.Buffer) error {
mapping, err := Parse(s.localPath, s.pkgs, lex.PascalCase(s.entity), s.kind)
if err != nil {
return err
}
table := mapping.TableName(s.entity, s.config["table"])
var where string
if mapping.Type == ReferenceTable || mapping.Type == MapTable {
where = "%s_id = ?"
}
if strings.HasPrefix(s.kind, "delete-by") {
filters := strings.Split(s.kind[len("delete-by-"):], "-and-")
conditions := make([]string, 0, len(filters))
for _, filter := range filters {
field, err := mapping.FilterFieldByName(filter)
if err != nil {
return err
}
column, value, err := field.InsertColumn(mapping, table, s.defs, s.registeredSQLStmts)
if err != nil {
return err
}
if column == "" && value == "" {
continue
}
conditions = append(conditions, fmt.Sprintf("%s = %s", column, value))
}
where = strings.Join(conditions, " AND ")
}
sql := fmt.Sprintf(stmts["delete"], table, where)
kind := strings.ReplaceAll(s.kind, "-", "_")
stmtName := stmtCodeVar(s.entity, kind)
if mapping.Type == ReferenceTable || mapping.Type == MapTable {
buf.L("const %s = `%s`", stmtName, sql)
} else {
s.register(buf, stmtName, sql)
}
return nil
}
// Output a line of code that registers the given statement and declares the
// associated statement code global variable.
func (s *Stmt) register(buf *file.Buffer, stmtName, sql string) {
s.registeredSQLStmts[stmtName] = sql
if !strings.HasPrefix(sql, "`") || !strings.HasSuffix(sql, "`") {
sql = fmt.Sprintf("`\n%s\n`", sql)
}
buf.L("var %s = RegisterStmt(%s)", stmtName, sql)
}
// Map of boilerplate statements.
var stmts = map[string]string{
"names": "SELECT %s\n FROM %s\n ORDER BY %s",
"objects": "SELECT %s\n FROM %s\n ORDER BY %s",
"create": "INSERT INTO %s (%s)\n VALUES (%s)",
"replace": "INSERT OR REPLACE INTO %s (%s)\n VALUES (%s)",
"id": "SELECT %s.id FROM %s\n WHERE %s",
"rename": "UPDATE %s SET name = ?%s WHERE %s",
"update": "UPDATE %s\n SET %s\n WHERE %s",
"delete": "DELETE FROM %s WHERE %s",
}
|