0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Go: gorm で PostgreSQL のバージョンを表示

Last updated at Posted at 2023-03-03

プログラム

フォルダー構造

$ tree -a
.
├── .env
├── config_postgres.go
└── gorm_pg_version.go
gorm_pg_version.go
// ----------------------------------------------------------------
//
//	gorm_pg_version.go
//
//					Mar/03/2023
//
// ----------------------------------------------------------------
package main

import (
	"fmt"
	"os"
	"gorm.io/gorm"
	"gorm.io/driver/postgres"
)

// ----------------------------------------------------------------
func main() {
	fmt.Fprintln(os.Stderr,"*** 開始 ***")

	host,user,password,data_base := config_postgres_proc()

dsn := "host=" + host + " user=" + user + " password=" + password + " dbname=" + data_base + " port=5432 sslmode=disable TimeZone=Asia/Tokyo"

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
		}

	result := map[string]interface{}{}

	db.Raw("SELECT VERSION ()").Scan(&result)

	fmt.Println(result)

	fmt.Fprintln(os.Stderr,"*** 終了 ***")
}

// ----------------------------------------------------------------
config_postgres.go
// ----------------------------------------------------------------
//
//	config_postgres.go
//
//					Mar/03/2023
//
// ----------------------------------------------------------------
package main

import (
	"os"
	"github.com/joho/godotenv"
)

// ----------------------------------------------------------------
func config_postgres_proc()(string, string, string, string) {
	err := godotenv.Load(".env")
	if err != nil {
		panic(err)
	}

	host := os.Getenv("host")
	user := os.Getenv("user")
	password := os.Getenv("password")
	data_base := os.Getenv("data_base")

	return host,user,password,data_base
}

// ----------------------------------------------------------------
.env
host = 'localhost'
user = 'scott'
password = 'tiger123'
data_base = 'city'

実行の準備

go mod init version
go mod tidy

go.mod go.sum が作成される。

実行結果

$ go run gorm_pg_version.go config_postgres.go
*** 開始 ***
map[version:PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 13.2.1 20230801, 64-bit]
*** 終了 ***
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?