-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalter_table.go
More file actions
300 lines (254 loc) · 8.16 KB
/
alter_table.go
File metadata and controls
300 lines (254 loc) · 8.16 KB
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
package mist
import (
"fmt"
"strings"
"time"
"github.com/abbychau/mysql-parser/ast"
)
// ExecuteAlterTable processes an ALTER TABLE statement
func ExecuteAlterTable(db *Database, stmt *ast.AlterTableStmt) error {
tableName := stmt.Table.Name.String()
// Get the table
table, err := db.GetTable(tableName)
if err != nil {
return err
}
// Process each ALTER specification
for _, spec := range stmt.Specs {
switch spec.Tp {
case ast.AlterTableAddColumns:
err = executeAddColumn(db, table, spec)
case ast.AlterTableDropColumn:
err = executeDropColumn(db, table, spec)
case ast.AlterTableModifyColumn:
err = executeModifyColumn(db, table, spec)
case ast.AlterTableChangeColumn:
err = executeChangeColumn(db, table, spec)
default:
return fmt.Errorf("unsupported ALTER TABLE operation: %v", spec.Tp)
}
if err != nil {
return err
}
}
return nil
}
// executeAddColumn adds a new column to the table
func executeAddColumn(db *Database, table *Table, spec *ast.AlterTableSpec) error {
if len(spec.NewColumns) == 0 {
return fmt.Errorf("no columns specified for ADD COLUMN")
}
table.mutex.Lock()
defer table.mutex.Unlock()
for _, colDef := range spec.NewColumns {
// Parse the new column
colType, length, precision, scale, err := parseColumnType(colDef)
if err != nil {
return fmt.Errorf("error parsing new column %s: %v", colDef.Name.Name.String(), err)
}
notNull, primary, unique, autoIncr, defaultValue, onUpdateValue, enumValues, setValues := parseColumnConstraints(colDef)
newColumn := Column{
Name: colDef.Name.Name.String(),
Type: colType,
Length: length,
Precision: precision,
Scale: scale,
NotNull: notNull,
Primary: primary,
Unique: unique,
AutoIncr: autoIncr,
Default: defaultValue,
OnUpdate: onUpdateValue,
EnumValues: enumValues,
SetValues: setValues,
}
// Check if column already exists
if table.GetColumnIndex(newColumn.Name) != -1 {
return fmt.Errorf("column %s already exists", newColumn.Name)
}
// Add the column to the table schema
table.Columns = append(table.Columns, newColumn)
// Add default value to all existing rows
defaultVal := getDefaultValue(newColumn)
for i := range table.Rows {
table.Rows[i].Values = append(table.Rows[i].Values, defaultVal)
}
}
return nil
}
// executeDropColumn removes a column from the table
func executeDropColumn(db *Database, table *Table, spec *ast.AlterTableSpec) error {
if spec.OldColumnName == nil {
return fmt.Errorf("no column specified for DROP COLUMN")
}
columnName := spec.OldColumnName.Name.String()
colIndex := table.GetColumnIndex(columnName)
if colIndex == -1 {
return fmt.Errorf("column %s does not exist", columnName)
}
table.mutex.Lock()
defer table.mutex.Unlock()
// Remove column from schema
table.Columns = append(table.Columns[:colIndex], table.Columns[colIndex+1:]...)
// Remove column data from all rows
for i := range table.Rows {
table.Rows[i].Values = append(table.Rows[i].Values[:colIndex], table.Rows[i].Values[colIndex+1:]...)
}
// Update any indexes that reference this column
indexesToDrop := make([]string, 0)
for _, indexName := range db.IndexManager.ListIndexes() {
if index, exists := db.IndexManager.GetIndex(indexName); exists {
if strings.EqualFold(index.TableName, table.Name) && strings.EqualFold(index.ColumnName, columnName) {
indexesToDrop = append(indexesToDrop, indexName)
}
}
}
// Drop affected indexes
for _, indexName := range indexesToDrop {
_ = db.IndexManager.DropIndex(indexName)
}
return nil
}
// executeModifyColumn modifies an existing column
func executeModifyColumn(db *Database, table *Table, spec *ast.AlterTableSpec) error {
if len(spec.NewColumns) == 0 {
return fmt.Errorf("no column specified for MODIFY COLUMN")
}
colDef := spec.NewColumns[0]
columnName := colDef.Name.Name.String()
colIndex := table.GetColumnIndex(columnName)
if colIndex == -1 {
return fmt.Errorf("column %s does not exist", columnName)
}
// Parse the new column definition
colType, length, precision, scale, err := parseColumnType(colDef)
if err != nil {
return fmt.Errorf("error parsing modified column %s: %v", columnName, err)
}
notNull, primary, unique, autoIncr, defaultValue, onUpdateValue, enumValues, setValues := parseColumnConstraints(colDef)
table.mutex.Lock()
defer table.mutex.Unlock()
// Update the column definition
table.Columns[colIndex] = Column{
Name: columnName,
Type: colType,
Length: length,
Precision: precision,
Scale: scale,
NotNull: notNull,
Primary: primary,
Unique: unique,
AutoIncr: autoIncr,
Default: defaultValue,
OnUpdate: onUpdateValue,
EnumValues: enumValues,
SetValues: setValues,
}
// Convert existing data to new type if possible
for i := range table.Rows {
if colIndex < len(table.Rows[i].Values) {
convertedValue, err := convertValueToColumnType(table.Rows[i].Values[colIndex], colType)
if err != nil {
return fmt.Errorf("cannot convert existing data in row %d: %v", i, err)
}
table.Rows[i].Values[colIndex] = convertedValue
}
}
return nil
}
// executeChangeColumn renames and/or modifies a column
func executeChangeColumn(db *Database, table *Table, spec *ast.AlterTableSpec) error {
if spec.OldColumnName == nil || len(spec.NewColumns) == 0 {
return fmt.Errorf("invalid CHANGE COLUMN specification")
}
oldColumnName := spec.OldColumnName.Name.String()
colIndex := table.GetColumnIndex(oldColumnName)
if colIndex == -1 {
return fmt.Errorf("column %s does not exist", oldColumnName)
}
colDef := spec.NewColumns[0]
newColumnName := colDef.Name.Name.String()
// Check if new name conflicts with existing columns (unless it's the same column)
if !strings.EqualFold(oldColumnName, newColumnName) {
if table.GetColumnIndex(newColumnName) != -1 {
return fmt.Errorf("column %s already exists", newColumnName)
}
}
// Parse the new column definition
colType, length, precision, scale, err := parseColumnType(colDef)
if err != nil {
return fmt.Errorf("error parsing changed column %s: %v", newColumnName, err)
}
notNull, primary, unique, autoIncr, defaultValue, onUpdateValue, enumValues, setValues := parseColumnConstraints(colDef)
table.mutex.Lock()
defer table.mutex.Unlock()
// Update the column definition
table.Columns[colIndex] = Column{
Name: newColumnName,
Type: colType,
Length: length,
Precision: precision,
Scale: scale,
NotNull: notNull,
Primary: primary,
Unique: unique,
AutoIncr: autoIncr,
Default: defaultValue,
OnUpdate: onUpdateValue,
EnumValues: enumValues,
SetValues: setValues,
}
// Convert existing data to new type if possible
for i := range table.Rows {
if colIndex < len(table.Rows[i].Values) {
convertedValue, err := convertValueToColumnType(table.Rows[i].Values[colIndex], colType)
if err != nil {
return fmt.Errorf("cannot convert existing data in row %d: %v", i, err)
}
table.Rows[i].Values[colIndex] = convertedValue
}
}
// Update indexes that reference the old column name
for _, indexName := range db.IndexManager.ListIndexes() {
if index, exists := db.IndexManager.GetIndex(indexName); exists {
if strings.EqualFold(index.TableName, table.Name) && strings.EqualFold(index.ColumnName, oldColumnName) {
// Update the index column name
index.ColumnName = newColumnName
// Rebuild the index with the new column name
_ = index.RebuildIndex(table)
}
}
}
return nil
}
// getDefaultValue returns an appropriate default value for a column type
func getDefaultValue(column Column) interface{} {
// If column has a specific default value, use it
if column.Default != nil {
if column.Default == "CURRENT_TIMESTAMP" {
return time.Now().Format("2006-01-02 15:04:05")
}
return column.Default
}
if !column.NotNull {
return nil
}
switch column.Type {
case TypeInt:
return int64(0)
case TypeFloat:
return float64(0)
case TypeVarchar, TypeText:
return ""
case TypeBool:
return false
case TypeDecimal:
return "0.00"
case TypeTimestamp:
return time.Now().Format("2006-01-02 15:04:05")
case TypeDate:
return time.Now().Format("2006-01-02")
default:
return nil
}
}