dbi

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2023 License: MIT Imports: 5 Imported by: 0

README

DBI

Postgresql Database Interface on top of pgx

PkgGoDev Go Report Card GitHub tag (latest by date) GitHub


Getting Started

Prerequisite
  • You need an active running instance of Postgresql DB somewhere you can access
  • (optional) Create .env file in your root directory and add below variables
    • PGUSER
    • PGPASSWORD
    • PGHOST
    • PGDATABASE
    • PGPORT
Installing

go get it (pun intended 😸)

go get github.com/junekimdev/dbi

Usage

package main

import (
  "log"

  "github.com/junekimdev/dbi"
  "github.com/joho/godotenv"
)

func init(){
  // Load environment variables
  err := godotenv.Load(".env")
  if err != nil {
    log.Fatalf("Failed to load .env file: %v", err)
  }
  // Connect to DB with env
  dbi.Connect(dbi.CreateURIFromEnv().String())
}

// User struct
type User struct {
  id     int
  name   string
  gender string
}

func main() {
  // Prep your sql
  sql := "SELECT id, name, gender FROM test_user WHERE id=($1)"

  // Query DB
  result := Query(sql, 7)

  // Destination of Scan
  var user User

  // Scan the result
  // You Need to pass "scan function" that has "Scan" method of pgx.Rows
  if err := Scan(result, func() { result.Scan(&user.id, &user.name, &user.gender) }); err != nil {
    panic(err)
  }

  log.Printf("%#+v", user)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Connect

func Connect(connString string) error

Connect to DB and load db-pool reference in the package

func Query

func Query(sql string, args ...interface{}) pgx.Rows

Query is the wrapper function of 'pgxpool.Query'

This starts a goroutine to run query and return the result (pgx.Rows) through the go-channel

func Scan

func Scan(rows pgx.Rows, scanfunc func()) error

Scan is the wrapper function of 'pgx.Rows.Scan' that scan the result of query

You Need to pass "scan function" that has "Scan" method of pgx.Rows

Types

type URI

type URI struct {
	Username string
	Password string
	Host     string
	Port     string
	Database string
}

URI struct represents parts of connection string

func CreateURIFromEnv

func CreateURIFromEnv() *URI

CreateURIFromEnv create URI from environment variables

This should be called after loading environment variables; otherwise, it will create an empty URI

func (*URI) String

func (uri *URI) String() string

String gives a valid connection string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL