github.com/schemalex/git-schemalex@v0.0.0-20170921120917-b690b7f9e063/query.go (about)

     1  package gitschemalex
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  	"fmt"
     7  	"io"
     8  	"strings"
     9  
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  type query struct {
    14  	stmt string
    15  	args []interface{}
    16  }
    17  
    18  func (q *query) execute(ctx context.Context, db *sql.DB) error {
    19  	_, err := db.ExecContext(ctx, q.stmt, q.args...)
    20  	return errors.Wrap(err, `failed to execute query`)
    21  }
    22  
    23  func (q *query) dump(dst io.Writer) error {
    24  	fmt.Fprintf(dst, "%s;", q.stmt)
    25  	if len(q.args) > 0 {
    26  		fmt.Fprintf(dst, "%v", q.args)
    27  	}
    28  	fmt.Fprintf(dst, "\n\n")
    29  	return nil
    30  }
    31  
    32  type queryList []*query
    33  
    34  func queryListFromString(stmts string) queryList {
    35  	var l queryList
    36  	for _, stmt := range strings.Split(stmts, ";") {
    37  		stmt = strings.TrimSpace(stmt)
    38  		if len(stmt) == 0 {
    39  			continue
    40  		}
    41  		l.AppendStmt(stmt)
    42  	}
    43  	return l
    44  }
    45  
    46  func (l *queryList) AppendStmt(stmt string, args ...interface{}) {
    47  	*l = append(*l, &query{
    48  		stmt: stmt,
    49  		args: args,
    50  	})
    51  }
    52  
    53  func (l *queryList) dump(dst io.Writer) error {
    54  	for i, q := range *l {
    55  		if err := q.dump(dst); err != nil {
    56  			return errors.Wrapf(err, `failed to dump query %d`, i+1)
    57  		}
    58  	}
    59  	return nil
    60  }
    61  
    62  func (l *queryList) execute(ctx context.Context, db *sql.DB) error {
    63  	for i, q := range *l {
    64  		if err := q.execute(ctx, db); err != nil {
    65  			return errors.Wrapf(err, `failed to execute query %d`, i+1)
    66  		}
    67  	}
    68  	return nil
    69  }