From 287f1beb90252a2e90c47aa9981651c3fa7d97c5 Mon Sep 17 00:00:00 2001 From: Athurg Gooth Date: Sun, 8 Oct 2023 18:30:24 +0800 Subject: [PATCH] fix: create storage without some attributes (#2358) --- store/db/mysql/storage.go | 14 ++++++++++++-- store/db/sqlite/storage.go | 22 ++++++++++++---------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/store/db/mysql/storage.go b/store/db/mysql/storage.go index 1fd9cb9e..36507ee6 100644 --- a/store/db/mysql/storage.go +++ b/store/db/mysql/storage.go @@ -8,8 +8,18 @@ import ( ) func (d *DB) CreateStorage(ctx context.Context, create *store.Storage) (*store.Storage, error) { - stmt := "INSERT INTO `storage` (`name`, `type`, `config`) VALUES (?, ?, ?)" - result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Type, create.Config) + fields := []string{"`name`", "`type`", "`config`"} + placeholder := []string{"?", "?", "?"} + args := []any{create.Name, create.Type, create.Config} + + if create.ID != 0 { + fields = append(fields, "`id`") + placeholder = append(placeholder, "?") + args = append(args, create.ID) + } + + stmt := "INSERT INTO `storage` (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ")" + result, err := d.db.ExecContext(ctx, stmt, args...) if err != nil { return nil, err } diff --git a/store/db/sqlite/storage.go b/store/db/sqlite/storage.go index 705a4531..5d4d009a 100644 --- a/store/db/sqlite/storage.go +++ b/store/db/sqlite/storage.go @@ -8,16 +8,18 @@ import ( ) func (d *DB) CreateStorage(ctx context.Context, create *store.Storage) (*store.Storage, error) { - stmt := ` - INSERT INTO storage ( - name, - type, - config - ) - VALUES (?, ?, ?) - RETURNING id - ` - if err := d.db.QueryRowContext(ctx, stmt, create.Name, create.Type, create.Config).Scan( + fields := []string{"`name`", "`type`", "`config`"} + placeholder := []string{"?", "?", "?"} + args := []any{create.Name, create.Type, create.Config} + + if create.ID != 0 { + fields = append(fields, "`id`") + placeholder = append(placeholder, "?") + args = append(args, create.ID) + } + + stmt := "INSERT INTO `storage` (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ") RETURNING `id`" + if err := d.db.QueryRowContext(ctx, stmt, args...).Scan( &create.ID, ); err != nil { return nil, err