|
| 1 | +package design_sql_2408 |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | +) |
| 7 | + |
| 8 | +type table struct { |
| 9 | + idInc int |
| 10 | + colCount int |
| 11 | + rows map[int][]string |
| 12 | +} |
| 13 | + |
| 14 | +type SQL struct { |
| 15 | + tables map[string]*table |
| 16 | +} |
| 17 | + |
| 18 | +func Constructor(names []string, columns []int) SQL { |
| 19 | + sql := SQL{ |
| 20 | + tables: make(map[string]*table), |
| 21 | + } |
| 22 | + for i, name := range names { |
| 23 | + colCount := columns[i] |
| 24 | + sql.tables[name] = &table{ |
| 25 | + idInc: 0, |
| 26 | + colCount: colCount, |
| 27 | + rows: make(map[int][]string), |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return sql |
| 32 | +} |
| 33 | + |
| 34 | +func (q *SQL) Ins(name string, row []string) bool { |
| 35 | + table, ok := q.tables[name] |
| 36 | + if !ok || len(row) != table.colCount { |
| 37 | + return false |
| 38 | + } |
| 39 | + |
| 40 | + table.idInc++ |
| 41 | + table.rows[table.idInc] = row |
| 42 | + return true |
| 43 | +} |
| 44 | + |
| 45 | +func (q *SQL) Rmv(name string, rowId int) { |
| 46 | + table, ok := q.tables[name] |
| 47 | + if !ok { |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + // deletes are idempotent, no need to check if it exists or not |
| 52 | + delete(table.rows, rowId) |
| 53 | +} |
| 54 | + |
| 55 | +func (q *SQL) Sel(name string, rowId int, columnId int) string { |
| 56 | + table, ok := q.tables[name] |
| 57 | + if !ok { |
| 58 | + return "<null>" |
| 59 | + } |
| 60 | + |
| 61 | + row, ok := table.rows[rowId] |
| 62 | + if !ok { |
| 63 | + return "<null>" |
| 64 | + } |
| 65 | + |
| 66 | + if columnId < 1 || columnId > len(row) { |
| 67 | + return "<null>" |
| 68 | + } |
| 69 | + |
| 70 | + return row[columnId-1] |
| 71 | +} |
| 72 | + |
| 73 | +func (q *SQL) Exp(name string) []string { |
| 74 | + table, ok := q.tables[name] |
| 75 | + if !ok { |
| 76 | + return []string{} |
| 77 | + } |
| 78 | + |
| 79 | + rows := make([]string, 0, len(table.rows)) |
| 80 | + for id, row := range table.rows { |
| 81 | + rows = append(rows, fmt.Sprintf("%d,%s", id, strings.Join(row, ","))) |
| 82 | + } |
| 83 | + |
| 84 | + return rows |
| 85 | +} |
0 commit comments