| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package dbx |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"strings" |
| 10 |
) |
| 11 |
|
| 12 |
|
| 13 |
type MssqlBuilder struct { |
| 14 |
*BaseBuilder |
| 15 |
qb *MssqlQueryBuilder |
| 16 |
} |
| 17 |
|
| 18 |
var _ Builder = &MssqlBuilder{} |
| 19 |
|
| 20 |
|
| 21 |
type MssqlQueryBuilder struct { |
| 22 |
*BaseQueryBuilder |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
func NewMssqlBuilder(db *DB, executor Executor) Builder { |
| 27 |
return &MssqlBuilder{ |
| 28 |
NewBaseBuilder(db, executor), |
| 29 |
&MssqlQueryBuilder{NewBaseQueryBuilder(db)}, |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
func (b *MssqlBuilder) QueryBuilder() QueryBuilder { |
| 35 |
return b.qb |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
func (b *MssqlBuilder) Select(cols ...string) *SelectQuery { |
| 42 |
return NewSelectQuery(b, b.db).Select(cols...) |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
func (b *MssqlBuilder) Model(model interface{}) *ModelQuery { |
| 48 |
return NewModelQuery(model, b.db.FieldMapper, b.db, b) |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
func (b *MssqlBuilder) QuoteSimpleTableName(s string) string { |
| 54 |
if strings.Contains(s, `[`) { |
| 55 |
return s |
| 56 |
} |
| 57 |
return `[` + s + `]` |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
func (b *MssqlBuilder) QuoteSimpleColumnName(s string) string { |
| 63 |
if strings.Contains(s, `[`) || s == "*" { |
| 64 |
return s |
| 65 |
} |
| 66 |
return `[` + s + `]` |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
func (b *MssqlBuilder) RenameTable(oldName, newName string) *Query { |
| 71 |
sql := fmt.Sprintf("sp_name '%v', '%v'", oldName, newName) |
| 72 |
return b.NewQuery(sql) |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
func (b *MssqlBuilder) RenameColumn(table, oldName, newName string) *Query { |
| 77 |
sql := fmt.Sprintf("sp_name '%v.%v', '%v', 'COLUMN'", table, oldName, newName) |
| 78 |
return b.NewQuery(sql) |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
func (b *MssqlBuilder) AlterColumn(table, col, typ string) *Query { |
| 83 |
col = b.db.QuoteColumnName(col) |
| 84 |
sql := fmt.Sprintf("ALTER TABLE %v ALTER COLUMN %v %v", b.db.QuoteTableName(table), col, typ) |
| 85 |
return b.NewQuery(sql) |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
func (q *MssqlQueryBuilder) BuildOrderByAndLimit(sql string, cols []string, limit int64, offset int64) string { |
| 90 |
orderBy := q.BuildOrderBy(cols) |
| 91 |
if limit < 0 && offset < 0 { |
| 92 |
if orderBy == "" { |
| 93 |
return sql |
| 94 |
} |
| 95 |
return sql + "\n" + orderBy |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
if orderBy == "" { |
| 101 |
|
| 102 |
orderBy = "ORDER BY (SELECT NULL)" |
| 103 |
} |
| 104 |
sql += "\n" + orderBy |
| 105 |
|
| 106 |
|
| 107 |
if offset < 0 { |
| 108 |
offset = 0 |
| 109 |
} |
| 110 |
sql += "\n" + fmt.Sprintf("OFFSET %v ROWS", offset) |
| 111 |
if limit >= 0 { |
| 112 |
sql += "\n" + fmt.Sprintf("FETCH NEXT %v ROWS ONLY", limit) |
| 113 |
} |
| 114 |
return sql |
| 115 |
} |