Skip to content

Commit

Permalink
✨ feat: tracked all query SQL stmt executed #10
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed Sep 30, 2023
1 parent ec92b12 commit 0ce10f0
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 44 deletions.
25 changes: 20 additions & 5 deletions qb.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,16 @@ func (q *QbDB) Limit(value int64) *QbDB {

// Drop drops >=1 tables
func (q *QbDB) Drop(tables string) (sql.Result, error) {
return q.Sql().Exec(fmt.Sprintf("%s%s", "DROP TABLE ", tables))
query := fmt.Sprintf("%s%s", "DROP TABLE ", tables)
setCacheExecuteStmt(query)
return q.Sql().Exec(query)
}

// Truncate clears >=1 tables
func (q *QbDB) Truncate(tables string) (sql.Result, error) {
return q.Sql().Exec(fmt.Sprintf("%s%s", "TRUNCATE ", tables))
query := fmt.Sprintf("%s%s", "TRUNCATE ", tables)
setCacheExecuteStmt(query)
return q.Sql().Exec(query)
}

// DropIfExists drops >=1 tables if they are existent
Expand All @@ -182,7 +186,9 @@ func (q *QbDB) DropIfExists(tables ...string) (result sql.Result, err error) {

// Rename renames from - to new table name
func (q *QbDB) Rename(from, to string) (sql.Result, error) {
return q.Sql().Exec(fmt.Sprintf("%s%s%s%s", "ALTER TABLE ", from, " RENAME TO ", to))
query := fmt.Sprintf("%s%s%s%s", "ALTER TABLE ", from, " RENAME TO ", to)
setCacheExecuteStmt(query)
return q.Sql().Exec(query)
}

// From prepares sql stmt to set data from another table, ex.:
Expand Down Expand Up @@ -219,6 +225,7 @@ func (q *QbDB) PrintQueryWithExit() {
// HasTable determines whether table exists in particular schema
func (q *QbDB) HasTable(schema, table string) (tblExists bool, err error) {
query := fmt.Sprintf("SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = '%s' AND tablename = '%s')", schema, table)
setCacheExecuteStmt(query)
err = q.Sql().QueryRow(query).Scan(&tblExists)
return
}
Expand All @@ -229,8 +236,8 @@ func (q *QbDB) HasColumns(schema, table string, columns ...string) (colsExists b
for _, v := range columns { // todo: find a way to check columns in 1 query
andColumns = " AND column_name = '" + v + "'"
query := fmt.Sprintf("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='%s' AND table_name='%s'"+andColumns+")", schema, table)
setCacheExecuteStmt(query)
err = q.Sql().QueryRow(query).Scan(&colsExists)

if !colsExists { // if at least once col doesn't exist - return false, nil
return
}
Expand All @@ -245,6 +252,7 @@ func (q *QbDB) Exists() (ok bool, err error) {
return false, errTableCallBeforeOp
}
query := `SELECT EXISTS(SELECT 1 FROM "` + builder.table + `" ` + builder.buildClauses() + `)`
setCacheExecuteStmt(query)
err = q.Sql().QueryRow(query, prepareValues(q.Builder.whereBindings)...).Scan(&ok)
return
}
Expand Down Expand Up @@ -307,7 +315,9 @@ func (q *QbDB) Chunk(amount int64, fn func(rows []map[string]interface{}) bool)
// buildSelect constructs a query for select statement
func (q *qbBuilder) buildSelect() string {
query := `SELECT ` + strings.Join(q.columns, `, `) + ` FROM ` + q.table
return fmt.Sprintf("%s%s", query, q.buildClauses())
v := fmt.Sprintf("%s%s", query, q.buildClauses())
setCacheExecuteStmt(v)
return v
}

// builds query string clauses
Expand Down Expand Up @@ -352,9 +362,14 @@ func (q *QbDB) increaseAndDecrease(column, sign string, on uint64) (int64, error
return 0, errTableCallBeforeOp
}
query := `UPDATE "` + q.Builder.table + `" SET ` + column + ` = ` + column + sign + strconv.FormatUint(on, 10)
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query)
if err != nil {
return 0, err
}
return result.RowsAffected()
}

func (q *QbDB) GetRawSQL() string {
return getCacheExecuteStmt()
}
5 changes: 5 additions & 0 deletions qb_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,8 @@ var (
errTableCallBeforeOp = fmt.Errorf("sql: there was no Table() call with table name set")
errTransactionModeWithoutTx = fmt.Errorf("sql: there was no *sql.Tx object set properly")
)

var (
// Cache Execute Stmt will be stored value for the query SQL has been called before
cacheExecuteStmt string = ""
)
10 changes: 10 additions & 0 deletions qb_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,3 +337,13 @@ func composeComment(tableName string, column *qbColumn) string {
}
return ""
}

// SetCacheExecuteStmt to storage query SQL native executed
func setCacheExecuteStmt(query string) {
cacheExecuteStmt = query
}

// GetCacheExecuteStmt return the query SQL have just executed
func getCacheExecuteStmt() string {
return cacheExecuteStmt
}
14 changes: 10 additions & 4 deletions qb_ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func (q *QbDB) Insert(data map[string]any) error {
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `)`
setCacheExecuteStmt(query)
_, err := q.Sql().Exec(query, values...)
if err != nil {
return err
Expand All @@ -37,6 +38,7 @@ func (q *QbTxn) Insert(data map[string]any) error {
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `)`
setCacheExecuteStmt(query)
_, err := q.Tx.Exec(query, values...)
if err != nil {
return err
Expand All @@ -55,6 +57,7 @@ func (q *QbDB) InsertGetId(data map[string]any) (uint64, error) {
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) RETURNING id`
setCacheExecuteStmt(query)
var id uint64
err := q.Sql().QueryRow(query, values...).Scan(&id)
if err != nil {
Expand All @@ -74,6 +77,7 @@ func (q *QbTxn) InsertGetId(data map[string]any) (uint64, error) {
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) RETURNING id`
setCacheExecuteStmt(query)
var id uint64
err := q.Tx.QueryRow(query, values...).Scan(&id)
if err != nil {
Expand Down Expand Up @@ -132,20 +136,19 @@ func (q *QbDB) Update(data map[string]any) (int64, error) {
setVal := ""
l := len(columns)
for k, col := range columns {
// setVal += col + " = " + bindings[k]
setVal += fmt.Sprintf("%s%s%s", col, " = ", bindings[k])
if k < l-1 {
setVal += ", "
}
}
query := `UPDATE "` + q.Builder.table + `" SET ` + setVal
if IsStringNotEmpty(q.Builder.from) {
// query += " FROM " + q.Builder.from
query += fmt.Sprintf("%s%s", " FROM ", q.Builder.from)
}
q.Builder.startBindingsAt = l + 1
query += q.Builder.buildClauses()
values = append(values, prepareValues(q.Builder.whereBindings)...)
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query, values...)
if err != nil {
return 0, err
Expand All @@ -167,20 +170,19 @@ func (q *QbTxn) Update(data map[string]any) (int64, error) {
setVal := ""
l := len(columns)
for k, col := range columns {
// setVal += col + " = " + bindings[k]
setVal += fmt.Sprintf("%s%s%s", col, " = ", bindings[k])
if k < l-1 {
setVal += ", "
}
}
query := `UPDATE "` + q.Builder.table + `" SET ` + setVal
if IsStringNotEmpty(q.Builder.from) {
// query += " FROM " + q.Builder.from
query += fmt.Sprintf("%s%s", " FROM ", q.Builder.from)
}
q.Builder.startBindingsAt = l + 1
query += q.Builder.buildClauses()
values = append(values, prepareValues(q.Builder.whereBindings)...)
setCacheExecuteStmt(query)
result, err := q.Tx.Exec(query, values...)
if err != nil {
return 0, err
Expand All @@ -200,6 +202,7 @@ func (q *QbDB) Delete() (int64, error) {
}
query := `DELETE FROM "` + q.Builder.table + `"`
query += q.Builder.buildClauses()
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query, prepareValues(q.Builder.whereBindings)...)
if err != nil {
return 0, err
Expand All @@ -219,6 +222,7 @@ func (q *QbTxn) Delete() (int64, error) {
}
query := `DELETE FROM "` + q.Builder.table + `"`
query += q.Builder.buildClauses()
setCacheExecuteStmt(query)
result, err := q.Tx.Exec(query, prepareValues(q.Builder.whereBindings)...)
if err != nil {
return 0, err
Expand All @@ -242,6 +246,7 @@ func (q *QbDB) Replace(data map[string]any, conflict string) (int64, error) {
columns[i] = fmt.Sprintf("%s%s%s", v, " = excluded.", v)
}
query += strings.Join(columns, ", ")
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query, values...)
if err != nil {
return 0, err
Expand All @@ -265,6 +270,7 @@ func (q *QbTxn) Replace(data map[string]any, conflict string) (int64, error) {
columns[i] = fmt.Sprintf("%s%s%s", v, " = excluded.", v)
}
query += strings.Join(columns, ", ")
setCacheExecuteStmt(query)
result, err := q.Tx.Exec(query, values...)
if err != nil {
return 0, err
Expand Down
71 changes: 36 additions & 35 deletions qb_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,40 +44,6 @@ func (q *QbDB) SchemaIfNotExists(tableName string, fn func(table *QbTable) error
return
}

func (q *QbDB) createIndices(indices []string) (result sql.Result, err error) {
if len(indices) == 0 {
return nil, fmt.Errorf("Indices is empty")
}
for _, idx := range indices {
if idx != "" {
result, err = q.Sql().Exec(idx)
if err != nil {
return nil, err
}
}
}
return
}

func (q *QbDB) createComments(comments []string) (result sql.Result, err error) {
for _, comment := range comments {
if comment != "" {
result, err = q.Sql().Exec(comment)
if err != nil {
return nil, err
}
}
}
return
}

func (q *QbTable) composeTableComment() string {
if q.comment != nil {
return "COMMENT ON TABLE " + q.tableName + " IS '" + *q.comment + "'"
}
return ""
}

// Increments creates auto incremented primary key integer column
func (q *QbTable) Increments(column string) *QbTable {
q.columns = append(q.columns, &qbColumn{Name: column, ColumnType: TypeSerial, IsPrimaryKey: true})
Expand Down Expand Up @@ -320,7 +286,7 @@ func (q *QbDB) createTable(t *QbTable) (result sql.Result, err error) {
comments = append(comments, composeComment(t.tableName, col))
}
query += ")"

setCacheExecuteStmt(query)
result, err = q.Sql().Exec(query)
if err != nil {
return nil, err
Expand Down Expand Up @@ -366,6 +332,7 @@ func (q *QbDB) modifyTable(t *QbTable) (result sql.Result, err error) {
query += SemiColon
}
}
setCacheExecuteStmt(query)
result, err = q.Sql().Exec(query)
if err != nil {
return nil, err
Expand All @@ -382,3 +349,37 @@ func (q *QbDB) modifyTable(t *QbTable) (result sql.Result, err error) {
}
return
}

func (q *QbDB) createIndices(indices []string) (result sql.Result, err error) {
if len(indices) == 0 {
return nil, fmt.Errorf("Indices is empty")
}
for _, idx := range indices {
if IsStringNotEmpty(idx) {
result, err = q.Sql().Exec(idx)
if err != nil {
return nil, err
}
}
}
return
}

func (q *QbDB) createComments(comments []string) (result sql.Result, err error) {
for _, comment := range comments {
if IsStringNotEmpty(comment) {
result, err = q.Sql().Exec(comment)
if err != nil {
return nil, err
}
}
}
return
}

func (q *QbTable) composeTableComment() string {
if q.comment != nil {
return "COMMENT ON TABLE " + q.tableName + " IS '" + *q.comment + "'"
}
return ""
}

0 comments on commit 0ce10f0

Please sign in to comment.