78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"math/rand"
|
|
"time"
|
|
|
|
"git.ksdemosapps.com/kylesoda/pgx-learning/internal/config"
|
|
"git.ksdemosapps.com/kylesoda/pgx-learning/internal/models"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func generateTasks(count int) []models.Task {
|
|
tasks := make([]models.Task, count)
|
|
|
|
for i := 1; i <= count; i++ {
|
|
tasks[i-1] = models.Task{
|
|
Text: fmt.Sprintf("random task Nº %v", i),
|
|
Completed: rand.Float64() > 0.5,
|
|
}
|
|
}
|
|
|
|
return tasks
|
|
}
|
|
|
|
func saveTasks(db *pgxpool.Pool, ctx context.Context, tasks []models.Task) error {
|
|
start := time.Now()
|
|
|
|
rowsCopied, err := db.CopyFrom(
|
|
ctx,
|
|
pgx.Identifier{"tasks"},
|
|
[]string{"text", "completed"},
|
|
pgx.CopyFromSlice(len(tasks), func(i int) ([]any, error) {
|
|
return []any{
|
|
(tasks)[i].Text,
|
|
(tasks)[i].Completed,
|
|
}, nil
|
|
}),
|
|
)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("Error al realizar el CopyFrom: %w", err)
|
|
}
|
|
|
|
duration := time.Since(start)
|
|
fmt.Printf("Se insertaron exitosamente %d registros en %v\n", rowsCopied, duration)
|
|
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("Starting seed process")
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
|
|
db, err := pgxpool.New(ctx, config.Db.Url)
|
|
if err != nil {
|
|
log.Fatalf("Unable to create connection pool: %v", err)
|
|
} else {
|
|
fmt.Println("Successfully connected to the database")
|
|
}
|
|
defer db.Close()
|
|
|
|
count := 100000
|
|
fmt.Printf("Generando %d registros...\n", count)
|
|
tasks := generateTasks(count)
|
|
|
|
if err := saveTasks(db, ctx, tasks); err != nil {
|
|
log.Fatalf("Unexpected error: %v", err)
|
|
} else {
|
|
fmt.Println("Database seed completed succesfully")
|
|
}
|
|
}
|