-
-
Save lakhansamani/55e87795174b1b65d66a51422da99034 to your computer and use it in GitHub Desktop.
handle postgres json with gorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/jinzhu/gorm" | |
_ "github.com/lib/pq" | |
) | |
func main() { | |
// Setup Postgres - set CONN_STRING to connect to an empty database | |
db, err := gorm.Open("postgres", "user=gorm DB.name=gorm sslmode=disable") | |
if err != nil { | |
panic(err) | |
} | |
// db.LogMode(true) | |
// Create Table | |
type ClassRoom struct { | |
gorm.Model | |
State string `sql:"type:JSONB NOT NULL DEFAULT '{}'::JSONB"` | |
} | |
// AutoMigrate | |
db.DropTable(&ClassRoom{}) | |
db.Debug().AutoMigrate(&ClassRoom{}) | |
// JSON to insert | |
STATE := `{"uses-kica": false, "hide-assessments-intro": true, "most-recent-grade-skew": 1.5}` | |
classRoom := ClassRoom{State: STATE} | |
db.Save(&classRoom) | |
// Select the row | |
var result ClassRoom | |
db.First(&result) | |
if result.State == STATE { | |
fmt.Println("SUCCESS: Selected JSON == inserted JSON") | |
} else { | |
fmt.Println("FAILED: Selected JSON != inserted JSON") | |
fmt.Println("Inserted: " + STATE) | |
fmt.Println("Selected: " + result.State) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment