/
action_delete_column.go
103 lines (77 loc) · 2.45 KB
/
action_delete_column.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package resource
import (
"context"
"github.com/artpar/api2go"
"github.com/jmoiron/sqlx"
"github.com/json-iterator/go"
"github.com/pkg/errors"
"net/http"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type deleteWorldColumnPerformer struct {
cmsConfig *CmsConfig
cruds map[string]*DbResource
}
func (d *deleteWorldColumnPerformer) Name() string {
return "world.column.delete"
}
func (d *deleteWorldColumnPerformer) DoAction(request Outcome, inFields map[string]interface{}, transaction *sqlx.Tx) (api2go.Responder, []ActionResponse, []error) {
worldName := inFields["world_name"].(string)
columnToDelete := inFields["column_name"].(string)
sessionUser := request.Attributes["user"]
httpReq := &http.Request{
Method: "GET",
}
httpReq = httpReq.WithContext(context.WithValue(context.Background(), "user", sessionUser))
req := &api2go.Request{
PlainRequest: httpReq,
}
table, err := d.cruds["world"].GetObjectByWhereClauseWithTransaction("world", "table_name", worldName, transaction)
if err != nil {
return nil, nil, []error{err}
}
tableData := table
schemaJson := tableData["world_schema_json"]
var tableSchema TableInfo
err = json.Unmarshal([]byte(schemaJson.(string)), &tableSchema)
if err != nil {
return nil, nil, []error{err}
}
indexToDelete := -1
newColumns := make([]api2go.ColumnInfo, 0)
for i, col := range tableSchema.Columns {
if col.Name == columnToDelete {
indexToDelete = i
continue
}
newColumns = append(newColumns, col)
}
if indexToDelete == -1 {
return nil, nil, []error{errors.New("no such column")}
}
tableSchema.Columns = newColumns
schemaJson, err = json.Marshal(tableSchema)
_, err = transaction.Exec("alter table " + tableSchema.TableName + " drop column " + columnToDelete)
if err != nil {
return nil, nil, []error{err}
}
updateObj := api2go.Api2GoModel{
Data: tableData,
}
updateObj.SetAttributes(map[string]interface{}{
"world_schema_json": schemaJson,
})
_, err = d.cruds["world"].UpdateWithoutFilters(updateObj, *req, transaction)
if err != nil {
return nil, nil, []error{err}
}
restart()
return nil, []ActionResponse{NewActionResponse("client.notify", NewClientNotification("message", "Column deleted", "Success"))}, nil
}
func NewDeleteWorldColumnPerformer(initConfig *CmsConfig, cruds map[string]*DbResource) (ActionPerformerInterface, error) {
handler := deleteWorldColumnPerformer{
cruds: cruds,
cmsConfig: initConfig,
}
return &handler, nil
}