2016-03-05 13:54:59 +03:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"database/sql/driver"
|
|
|
|
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"github.com/lib/pq/hstore"
|
2017-10-10 16:28:39 +03:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2016-03-05 13:54:59 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type Hstore map[string]*string
|
|
|
|
|
2016-03-08 17:29:58 +03:00
|
|
|
// Value get value of Hstore
|
2016-03-05 13:54:59 +03:00
|
|
|
func (h Hstore) Value() (driver.Value, error) {
|
|
|
|
hstore := hstore.Hstore{Map: map[string]sql.NullString{}}
|
|
|
|
if len(h) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for key, value := range h {
|
|
|
|
var s sql.NullString
|
|
|
|
if value != nil {
|
|
|
|
s.String = *value
|
|
|
|
s.Valid = true
|
|
|
|
}
|
|
|
|
hstore.Map[key] = s
|
|
|
|
}
|
|
|
|
return hstore.Value()
|
|
|
|
}
|
|
|
|
|
2016-03-08 17:29:58 +03:00
|
|
|
// Scan scan value into Hstore
|
2016-03-05 13:54:59 +03:00
|
|
|
func (h *Hstore) Scan(value interface{}) error {
|
|
|
|
hstore := hstore.Hstore{}
|
|
|
|
|
|
|
|
if err := hstore.Scan(value); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(hstore.Map) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
*h = Hstore{}
|
|
|
|
for k := range hstore.Map {
|
|
|
|
if hstore.Map[k].Valid {
|
|
|
|
s := hstore.Map[k].String
|
|
|
|
(*h)[k] = &s
|
|
|
|
} else {
|
|
|
|
(*h)[k] = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2017-10-10 16:28:39 +03:00
|
|
|
|
|
|
|
// Jsonb Postgresql's JSONB data type
|
|
|
|
type Jsonb struct {
|
|
|
|
json.RawMessage
|
|
|
|
}
|
|
|
|
|
|
|
|
// Value get value of Jsonb
|
|
|
|
func (j Jsonb) Value() (driver.Value, error) {
|
|
|
|
return j.MarshalJSON()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Scan scan value into Jsonb
|
|
|
|
func (j *Jsonb) Scan(value interface{}) error {
|
|
|
|
bytes, ok := value.([]byte)
|
|
|
|
if !ok {
|
|
|
|
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Unmarshal(bytes, j)
|
|
|
|
}
|