commit d9e6b2563a36ca59fdb41ee22ed2c1e50cdcc73d
parent f1a7d841bcae96c96867a5f9f29aae96eb5d81de
Author: Vetle Haflan <vetle@haflan.dev>
Date: Fri, 29 Jul 2022 12:14:39 +0200
Add pgtester app - for testing Postgres connection
Diffstat:
5 files changed, 62 insertions(+), 0 deletions(-)
diff --git a/pgtester/.gitignore b/pgtester/.gitignore
@@ -0,0 +1 @@
+pgtester
diff --git a/pgtester/build.sh b/pgtester/build.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+GOOS=linux GOARCH=amd64 go build \
+ -a -tags=prod,osusergo,netgo,sqlite_omit_load_extension \
+ -ldflags '-s -w -extldflags "-static"' .
diff --git a/pgtester/go.mod b/pgtester/go.mod
@@ -0,0 +1,5 @@
+module pgtester
+
+go 1.18
+
+require github.com/lib/pq v1.10.6
diff --git a/pgtester/go.sum b/pgtester/go.sum
@@ -0,0 +1,2 @@
+github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs=
+github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
diff --git a/pgtester/pgtester.go b/pgtester/pgtester.go
@@ -0,0 +1,50 @@
+package main
+
+import (
+ "database/sql"
+ "fmt"
+ "os"
+ "strings"
+
+ _ "github.com/lib/pq"
+)
+
+const (
+ urlFmt = "<user>:<password>@<host>/<database>[?sslmode=disable]\n"
+ testNum = 3423
+ pgPrefix = "postgresql://"
+)
+
+func must(err error, msg string) {
+ if err == nil {
+ return
+ }
+ fmt.Println(msg+":", err)
+ os.Exit(1)
+}
+
+func main() {
+ if len(os.Args) < 2 {
+ fmt.Printf("Use:\n\t%v [postgresql://]<database_url>\nURL format:\n\t%v", os.Args[0], urlFmt)
+ return
+ }
+ dbURL := pgPrefix + strings.TrimPrefix(os.Args[1], pgPrefix)
+ db, err := sql.Open("postgres", dbURL)
+ must(err, "Failed to open database:")
+ err = db.Ping()
+ must(err, "Failed to ping database")
+ _, err = db.Exec(`CREATE TABLE pgtester_temp_table (num int);`)
+ must(err, "Failed to create temporary table")
+ _, err = db.Exec(`INSERT INTO pgtester_temp_table VALUES ($1);`, testNum)
+ must(err, "Failed to insert into temporary table")
+ row := db.QueryRow(`SELECT num FROM pgtester_temp_table;`)
+ var readNum int
+ err = row.Scan(&readNum)
+ must(err, "Failed to read data from temporary table")
+ if readNum != testNum {
+ fmt.Printf("Inserted data does not match fetched data (%v != %v)\n", readNum, testNum)
+ os.Exit(1)
+ }
+ _, err = db.Exec(`DROP TABLE pgtester_temp_table;`)
+ must(err, "Failed to delete temporary database")
+}