I'm developing an CRUD app. I'm reading an JSON from an api and I want to write this JSON in a database with "database/sql" and GORM in a spcific schema the struct:
type Veiculo struct {
gorm.Model
Codigo int `json:"vei_codigo"`
Placa string `json:"vei_placa"`
Nome string `json:"vei_nome"`
}
the endpoint function:
func CreateVeiculo(c *gin.Context) {
var veiculo model.Veiculo
//id := c.Params.ByName("id")
c.BindJSON(&veiculo)
c.JSON(200, veiculo)
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+" password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
dbVeiculosGorm, err := gorm.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer dbVeiculosGorm.Close()
dbVeiculosGorm.AutoMigrate(&model.Veiculo{})
//t := time.Now()
//ts := t.Format("2006-01-02 15:04:05")
dbVeiculosGorm.Create(&model.Veiculo{Placa: veiculo.Placa, Nome: veiculo.Nome}
but the database is untouchable. There is multiple schemas. Do i have to set the specific schema?? What am i doing wrong?
Here's a basic example of pretty much all you need to insert some simple data
into a PostgreSQL database via gorm.
main.go
package main
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" // Don't forget the dialect
)
// Simple Example model
type FuelType struct {
gorm.Model // Gorm default columns (id, created_at, updated_at, deleted_at)
Name string
}
func main() {
// Database initialization
db, err := gorm.Open(
"postgres",
"host=localhost port=5432 user=postgres dbname=foo password=bar sslmode=disable",
)
if err != nil {
log.Fatalln("Can't connect to the db: ", err)
}
defer func() {
if err := db.Close(); err != nil {
log.Fatalln("Can't close the db connection: ", err)
}
}()
// Migration
db.AutoMigrate(&FuelType{})
// Insertion
fuelType := FuelType{Name: "100 GFuel"}
db.Create(&fuelType)
}
before automigrate do
gorm.DefaultTableNameHandler = func(dbVeiculosGorm *gorm.DB, defaultTableName string) string {
return "your schema name." + defaultTableName
}
dbVeiculosGorm.AutoMigrate(&model.Veiculo{})