forked from aliyun/aliyun-odps-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table_schema.go
311 lines (260 loc) · 8.09 KB
/
table_schema.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tableschema
import (
"bytes"
"fmt"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/arrow"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/odps/common"
"github.com/pkg/errors"
"strings"
"text/template"
)
type TableSchema struct {
TableName string
Columns []Column
Comment string
CreateTime common.GMTTime
ExtendedLabel []string
HubLifecycle int
IsExternal bool
IsMaterializedView bool
IsVirtualView bool
LastDDLTime common.GMTTime
LastModifiedTime common.GMTTime
Lifecycle int
Owner string
PartitionColumns []Column `json:"PartitionKeys"`
RecordNum int
ShardExist bool
ShardInfo string
Size int
TableLabel string
ViewText string
// extended schema, got by adding "?extended" to table api
FileNum int
IsArchived bool
PhysicalSize int
Reserved string // reserved json string, 字段不固定
// for external table extended info
StorageHandler string
Location string
resources string
// for clustered info
ClusterInfo ClusterInfo
}
// ClusterInfo 聚簇信息
type ClusterInfo struct {
ClusterType string
ClusterInfo []string
SortCols []SortColumn
}
type SortColumn struct {
name string
order string
}
type SchemaBuilder struct {
name string
comment string
columns []Column
partitionColumns []Column
storageHandler string
location string
lifecycle int
}
func NewSchemaBuilder() SchemaBuilder {
return SchemaBuilder{}
}
func (builder *SchemaBuilder) Name(name string) *SchemaBuilder {
builder.name = name
return builder
}
func (builder *SchemaBuilder) Comment(comment string) *SchemaBuilder {
builder.comment = comment
return builder
}
func (builder *SchemaBuilder) Column(column Column) *SchemaBuilder {
builder.columns = append(builder.columns, column)
return builder
}
func (builder *SchemaBuilder) PartitionColumn(column Column) *SchemaBuilder {
builder.partitionColumns = append(builder.partitionColumns, column)
return builder
}
func (builder *SchemaBuilder) Columns(columns ...Column) *SchemaBuilder {
builder.columns = append(builder.columns, columns...)
return builder
}
func (builder *SchemaBuilder) PartitionColumns(columns ...Column) *SchemaBuilder {
builder.partitionColumns = append(builder.partitionColumns, columns...)
return builder
}
func (builder *SchemaBuilder) StorageHandler(storageHandler string) *SchemaBuilder {
builder.storageHandler = storageHandler
return builder
}
func (builder *SchemaBuilder) Location(location string) *SchemaBuilder {
builder.location = location
return builder
}
// Lifecycle 表的生命周期,仅支持正整数。单位:天
func (builder *SchemaBuilder) Lifecycle(lifecycle int) *SchemaBuilder {
builder.lifecycle = lifecycle
return builder
}
func (builder *SchemaBuilder) Build() TableSchema {
return TableSchema{
TableName: builder.name,
Columns: builder.columns,
PartitionColumns: builder.partitionColumns,
Comment: builder.comment,
Lifecycle: builder.lifecycle,
StorageHandler: builder.storageHandler,
Location: builder.location,
}
}
func (schema *TableSchema) ToBaseSQLString(projectName string, createIfNotExists, isExternal bool) (string, error) {
if schema.TableName == "" {
return "", errors.New("table name is not set")
}
if len(schema.Columns) == 0 {
return "", errors.New("table columns is not set")
}
var fns = template.FuncMap{
"notLast": func(i, length int) bool {
return i < length-1
},
}
tplStr :=
"{{$columnNum := len .Schema.Columns}}" +
"{{$partitionNum := len .Schema.PartitionColumns}}" +
"create {{if .IsExternal -}} external {{ end -}} table {{ if .CreateIfNotExists }}if not exists{{ end }} {{.ProjectName}}.`{{.Schema.TableName}}` (\n" +
"{{ range $i, $column := .Schema.Columns }}" +
" `{{.Name}}` {{.Type | print}} {{ if ne .Comment \"\" }}comment '{{.Comment}}'{{ end }}{{ if notLast $i $columnNum }},{{ end }}\n" +
"{{ end }}" +
")" +
"{{ if ne .Schema.Comment \"\" }}" +
"\ncomment '{{.Schema.Comment}}'" +
"{{ end }}" +
"{{ if gt $partitionNum 0 }}" +
"\npartitioned by (" +
"{{ range $i, $partition := .Schema.PartitionColumns }}" +
"`{{.Name}}` {{.Type | print}} {{- if ne .Comment \"\" }} comment '{{.Comment}}' {{- end -}} {{- if notLast $i $partitionNum }}, {{ end }}" +
"{{ end -}}" +
")" +
"{{ end }}"
tpl, err := template.New("DDL_CREATE_TABLE").Funcs(fns).Parse(tplStr)
if err != nil {
panic(err)
}
type Data struct {
ProjectName string
Schema *TableSchema
IsExternal bool
CreateIfNotExists bool
}
data := Data{projectName, schema, isExternal, createIfNotExists}
var out bytes.Buffer
err = tpl.Execute(&out, data)
if err != nil {
panic(err)
} else {
return out.String(), nil
}
}
func (schema *TableSchema) ToSQLString(projectName string, createIfNotExists bool) (string, error) {
baseSql, err := schema.ToBaseSQLString(projectName, createIfNotExists, false)
if err != nil {
return "", errors.WithStack(err)
}
if schema.Lifecycle > 0 {
baseSql += fmt.Sprintf("\nlifecycle %d", schema.Lifecycle)
}
baseSql += ";"
return baseSql, nil
}
func (schema *TableSchema) ToExternalSQLString(
projectName string,
createIfNotExists bool,
serdeProperties map[string]string,
jars []string) (string, error) {
if schema.StorageHandler == "" {
return "", errors.New("TableSchema.StorageHandler is not set")
}
if schema.Location == "" {
return "", errors.New("TableSchema.Location is not set")
}
baseSql, err := schema.ToBaseSQLString(projectName, createIfNotExists, true)
if err != nil {
return "", errors.WithStack(err)
}
var builder strings.Builder
builder.WriteString(baseSql)
// stored by, 用于指定自定义格式StorageHandler的类名或其他外部表文件格式
builder.WriteString(fmt.Sprintf("\nstored by '%s'\n", schema.StorageHandler))
// serde properties, 序列化属性参数
if len(serdeProperties) > 0 {
builder.WriteString("with serdeproperties(")
i, n := 0, len(serdeProperties)
for key, value := range serdeProperties {
builder.WriteString(fmt.Sprintf("'%s'='%s'", key, value))
i += 1
if i < n {
builder.WriteString(", ")
}
}
builder.WriteString(")\n")
}
// location, 外部表存放地址
builder.WriteString(fmt.Sprintf("location '%s'\n", schema.Location))
// 自定义格式时类定义所在的jar
if len(jars) > 0 {
builder.WriteString("using '")
n := len(jars)
for i, jar := range jars {
builder.WriteString(jar)
if i < n-1 {
builder.WriteString(", ")
}
}
builder.WriteString("'\n")
}
if schema.Lifecycle > 0 {
builder.WriteString(fmt.Sprintf("lifecycle %d", schema.Lifecycle))
}
builder.WriteRune(';')
return builder.String(), nil
}
func (schema *TableSchema) ToArrowSchema() *arrow.Schema {
fields := make([]arrow.Field, len(schema.Columns))
for i, column := range schema.Columns {
arrowType, _ := TypeToArrowType(column.Type)
fields[i] = arrow.Field{
Name: column.Name,
Type: arrowType,
Nullable: column.IsNullable,
}
}
return arrow.NewSchema(fields, nil)
}
func (schema *TableSchema) FieldByName(name string) (Column, bool) {
for _, c := range schema.Columns {
if c.Name == name {
return c, true
}
}
return Column{}, false
}