Skip to content

Upsert struct into postgres using sqlx prepared statement

License

Notifications You must be signed in to change notification settings

covrom/sqlx-upsert-postgres

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sqlx-upsert-postgres

Insert or update (aka "upsert", "replace") structure into postgres table using sqlx prepared statement.

Basic usage

import (
    upsert "github.com/covrom/sqlx-upsert-postgres"
    "github.com/google/uuid"
    "github.com/jmoiron/sqlx"
)

type PgComment struct {
	ID        uuid.UUID    `db:"id" pk:"true"` // primary key for conflict resolving
	CreatedAt time.Time    `db:"created_at"`
	UpdatedAt time.Time    `db:"updated_at"`
	DeletedAt sql.NullTime `db:"deleted_at"`

	Description     string  `db:"description"`
	ComputedColumn  float64 `store:"-"` // skipped
}

el := PgComment{
    ID:              uuid.New(),
    CreatedAt:       time.Now(),
    UpdatedAt:       time.Now(),
    Description:     "this is a comment",
    ComputedColumn:  5.54,   // skipped in tag
}

st, err := upsert.PrepareNamedQuery[PgComment](ctx, pgdb, "comments", el)
if err != nil {
    return err
}
defer st.Close()

_, err = st.ExecContext(ctx, el)
if err != nil {
    return err
}

Full example

Example

About

Upsert struct into postgres using sqlx prepared statement

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages