From 79fd8195cd5b95107843de402663bfe32c5d3d67 Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Tue, 19 Mar 2024 06:51:07 +0100 Subject: [PATCH] add sql query generation --- app/app.go | 52 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/app/app.go b/app/app.go index 01d84f6..0eee54e 100644 --- a/app/app.go +++ b/app/app.go @@ -4,8 +4,10 @@ import ( "database/sql" "errors" "fmt" - "os" + // "os" + "strings" + nq "github.com/Knetic/go-namedParameterQuery" "gitnet.fr/deblan/database-anonymizer/config" "gitnet.fr/deblan/database-anonymizer/data" "gitnet.fr/deblan/database-anonymizer/database" @@ -33,8 +35,6 @@ func (a *App) ApplyRule(c config.SchemaConfigData, globalColumns map[string]stri c.PrimaryKey = []string{"id"} } - fmt.Printf("%+v\n", c.PrimaryKey) - rows := database.GetRows(a.Db, query) for key, row := range rows { @@ -86,14 +86,50 @@ func (a *App) ApplyRule(c config.SchemaConfigData, globalColumns map[string]stri rows[key][col] = value } - fmt.Printf("%+v\n", rows[key]) - rows[key] = a.UpdateRow(rows[key]) - fmt.Printf("%+v\n", rows[key]) - os.Exit(0) } - // fmt.Printf("%+v\n", rows) + var scan any + + for _, row := range rows { + updates := []string{} + pkeys := []string{} + + for col, value := range row { + if value.IsUpdated { + updates = append(updates, fmt.Sprintf("%s=:%s", col, col)) + } + } + + for _, col := range c.PrimaryKey { + pkeys = append(pkeys, fmt.Sprintf("%s=:%s", col, col)) + } + + if len(updates) > 0 { + sql := fmt.Sprintf( + "UPDATE %s SET %s WHERE %s", + c.Table, + strings.Join(updates, ", "), + strings.Join(pkeys, " AND "), + ) + + stmt := nq.NewNamedParameterQuery(sql) + + for col, value := range row { + if value.IsUpdated { + stmt.SetValue(col, value.Value) + } + } + + for _, col := range c.PrimaryKey { + stmt.SetValue(col, row[col].Value) + } + + r := a.Db.QueryRow(stmt.GetParsedQuery(), (stmt.GetParsedParameters())...).Scan(&scan) + + fmt.Printf("%+v\n", r) + } + } return nil }