github.com/pavlo67/common@v0.5.3/common/sqllib/helpers.go (about)

     1  package sqllib
     2  
     3  import (
     4  	"database/sql"
     5  	"strings"
     6  
     7  	"github.com/pavlo67/common/common/auth"
     8  
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  type CorrectWildcards func(query string) string
    13  
    14  const CantPrepare = "can't .Prepare(%s)"
    15  const CantQuery = "can't .Query('%s', %#v)"
    16  const CantExec = "can't .Exec('%s', %#v)"
    17  
    18  const CantGetLastInsertId = "can't .LastInsertId('%s', %#v)"
    19  const CantGetRowsAffected = "can't .RowsAffected('%s', %#v)"
    20  const NoRowOnQuery = "no row on query('%s', %#v)"
    21  const CantScanQueryRow = "can't scan query row ('%s', %#v)"
    22  const RowsError = "error on .Rows ('%s', %#v)"
    23  
    24  var ErrNoTable = errors.New("table doesn't exist")
    25  
    26  func SQLList(table, fields, condition string, identity *auth.Identity) string {
    27  	if strings.TrimSpace(condition) != "" {
    28  		condition = " WHERE " + condition
    29  	}
    30  
    31  	var limit, order string
    32  
    33  	//ranges := options.GetRanges()
    34  	//
    35  	//if ranges != nil {
    36  	//	if len(ranges.OrderBy) > 0 {
    37  	//		order = strings.Join(ranges.OrderBy, ", ")
    38  	//	}
    39  	//
    40  	//	if ranges.Offset+ranges.Limit > 0 {
    41  	//		if ranges.Limit > 0 {
    42  	//			limit += " LIMIT " + strconv.FormatUint(ranges.Limit, 10)
    43  	//		}
    44  	//
    45  	//		if ranges.Offset > 0 {
    46  	//			limit += " OFFSET " + strconv.FormatUint(ranges.Offset, 10)
    47  	//		}
    48  	//
    49  	//		// TODO: sqlite & mysql version
    50  	//	}
    51  	// " ORDER BY " +
    52  	//}
    53  
    54  	return "SELECT " + fields + " FROM " + table + condition + order + limit
    55  }
    56  
    57  func SQLCount(table, condition string, _ *auth.Identity) string {
    58  	query := "SELECT COUNT(*) FROM " + table
    59  
    60  	if strings.TrimSpace(condition) != "" {
    61  		return query + " WHERE " + condition
    62  	}
    63  
    64  	return query
    65  }
    66  
    67  //const defaultPageLengthStr = "200"
    68  //
    69  //func OrderAndLimit(sortBy []string, limits []uint64) string {
    70  //	var sortStr, limitsStr string
    71  //	if len(sortBy) > 0 {
    72  //		for _, s := range sortBy {
    73  //			if s == "" {
    74  //				continue
    75  //			}
    76  //			desc := ""
    77  //			if s[len(s)-1:] == "-" {
    78  //				s = s[:len(s)-1]
    79  //				desc = " DESC"
    80  //			} else if s[len(s)-1:] == "+" {
    81  //				s = s[:len(s)-1]
    82  //			}
    83  //			if sortStr != "" {
    84  //				sortStr += ", "
    85  //			}
    86  //			sortStr += "`" + s + "`" + desc
    87  //		}
    88  //		if sortStr != "" {
    89  //			sortStr = " ORDER BY " + sortStr
    90  //		}
    91  //	}
    92  //	if len(limits) > 1 {
    93  //		// limit[0] can be equal to 0
    94  //		var pageLengthStr string
    95  //		if limits[1] > 0 {
    96  //			pageLengthStr = strconv.FormatUint(limits[1], 10)
    97  //		} else {
    98  //			pageLengthStr = defaultPageLengthStr
    99  //		}
   100  //		limitsStr = " LIMIT " + strconv.FormatUint(limits[0], 10) + ", " + pageLengthStr
   101  //	} else if len(limits) > 0 {
   102  //		if limits[0] > 0 {
   103  //			limitsStr = " LIMIT " + strconv.FormatUint(limits[0], 10)
   104  //		} else {
   105  //			limitsStr = " LIMIT " + defaultPageLengthStr
   106  //		}
   107  //	}
   108  //	return sortStr + limitsStr
   109  //}
   110  
   111  type SqlStmt struct {
   112  	Stmt **sql.Stmt
   113  	Sql  string
   114  }
   115  
   116  func Prepare(dbh *sql.DB, sqlQuery string, stmt **sql.Stmt) error {
   117  	var err error
   118  
   119  	*stmt, err = dbh.Prepare(sqlQuery)
   120  	if err != nil {
   121  		return errors.Wrapf(err, "can't dbh.Prepare(%s)", sqlQuery)
   122  	}
   123  
   124  	return nil
   125  }
   126  
   127  func Exec(dbh *sql.DB, sqlQuery string, values ...interface{}) (*sql.Result, error) {
   128  	stmt, err := dbh.Prepare(sqlQuery)
   129  	if err != nil {
   130  		return nil, errors.Wrapf(err, CantPrepare, sqlQuery)
   131  	}
   132  
   133  	res, err := stmt.Exec(values...)
   134  	if err != nil {
   135  		return nil, errors.Wrapf(err, CantExec, sqlQuery, values)
   136  	}
   137  
   138  	return &res, nil
   139  }
   140  
   141  func Query(dbh *sql.DB, sqlQuery string, values ...interface{}) (*sql.Rows, error) {
   142  	stmt, err := dbh.Prepare(sqlQuery)
   143  	if err != nil {
   144  		return nil, errors.Wrapf(err, CantPrepare, sqlQuery)
   145  	}
   146  
   147  	rows, err := stmt.Query(values...)
   148  	if err != nil {
   149  		return nil, errors.Wrapf(err, CantExec, sqlQuery, values)
   150  	}
   151  
   152  	return rows, nil
   153  }
   154  
   155  func QueryStrings(stmt *sql.Stmt, sql string, values ...interface{}) (results []string, err error) {
   156  	rows, err := stmt.Query(values...)
   157  	if err != nil {
   158  		return nil, errors.Wrapf(err, CantExec, sql, values)
   159  	}
   160  	defer rows.Close()
   161  
   162  	for rows.Next() {
   163  		var r string
   164  		if err := rows.Scan(&r); err != nil {
   165  			return results, errors.Wrapf(err, CantScanQueryRow, sql, values)
   166  		}
   167  
   168  		results = append(results, r)
   169  	}
   170  
   171  	err = rows.Err()
   172  	if err != nil {
   173  		return results, errors.Wrapf(err, CantScanQueryRow, sql, values)
   174  	}
   175  
   176  	return results, nil
   177  }
   178  
   179  //func QueryIDs(stmt *sql.Stmt, sql string, values ...interface{}) (ids []uint64, err error) {
   180  //	rows, err := stmt.Query(values...)
   181  //	if err != nil {
   182  //		return nil, errors.Wrapf(err, basis.CantExecQuery, sql, values)
   183  //	}
   184  //	defer rows.Close()
   185  //
   186  //	for rows.Right() {
   187  //		var id uint64
   188  //		if err := rows.Scan(&id); err != nil {
   189  //			return ids, errors.Wrapf(err, CantScanQueryRow, sql, values)
   190  //		}
   191  //
   192  //		ids = append(ids, id)
   193  //	}
   194  //
   195  //	err = rows.Err()
   196  //	if err != nil {
   197  //		return ids, errors.Wrapf(err, CantScanQueryRow, sql, values)
   198  //	}
   199  //
   200  //	return ids, nil
   201  //}