Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
4
Indexable
Never
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"

	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/pgdialect"
	"github.com/uptrace/bun/driver/pgdriver"
)

type WorkOrder struct {
	bun.BaseModel `bun:"table:work_oders,alias:wo"`

	ID       int64                  `bun:",pk,autoincrement"`
	Data     map[string]interface{} `bun:"type:jsonb"`
	TypeName string                 `bun:",notnull"`
}

type FrontierData struct {
	FrontierID int   `json:"frontier_id"`
	LeadID     int   `json:"lead_id"`
	Operator   []int `json:"operator"`
}

type FrontierWorkOrder struct {
	bun.BaseModel `bun:"table:work_oders,alias:wo"`

	ID       int64        `bun:",pk,autoincrement"`
	Data     FrontierData `bun:"type:jsonb"`
	TypeName string       `bun:",notnull"`
}

type SmartBitWorkOrder struct {
	FrontierID int   `json:"smarbit_id"`
	Operator   []int `json:"operator"`
}

type GabinetWorkOrder struct {
	FrontierID int   `json:"gabinet_id"`
	Operator   []int `json:"operator"`
}

func main() {
	pgconn := pgdriver.NewConnector(
		pgdriver.WithAddr("localhost:5432"),
		pgdriver.WithUser("test"),
		pgdriver.WithPassword("test"),
		pgdriver.WithDatabase("test"),
		pgdriver.WithApplicationName("manager"),
		pgdriver.WithInsecure(true),
	)
	sqldb := sql.OpenDB(pgconn)

	db := bun.NewDB(sqldb, pgdialect.New())
	err := db.ResetModel(context.Background(), (*WorkOrder)(nil))
	if err != nil {
		log.Println(err)
	}

	orders := []WorkOrder{
		{
			TypeName: "frontier",
			Data: map[string]interface{}{
				"frontier_id": 1,
				"lead_id":     2,
				"operator":    []int{1, 2},
			},
		},
		{
			TypeName: "smarbit",
			Data: map[string]interface{}{
				"smarbit_id": 1,
				"operator":   []int{1, 2},
			},
		},
		{
			TypeName: "gabinet",
			Data: map[string]interface{}{
				"gabinet_id": 1,
				"operator":   []int{1, 2},
			},
		},
	}
	res, _ := db.NewInsert().Model(&orders).Exec(context.Background())
	log.Println(res)

	fwo := new(FrontierWorkOrder)
	err = db.NewSelect().Model(fwo).Where("id = ?", 1).Scan(context.Background())
	if err != nil {
		log.Println(err)
	}

	jsonBytes, err := json.Marshal(fwo)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	jsonString := string(jsonBytes)

	fmt.Println("Work order frontier", jsonString)
}