Dragonfly2

Форк
0
141 строка · 3.1 Кб
1
/*
2
 *     Copyright 2020 The Dragonfly Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package models
18

19
import (
20
	"database/sql/driver"
21
	"encoding/json"
22
	"errors"
23
	"fmt"
24
	"time"
25

26
	"gorm.io/gorm"
27
	"gorm.io/gorm/schema"
28
	"gorm.io/plugin/soft_delete"
29
)
30

31
type BaseModel struct {
32
	ID        uint                  `gorm:"primarykey;comment:id" json:"id"`
33
	CreatedAt time.Time             `gorm:"column:created_at;type:timestamp;default:current_timestamp" json:"created_at"`
34
	UpdatedAt time.Time             `gorm:"column:updated_at;type:timestamp;default:current_timestamp" json:"updated_at"`
35
	IsDel     soft_delete.DeletedAt `gorm:"softDelete:flag;comment:soft delete flag" json:"is_del"`
36
}
37

38
func Paginate(page, perPage int) func(db *gorm.DB) *gorm.DB {
39
	return func(db *gorm.DB) *gorm.DB {
40
		offset := (page - 1) * perPage
41
		return db.Offset(offset).Limit(perPage)
42
	}
43
}
44

45
type JSONMap map[string]any
46

47
func (m JSONMap) Value() (driver.Value, error) {
48
	if m == nil {
49
		return nil, nil
50
	}
51
	ba, err := m.MarshalJSON()
52
	return string(ba), err
53
}
54

55
func (m *JSONMap) Scan(val any) error {
56
	var ba []byte
57
	switch v := val.(type) {
58
	case []byte:
59
		ba = v
60
	case string:
61
		ba = []byte(v)
62
	default:
63
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", val))
64
	}
65
	t := map[string]any{}
66
	err := json.Unmarshal(ba, &t)
67
	*m = JSONMap(t)
68
	return err
69
}
70

71
func (m JSONMap) MarshalJSON() ([]byte, error) {
72
	if m == nil {
73
		return []byte("null"), nil
74
	}
75
	t := (map[string]any)(m)
76
	return json.Marshal(t)
77
}
78

79
func (m *JSONMap) UnmarshalJSON(b []byte) error {
80
	t := map[string]any{}
81
	err := json.Unmarshal(b, &t)
82
	*m = JSONMap(t)
83
	return err
84
}
85

86
func (m JSONMap) GormDataType() string {
87
	return "jsonmap"
88
}
89

90
func (JSONMap) GormDBDataType(db *gorm.DB, field *schema.Field) string {
91
	return "text"
92
}
93

94
type Array []string
95

96
func (a Array) Value() (driver.Value, error) {
97
	if a == nil {
98
		return nil, nil
99
	}
100
	ba, err := a.MarshalJSON()
101
	return string(ba), err
102
}
103

104
func (a *Array) Scan(val any) error {
105
	var ba []byte
106
	switch v := val.(type) {
107
	case []byte:
108
		ba = v
109
	case string:
110
		ba = []byte(v)
111
	default:
112
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", val))
113
	}
114
	t := []string{}
115
	err := json.Unmarshal(ba, &t)
116
	*a = Array(t)
117
	return err
118
}
119

120
func (a Array) MarshalJSON() ([]byte, error) {
121
	if a == nil {
122
		return []byte("null"), nil
123
	}
124
	t := ([]string)(a)
125
	return json.Marshal(t)
126
}
127

128
func (a *Array) UnmarshalJSON(b []byte) error {
129
	t := []string{}
130
	err := json.Unmarshal(b, &t)
131
	*a = Array(t)
132
	return err
133
}
134

135
func (Array) GormDataType() string {
136
	return "array"
137
}
138

139
func (Array) GormDBDataType(db *gorm.DB, field *schema.Field) string {
140
	return "text"
141
}
142

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.