Skip to content

Instantly share code, notes, and snippets.

@craftslab
Last active May 4, 2021 01:11
Show Gist options
  • Save craftslab/575199c58fe40c623d45f24682662ef1 to your computer and use it in GitHub Desktop.
Save craftslab/575199c58fe40c623d45f24682662ef1 to your computer and use it in GitHub Desktop.
gorm postgres

Install

# Docker
# https://gist.github.com/craftslab/94ec9617aff0bbf022ae388eb1b3287b

# Ubuntu
# https://www.postgresql.org/download/linux/ubuntu/
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get -y install postgresql

# Windows
# https://www.postgresql.org/download/windows/
curl -L https://get.enterprisedb.com/postgresql/postgresql-13.1-1-windows-x64.exe -o postgresql.exe

Run

go run main.go

Backup

pg_dump -h 127.0.0.1 -p 5432 -U postgres -d postgres -E utf8 -F t -b -v -f postgres.tar

Restore

pg_restore -h 127.0.0.1 -p 5432 -U postgres -O -d postgres -v postgres.tar

Reference

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
const (
dsn = "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=postgres sslmode=disable TimeZone=Asia/Shanghai"
)
func main() {
// Open
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("failed to open: %v", err)
}
// Migrate
if err := db.AutoMigrate(&Product{}); err != nil {
log.Fatalf("failed to migrate: %v", err)
}
// Create
db.Create(&Product{Code: "D42", Price: 100})
var p Product
// Read
db.First(&p, "code=?", "D42")
fmt.Printf("%#v\n", p)
// Update
db.Model(&p).Update("Price", 200)
db.Model(&p).Updates(Product{Code: "F42", Price: 200})
db.Model(&p).Updates(map[string]interface{}{"Code": "F42", "Price": 200})
// Delete
db.Delete(&p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment