diff options
| -rw-r--r-- | src/db/db.go | 9 | ||||
| -rw-r--r-- | src/user/user.go | 9 |
2 files changed, 14 insertions, 4 deletions
diff --git a/src/db/db.go b/src/db/db.go index 6f617c2..d74c874 100644 --- a/src/db/db.go +++ b/src/db/db.go @@ -16,6 +16,8 @@ type Database struct { p *pgxpool.Pool } +type DbValues pgx.NamedArgs + func NewDb(config *conf.Conf) *Database { pool, err := pgxpool.New(context.Background(), config.Db.Url) if err != nil { @@ -33,13 +35,16 @@ func NewDb(config *conf.Conf) *Database { } } -func (d *Database) InsertTable(table string, columns []string, values pgx.NamedArgs) error { +func (d *Database) InsertTable(table string, columns []string, values DbValues) error { columnstr := stringifyColumns(columns, "") valuesstr := stringifyColumns(columns, "@") query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s) RETURNING *", table, columnstr, valuesstr) log.Println(query, values) + // Convert DbValues to pgx.NamedArgs type to use NamedArgs type features + namedArgs := pgx.NamedArgs(values) + // TODO Use r.Context() from HTTP Request? ctx := context.Background() - row, err := d.p.Exec(ctx, query, values) + row, err := d.p.Exec(ctx, query, namedArgs) if err != nil { return err } diff --git a/src/user/user.go b/src/user/user.go index e35c7c5..d9fca6b 100644 --- a/src/user/user.go +++ b/src/user/user.go @@ -6,7 +6,6 @@ import ( "fmt" "time" - "github.com/jackc/pgx/v5" "gitlab.com/alexkavon/newsstand/src/db" "golang.org/x/crypto/argon2" ) @@ -23,11 +22,17 @@ type User struct { Db *db.Database } +func NewUser(d *db.Database) *User { + return &User{ + Db: d, + } +} + func (u *User) Insert() error { err := u.Db.InsertTable( "users", []string{"username", "secret", "email"}, - pgx.NamedArgs{"username": u.Username, "secret": string(u.hash), "email": u.Email}, + db.DbValues{"username": u.Username, "secret": string(u.hash), "email": u.Email}, ) if err != nil { return err |
