Skip to content

Commit

Permalink
feat: improve batch create API (#745)
Browse files Browse the repository at this point in the history
  • Loading branch information
aeneasr authored Nov 10, 2023
1 parent 33c73f3 commit e1d7bd3
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions sqlxx/batch/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ func buildInsertQueryValues[T any](dialect string, mapper *reflectx.Mapper, colu
case "updated_at":
field.Set(reflect.ValueOf(now))
case "id":
if field.Interface().(uuid.UUID) != uuid.Nil {
if value, ok := field.Interface().(uuid.UUID); ok && value != uuid.Nil {
break // breaks switch, not for
} else if value, ok := field.Interface().(string); ok && len(value) > 0 {
break // breaks switch, not for
} else if dialect == dbal.DriverCockroachDB {
// This is a special case:
Expand Down Expand Up @@ -165,16 +167,33 @@ func buildInsertQueryValues[T any](dialect string, mapper *reflectx.Mapper, colu
return values, nil
}

type createOptions struct {
onConflict string
}

type option func(*createOptions)

func OnConflictDoNothing() func(*createOptions) {
return func(o *createOptions) {
o.onConflict = "ON CONFLICT DO NOTHING"
}
}

// Create batch-inserts the given models into the database using a single INSERT statement.
// The models are either all created or none.
func Create[T any](ctx context.Context, p *TracerConnection, models []*T) (err error) {
func Create[T any](ctx context.Context, p *TracerConnection, models []*T, opts ...option) (err error) {
ctx, span := p.Tracer.Tracer().Start(ctx, "persistence.sql.batch.Create")
defer otelx.End(span, &err)

if len(models) == 0 {
return nil
}

options := &createOptions{}
for _, opt := range opts {
opt(options)
}

var v T
model := pop.NewModel(v, ctx)

Expand All @@ -197,10 +216,11 @@ func Create[T any](ctx context.Context, p *TracerConnection, models []*T) (err e
}

query := conn.Dialect.TranslateSQL(fmt.Sprintf(
"INSERT INTO %s (%s) VALUES\n%s\n%s",
"INSERT INTO %s (%s) VALUES\n%s\n%s\n%s",
queryArgs.TableName,
queryArgs.ColumnsDecl,
queryArgs.Placeholders,
options.onConflict,
returningClause,
))

Expand Down

0 comments on commit e1d7bd3

Please sign in to comment.