upsert

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2024 License: MIT Imports: 6 Imported by: 0

README

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrepareNamedQuery

func PrepareNamedQuery[T any](ctx context.Context, db *sqlx.DB, tableName string, val T, skipCols ...string) (*sqlx.NamedStmt, error)

Types

type Columns

type Columns[T any] []StructColumn[T]

func StructColumns

func StructColumns[T any](mVal T) (Columns[T], error)

Tag "db" - name of the column in the database Tag "pk" - any non-empty value defines the column for conflict resolution Tag store:"-" skips the field in any case

func (Columns[T]) DBs

func (c Columns[T]) DBs() []string

func (Columns[T]) PKs

func (c Columns[T]) PKs() []string

type StructColumn

type StructColumn[T any] struct {
	StructName string
	DBName     string
	IsPK       bool
}

type Upserter

type Upserter interface {
	// returns database name of primary key columnts
	UpsertPrimaryKeyColumns() []string
	// returns database name of skipped columns
	UpsertSkipColumns() []string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL