Skip to content
14 changes: 14 additions & 0 deletions internal/core/catalogdb/query.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions internal/core/catalogdef/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ DELETE FROM sql_class WHERE oid = ?;
-- name: RenameClass :exec
UPDATE sql_class SET name = sqlc.arg(new_name) WHERE oid = sqlc.arg(oid);

-- name: SetClassNamespace :exec
UPDATE sql_class SET namespace_oid = sqlc.arg(namespace_oid) WHERE oid = sqlc.arg(oid);

-- ============================= sql_attribute ===========================

-- name: CreateAttribute :exec
Expand Down
12 changes: 12 additions & 0 deletions internal/core/class.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ func (c *Catalog) RenameClass(classOID int64, name string) error {
return nil
}

// SetClassNamespace moves a relation to another namespace.
func (c *Catalog) SetClassNamespace(classOID, namespaceOID int64) error {
err := c.q.SetClassNamespace(context.Background(), catalogdb.SetClassNamespaceParams{
Oid: classOID,
NamespaceOid: namespaceOID,
})
if err != nil {
return fmt.Errorf("set namespace of class %d: %w", classOID, err)
}
return nil
}

type ClassInfo struct {
OID int64
Name string
Expand Down
113 changes: 110 additions & 3 deletions internal/core/schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,16 @@ func Apply(cat *core.Catalog, n ast.Node) error {
return applyRenameColumn(cat, v)
case *ast.RenameTableStmt:
return applyRenameTable(cat, v)
case *ast.AlterTableSetSchemaStmt:
return applySetSchema(cat, v)
case *ast.ViewStmt:
return applyView(cat, v.View, v.Aliases, v.Query, v.Replace)
err := applyView(cat, v.View, v.Aliases, v.Query, v.Replace)
// A synonym may name a procedure, or something created later,
// leaving nothing for a query to select from it.
if err != nil && hasOption(v.Options, "synonym") {
return nil
}
return err
case *ast.CreateTableAsStmt:
if v.Into == nil {
return nil
Expand Down Expand Up @@ -160,7 +168,12 @@ func applyCreateTable(cat *core.Catalog, stmt *ast.CreateTableStmt) error {
if err != nil {
return err
}
var generated []int
for i, col := range stmt.Cols {
if generatedExpr(col) != nil {
generated = append(generated, i)
continue
}
if col == nil || col.TypeName == nil {
return fmt.Errorf("column %d on %q: missing type", i+1, stmt.Name.Name)
}
Expand All @@ -181,9 +194,69 @@ func applyCreateTable(cat *core.Catalog, stmt *ast.CreateTableStmt) error {
return fmt.Errorf("attr %s.%s: %w", stmt.Name.Name, col.Colname, err)
}
}
for _, i := range generated {
if err := applyGenerated(cat, classOID, stmt.Name, stmt.Cols[i], i+1); err != nil {
return fmt.Errorf("attr %s.%s: %w", stmt.Name.Name, stmt.Cols[i].Colname, err)
}
}
return nil
}

// generatedExpr is the expression of a column that declares no type and
// takes its value, and so its type, from an expression over the row, as a
// SQL Server computed column does.
func generatedExpr(col *ast.ColumnDef) ast.Node {
if col == nil || col.TypeName != nil {
return nil
}
for _, item := range listItems(col.Constraints) {
if c, ok := item.(*ast.Constraint); ok && c.Contype == ast.ConstrTypeGenerated {
return c.RawExpr
}
}
return nil
}

// applyGenerated records a generated column with the type and nullability
// of its expression, typed against the table's other columns. One whose
// expression cannot be typed is left untyped rather than failing the schema.
// An engine that reports most generated columns nullable whatever their
// expression marks NOT NULL the ones that keep their expression's.
func applyGenerated(cat *core.Catalog, classOID int64, table *ast.TableName, col *ast.ColumnDef, num int) error {
sel := &ast.SelectStmt{
TargetList: &ast.List{Items: []ast.Node{&ast.ResTarget{Val: generatedExpr(col)}}},
FromClause: &ast.List{Items: []ast.Node{&ast.RangeVar{Schemaname: &table.Schema, Relname: &table.Name}}},
}
var res core.Column
var typeOID int64
if r, err := analyzer.Prepare(cat, sel); err == nil && len(r.Columns) == 1 {
res, typeOID = r.Columns[0], r.Columns[0].TypeOID
// An expression's type may carry arguments, as decimal(10,2) does,
// that no column has interned yet, and for which the analysis
// reports the family's row.
if res.Type != nil && (typeOID == 0 || len(res.Type.Args) > 0) {
t := *res.Type
t.Nullable = false
typeOID, _ = cat.ResolveTypeExpr(&t)
}
}
if typeOID == 0 {
anyOID, err := cat.ResolveTypeName("any")
if err != nil {
return err
}
res, typeOID = core.Column{}, anyOID
}
return cat.CreateAttributeSpec(core.AttributeSpec{
ClassOID: classOID,
Name: col.Colname,
TypeOID: typeOID,
Num: num,
NotNull: col.IsNotNull && res.NotNull,
DeclType: res.DataType,
})
}

func applyDropTable(cat *core.Catalog, stmt *ast.DropTableStmt) error {
for _, tn := range stmt.Tables {
if tn == nil {
Expand Down Expand Up @@ -232,11 +305,17 @@ func applyAlterTable(cat *core.Catalog, stmt *ast.AlterTableStmt) error {
if cmd.Def == nil {
continue
}
typeOID, err := columnTypeOID(cat, cmd.Def)
num, err := cat.NextAttributeNum(classOID)
if err != nil {
return err
}
num, err := cat.NextAttributeNum(classOID)
if generatedExpr(cmd.Def) != nil {
if err := applyGenerated(cat, classOID, table, cmd.Def, num); err != nil {
return err
}
continue
}
typeOID, err := columnTypeOID(cat, cmd.Def)
if err != nil {
return err
}
Expand Down Expand Up @@ -328,6 +407,25 @@ func applyRenameTable(cat *core.Catalog, stmt *ast.RenameTableStmt) error {
return cat.RenameClass(classOID, *stmt.NewName)
}

// applySetSchema moves a relation to another schema.
func applySetSchema(cat *core.Catalog, stmt *ast.AlterTableSetSchemaStmt) error {
if stmt.NewSchema == nil {
return nil
}
classOID, err := lookupClass(cat, stmt.Table)
if err != nil {
if stmt.MissingOk {
return nil
}
return err
}
nsOID, err := resolveOrCreateNamespace(cat, *stmt.NewSchema)
if err != nil {
return err
}
return cat.SetClassNamespace(classOID, nsOID)
}

func lookupClass(cat *core.Catalog, table *ast.TableName) (int64, error) {
if table == nil {
return 0, fmt.Errorf("missing table name")
Expand Down Expand Up @@ -413,6 +511,15 @@ func applyCreateDomain(cat *core.Catalog, stmt *ast.CreateDomainStmt) error {
return err
}

func hasOption(options *ast.List, name string) bool {
for _, item := range listItems(options) {
if def, ok := item.(*ast.DefElem); ok && def.Defname != nil && *def.Defname == name {
return true
}
}
return false
}

// applyCompositeType records a composite type as a type whose arguments are
// its fields, labelled by name.
func applyCompositeType(cat *core.Catalog, stmt *ast.CompositeTypeStmt) error {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"command": "analyze",
"args": ["--dialect", "mssql", "--schema", "schema.sql", "query.sql"],
"contexts": ["base"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- name: ListItems :many
SELECT * FROM items;
10 changes: 10 additions & 0 deletions internal/endtoend/testdata/analyze_alter_column/mssql/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE items (
id INT NOT NULL,
code INT NOT NULL,
label VARCHAR(10) NOT NULL,
note INT NULL
);

ALTER TABLE items ALTER COLUMN code BIGINT;
ALTER TABLE items ALTER COLUMN label NVARCHAR(50) NOT NULL;
ALTER TABLE items ALTER COLUMN note INT NOT NULL;
43 changes: 43 additions & 0 deletions internal/endtoend/testdata/analyze_alter_column/mssql/stdout.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[
{
"name": "ListItems",
"cmd": ":many",
"columns": [
{
"name": "id",
"type": {
"name": "int"
},
"table": "items"
},
{
"name": "code",
"type": {
"name": "bigint",
"nullable": true
},
"table": "items"
},
{
"name": "label",
"type": {
"name": "nvarchar",
"args": [
{
"int": 50
}
]
},
"table": "items"
},
{
"name": "note",
"type": {
"name": "int"
},
"table": "items"
}
],
"params": []
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"command": "analyze",
"args": ["--dialect", "mssql", "--schema", "schema.sql", "query.sql"],
"contexts": ["base"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- name: GetComputed :one
SELECT total, doubled, doubled_nn, label, bio_label, cost, precise, price_text, extra
FROM authors
WHERE id = @id;

-- name: ListAuthors :many
SELECT * FROM authors;

-- name: CreateAuthor :exec
INSERT INTO authors (name, bio, price) VALUES (@name, @bio, @price);
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
CREATE TABLE authors (
id BIGINT IDENTITY(1,1) PRIMARY KEY,
name NVARCHAR(100) NOT NULL,
bio NVARCHAR(200) NULL,
price INT NOT NULL,
total AS (id * 2),
doubled AS (price * 2) PERSISTED,
doubled_nn AS (price * 2) PERSISTED NOT NULL,
label AS (name + N'!'),
bio_label AS (bio + N'?'),
cost AS (CAST(price AS decimal(10,2))),
precise AS (CAST(price AS decimal(17,9))),
price_text AS (CAST(price AS nvarchar(37)))
);

ALTER TABLE authors ADD extra AS (price + 1);
Loading