Skip to content

Commit

Permalink
Batch results at localhost in raw text format.
Browse files Browse the repository at this point in the history
  • Loading branch information
giuliocn committed Aug 29, 2024
1 parent 84a0ec5 commit ad1dad8
Showing 1 changed file with 83 additions and 53 deletions.
136 changes: 83 additions & 53 deletions examples/batch/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"net/http"
"strings"

pgx "github.com/jackc/pgx/v5"
pgconn "github.com/jackc/pgx/v5/pgconn"
Expand All @@ -20,48 +20,79 @@ type PgxPoolInterface interface {
}

type ExampleBatch struct {
batch *pgx.Batch
br pgx.BatchResults
db PgxPoolInterface
batch *pgx.Batch
br pgx.BatchResults
db PgxPoolInterface
output strings.Builder
}

func (ex *ExampleBatch) insertRow(fields ...string) (err error) {
for i, value := range fields {
fields[i] = "$$" + value + "$$"
}
sql := `INSERT INTO metadata (title, authors, subject, description)
VALUES
(` + strings.Join(fields[:4], ", ") + ");"
_, err = ex.db.Exec(context.Background(), sql)
return err
}

func (ex *ExampleBatch) databaseSetup() (err error) {
// Create a new table 'ledger'
sql := `CREATE TABLE IF NOT EXISTS ledger (
id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
description TEXT NOT NULL,
amount BIGINT NOT NULL);`
// Create a new table 'metadata'
sql := `
CREATE TABLE IF NOT EXISTS metadata (
id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
title TEXT NOT NULL,
authors TEXT NOT NULL,
subject TEXT NOT NULL,
description TEXT NOT NULL);
DELETE FROM metadata ;
INSERT INTO metadata (title, authors, subject, description)
VALUES
($$A Journey Through the Alps$$, $$John Doe, Jane Smith$$, $$Hiking, Nature, Travel$$, $$Explore the breathtaking beauty of the Alps on a scenic hiking adventure. Discover hidden trails, alpine lakes, and charming mountain villages.$$),
($$The Art of Baking: A Beginner's Guide$$, $$Emily Baker$$, $$Cooking, Baking, Food$$, $$Learn the fundamentals of baking and create delicious treats from scratch. Master techniques like kneading dough, frosting cakes, and piping cookies.$$),
($$The History of Ancient Rome$$, $$David Johnson$$, $$History, Ancient Rome, Civilization$$, $$Delve into the fascinating history of the Roman Empire. Explore its rise to power, its cultural achievements, and its eventual decline.$$);
`
_, err = ex.db.Exec(context.Background(), sql)
return err
}

func (ex *ExampleBatch) printResults(file io.Writer) (err error) {
func (ex *ExampleBatch) printResults(w http.ResponseWriter, req *http.Request) {

var temp strings.Builder

// Iterate over a batch of queued queries
for index, query := range ex.batch.QueuedQueries {
for _, query := range ex.batch.QueuedQueries {

// Read results from the current query
rows, err := ex.br.Query()
if err != nil {
return fmt.Errorf("iterateResults: %s", err)
rows, _ := ex.br.Query()

// Print SQL field of the current query
temp.WriteString(fmt.Sprintf("%v \n", query.SQL))

// Iterate over the selected records
//
for rows.Next() {
err := rows.Err()
if err != nil {
return
}

values, err := rows.Values()
if err != nil {
return
}

// Convert values to a string
temp.WriteString(fmt.Sprintf("%v \n", values))
}
}

if index > 0 {
// Print SQL field of the current query
fmt.Fprintf(file, "%v \n", query.SQL)

// Iterate over the selected records
//
var id, amount, descr = int64(0), int64(0), string("")
_, err = pgx.ForEachRow(rows, []any{&id, &descr, &amount}, func() error {
descr = "\"" + descr + "\""
fmt.Fprintf(file, "- %24v, amount: %d \n", descr, amount)
return err
})
}
if ex.output.Len() == 0 {
ex.output = temp
}
fmt.Fprint(w, ex.output.String())

return err
}

func (ex *ExampleBatch) requestBatch() (err error) {
Expand All @@ -79,10 +110,6 @@ func (ex *ExampleBatch) requestBatch() (err error) {

func (ex *ExampleBatch) Close() (err error) {

// Delete all rows in table ledger
sql := `DELETE FROM ledger ;`
_, err = ex.db.Exec(context.Background(), sql)

// Close batch results object
ex.br.Close()

Expand All @@ -99,34 +126,37 @@ func main() {
if err != nil {
panic(err)
}
defer db.Close()

// Setup the example
var example = ExampleBatch{db: db, batch: &pgx.Batch{}}
// Setup the database
var example = ExampleBatch{
db: db,
batch: &pgx.Batch{},
}
if err = example.databaseSetup(); err != nil {
panic(err)
}

// Add SQL queries to the queue
example.batch.Queue(
`INSERT INTO ledger(description, amount) VALUES ($1, $2), ($3, $4)`,
"first item", 1, "second item", 2)

example.batch.Queue("SELECT * FROM ledger")
example.batch.Queue("SELECT * FROM ledger WHERE amount = 1")

// Send a batch request and store results
defer example.Close()

// Add an example to database table
example.insertRow(
"The Adventures of Captain Pickle",
"Timothy T. Turtle",
"Adventure, Fantasy",
"Join Captain Pickle...",
)

// Add SQL queries to the queue for a batch operation
example.batch.Queue("SELECT title FROM metadata")
example.batch.Queue("SELECT authors FROM metadata")
example.batch.Queue("SELECT subject, description FROM metadata")

// Send the batch request to database
if err = example.requestBatch(); err != nil {
panic(err)
}

// Print batch result to ...
if err = example.printResults(os.Stdout); err != nil {
panic(err)
}
http.HandleFunc("/", example.printResults)
_ = http.ListenAndServe(":8080", nil)

// Close the example
if err = example.Close(); err != nil {
panic(err)
}
}

0 comments on commit ad1dad8

Please sign in to comment.