2020-08-06 20:58:47 +03:00
|
|
|
package libsq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"sync"
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/record"
|
|
|
|
|
2023-04-02 22:49:45 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/source"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lga"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lgm"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg"
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/errz"
|
2021-01-04 05:56:22 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlmodel"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlz"
|
2020-08-06 20:58:47 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/driver"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DBWriter implements RecordWriter, writing
|
|
|
|
// records to a database table.
|
|
|
|
type DBWriter struct {
|
|
|
|
wg *sync.WaitGroup
|
|
|
|
cancelFn context.CancelFunc
|
|
|
|
destDB driver.Database
|
|
|
|
destTbl string
|
2023-05-22 18:08:14 +03:00
|
|
|
recordCh chan record.Record
|
2020-08-12 21:24:01 +03:00
|
|
|
bi *driver.BatchInsert
|
2020-08-06 20:58:47 +03:00
|
|
|
errCh chan error
|
|
|
|
errs []error
|
|
|
|
|
|
|
|
// preWriteHook, when non-nil, is invoked by the Open method before any
|
|
|
|
// records are written. This is useful when the recMeta or tx are
|
|
|
|
// needed to perform actions before insertion, such as creating
|
|
|
|
// the dest table on the fly.
|
2021-01-04 05:56:22 +03:00
|
|
|
preWriteHooks []DBWriterPreWriteHook
|
|
|
|
}
|
|
|
|
|
|
|
|
// DBWriterPreWriteHook is a function that is invoked before DBWriter
|
|
|
|
// begins writing.
|
2023-05-22 18:08:14 +03:00
|
|
|
type DBWriterPreWriteHook func(ctx context.Context, recMeta record.Meta, destDB driver.Database, tx sqlz.DB) error
|
2021-01-04 05:56:22 +03:00
|
|
|
|
|
|
|
// DBWriterCreateTableIfNotExistsHook returns a hook that
|
|
|
|
// creates destTblName if it does not exist.
|
|
|
|
func DBWriterCreateTableIfNotExistsHook(destTblName string) DBWriterPreWriteHook {
|
2023-05-22 18:08:14 +03:00
|
|
|
return func(ctx context.Context, recMeta record.Meta, destDB driver.Database, tx sqlz.DB) error {
|
2023-07-08 18:21:27 +03:00
|
|
|
db, err := destDB.DB(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
tblExists, err := destDB.SQLDriver().TableExists(ctx, db, destTblName)
|
2021-01-04 05:56:22 +03:00
|
|
|
if err != nil {
|
|
|
|
return errz.Err(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if tblExists {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
destColNames := recMeta.Names()
|
|
|
|
destColKinds := recMeta.Kinds()
|
|
|
|
destTblDef := sqlmodel.NewTableDef(destTblName, destColNames, destColKinds)
|
|
|
|
|
|
|
|
err = destDB.SQLDriver().CreateTable(ctx, tx, destTblDef)
|
|
|
|
if err != nil {
|
|
|
|
return errz.Wrapf(err, "failed to create dest table %s.%s", destDB.Source().Handle, destTblName)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewDBWriter returns a new writer than implements RecordWriter.
|
|
|
|
// The writer writes records from recordCh to destTbl
|
|
|
|
// in destDB. The recChSize param controls the size of recordCh
|
|
|
|
// returned by the writer's Open method.
|
2023-04-30 17:18:56 +03:00
|
|
|
func NewDBWriter(destDB driver.Database, destTbl string, recChSize int,
|
2022-12-18 11:35:59 +03:00
|
|
|
preWriteHooks ...DBWriterPreWriteHook,
|
|
|
|
) *DBWriter {
|
2020-08-06 20:58:47 +03:00
|
|
|
return &DBWriter{
|
2021-01-04 05:56:22 +03:00
|
|
|
destDB: destDB,
|
|
|
|
destTbl: destTbl,
|
2023-05-22 18:08:14 +03:00
|
|
|
recordCh: make(chan record.Record, recChSize),
|
2021-01-04 05:56:22 +03:00
|
|
|
errCh: make(chan error, 3),
|
|
|
|
wg: &sync.WaitGroup{},
|
|
|
|
preWriteHooks: preWriteHooks,
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Note: errCh has size 3 because that's the maximum number of
|
|
|
|
// errs that could be sent. Frequently only one err is sent,
|
|
|
|
// but sometimes there are additional errs, e.g. when
|
|
|
|
// ctx is done, we send ctx.Err, followed by any rollback err.
|
|
|
|
}
|
|
|
|
|
|
|
|
// Open implements RecordWriter.
|
2023-05-22 18:08:14 +03:00
|
|
|
func (w *DBWriter) Open(ctx context.Context, cancelFn context.CancelFunc, recMeta record.Meta) (
|
|
|
|
chan<- record.Record, <-chan error, error,
|
2022-12-18 11:35:59 +03:00
|
|
|
) {
|
2020-08-06 20:58:47 +03:00
|
|
|
w.cancelFn = cancelFn
|
|
|
|
|
2023-07-08 18:21:27 +03:00
|
|
|
db, err := w.destDB.DB(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// REVISIT: tx could potentially be passed to NewDBWriter?
|
2023-07-08 18:21:27 +03:00
|
|
|
tx, err := db.BeginTx(ctx, nil)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errz.Wrapf(err, "failed to open tx for %s.%s", w.destDB.Source().Handle, w.destTbl)
|
|
|
|
}
|
|
|
|
|
2021-01-04 05:56:22 +03:00
|
|
|
for _, hook := range w.preWriteHooks {
|
|
|
|
err = hook(ctx, recMeta, w.destDB, tx)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-04-30 17:18:56 +03:00
|
|
|
w.rollback(ctx, tx, err)
|
2020-08-06 20:58:47 +03:00
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
batchSize := driver.MaxBatchRows(w.destDB.SQLDriver(), len(recMeta.Names()))
|
2023-04-02 22:49:45 +03:00
|
|
|
w.bi, err = driver.NewBatchInsert(ctx, w.destDB.SQLDriver(), tx, w.destTbl, recMeta.Names(), batchSize)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-04-30 17:18:56 +03:00
|
|
|
w.rollback(ctx, tx, err)
|
2020-08-06 20:58:47 +03:00
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
w.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer func() {
|
|
|
|
// When the inserter goroutine finishes:
|
2020-08-12 21:24:01 +03:00
|
|
|
// - we close errCh (indicates that the DBWriter is done)
|
|
|
|
// - and mark wg as done, which the Wait method depends upon.
|
2020-08-06 20:58:47 +03:00
|
|
|
close(w.errCh)
|
|
|
|
w.wg.Done()
|
|
|
|
}()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
// ctx is done (e.g. cancelled), so we're going to rollback.
|
2023-04-30 17:18:56 +03:00
|
|
|
w.rollback(ctx, tx, ctx.Err())
|
2020-08-06 20:58:47 +03:00
|
|
|
return
|
|
|
|
|
|
|
|
case rec := <-w.recordCh:
|
|
|
|
if rec == nil {
|
|
|
|
// No more results on recordCh, it has been closed.
|
|
|
|
// It's time to commit the tx.
|
|
|
|
// Note that Commit automatically closes any stmts
|
|
|
|
// that were prepared by tx.
|
2020-08-12 21:24:01 +03:00
|
|
|
|
|
|
|
// Tell batch inserter that we're done sending records
|
|
|
|
close(w.bi.RecordCh)
|
|
|
|
|
|
|
|
err = <-w.bi.ErrCh // Wait for batch inserter to complete
|
|
|
|
if err != nil {
|
2023-05-03 15:36:10 +03:00
|
|
|
lg.FromContext(ctx).Error(err.Error())
|
2020-08-12 21:24:01 +03:00
|
|
|
w.addErrs(err)
|
2023-04-30 17:18:56 +03:00
|
|
|
w.rollback(ctx, tx, err)
|
2020-08-12 21:24:01 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
commitErr := errz.Err(tx.Commit())
|
|
|
|
if commitErr != nil {
|
2023-05-03 15:36:10 +03:00
|
|
|
lg.FromContext(ctx).Error(commitErr.Error())
|
2020-08-06 20:58:47 +03:00
|
|
|
w.addErrs(commitErr)
|
|
|
|
} else {
|
2023-05-03 15:36:10 +03:00
|
|
|
lg.FromContext(ctx).Debug("Tx commit success",
|
2023-04-02 22:49:45 +03:00
|
|
|
lga.Target, source.Target(w.destDB.Source(), w.destTbl))
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2020-08-12 21:24:01 +03:00
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
// rec is not nil, therefore we write it to the db
|
|
|
|
err = w.doInsert(ctx, rec)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-04-30 17:18:56 +03:00
|
|
|
w.rollback(ctx, tx, err)
|
2020-08-06 20:58:47 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, we successfully wrote rec to tx.
|
|
|
|
// Therefore continue to wait/select for the next
|
|
|
|
// element on recordCh (or for recordCh to close)
|
|
|
|
// or for ctx.Done indicating timeout or cancel etc.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return w.recordCh, w.errCh, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait implements RecordWriter.
|
|
|
|
func (w *DBWriter) Wait() (written int64, err error) {
|
|
|
|
w.wg.Wait()
|
|
|
|
if w.cancelFn != nil {
|
|
|
|
w.cancelFn()
|
|
|
|
}
|
2021-01-04 04:20:05 +03:00
|
|
|
|
|
|
|
if w.bi != nil {
|
|
|
|
written = w.bi.Written()
|
|
|
|
}
|
|
|
|
|
|
|
|
return written, errz.Combine(w.errs...)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// addErrs handles any non-nil err in errs by appending it to w.errs
|
|
|
|
// and sending it on w.errCh.
|
|
|
|
func (w *DBWriter) addErrs(errs ...error) {
|
|
|
|
for _, err := range errs {
|
|
|
|
if err != nil {
|
|
|
|
w.errs = append(w.errs, err)
|
|
|
|
w.errCh <- err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// rollback rolls back tx. Note that rollback or commit of the tx
|
2023-04-30 17:18:56 +03:00
|
|
|
// will close each of the tx's prepared statements, so we don't
|
2020-08-06 20:58:47 +03:00
|
|
|
// need to close those manually.
|
2023-04-30 17:18:56 +03:00
|
|
|
func (w *DBWriter) rollback(ctx context.Context, tx *sql.Tx, causeErrs ...error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// Guaranteed to be at least one causeErr
|
2023-07-09 04:34:53 +03:00
|
|
|
lg.FromContext(ctx).Error("failed to insert data: tx will rollback",
|
|
|
|
lga.Target, w.destDB.Source().Handle+"."+w.destTbl,
|
|
|
|
lga.Err, causeErrs[0])
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
rollbackErr := errz.Err(tx.Rollback())
|
2023-05-03 15:36:10 +03:00
|
|
|
lg.WarnIfError(lg.FromContext(ctx), lgm.TxRollback, rollbackErr)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
w.addErrs(causeErrs...)
|
|
|
|
w.addErrs(rollbackErr)
|
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
func (w *DBWriter) doInsert(ctx context.Context, rec record.Record) error {
|
2020-08-12 21:24:01 +03:00
|
|
|
err := w.bi.Munge(rec)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case err = <-w.bi.ErrCh:
|
|
|
|
return err
|
|
|
|
case w.bi.RecordCh <- rec:
|
|
|
|
return nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|