Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: remove legacy PostgreSQL AST system (#18004)

h3n4l5c505b9a8f8d
diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.go
index 5fa831d5e9..b45cdec483 100644
--- a/backend/plugin/advisor/catalog/walk_through.go
+++ b/backend/plugin/advisor/catalog/walk_through.go
@@ -2,6 +2,7 @@ package catalog
import (
"fmt"
+ "regexp"
"strings"
tidbast "github.com/pingcap/tidb/pkg/parser/ast"
@@ -25,6 +26,8 @@ const (
// SpatialName is the string for SPATIAL.
SpatialName string = "SPATIAL"
+ publicSchemaName = "public"
+
// ErrorTypeUnsupported is the error for unsupported cases.
ErrorTypeUnsupported WalkThroughErrorType = 1
// ErrorTypeInternal is the error for internal errors.
@@ -209,25 +212,18 @@ func (d *DatabaseState) WalkThrough(ast any) error {
err := d.mysqlWalkThrough(ast)
return err
case storepb.Engine_POSTGRES:
- // Check if this is ANTLR ParseResult or legacy AST
- if parseResult, ok := ast.(*pgparser.ParseResult); ok {
- // ANTLR-based walkthrough
- if err := d.pgAntlrWalkThrough(parseResult.Tree); err != nil {
- if d.ctx.CheckIntegrity {
- return err
- }
- d.usable = false
+ // ANTLR-based walkthrough
+ parseResult, ok := ast.(*pgparser.ParseResult)
+ if !ok {
+ return &WalkThroughError{
+ Type: ErrorTypeUnsupported,
+ Content: fmt.Sprintf("PostgreSQL walk-through expects *pgparser.ParseResult, got %T", ast),
}
- return nil
}
- // Legacy AST walkthrough
- if err := d.pgWalkThrough(ast); err != nil {
+ if err := d.pgAntlrWalkThrough(parseResult.Tree); err != nil {
if d.ctx.CheckIntegrity {
return err
}
- // For PostgreSQL, we only support to walk-through with CheckIntegrity == true.
- // If CheckIntegrity == false, we'll try to walk-through with empty public schema.
- // We use `usable` to check if walk-through successfully.
d.usable = false
}
return nil
@@ -1406,3 +1402,115 @@ func getIndexType(option *tidbast.IndexOption) string {
}
return tidbast.IndexTypeBtree.String()
}
+
+// PostgreSQL-specific helper methods.
+
+func parseViewName(viewName string) (string, string, error) {
+ pattern := `^"(.+?)"\."(.+?)"$`
+
+ re := regexp.MustCompile(pattern)
+
+ match := re.FindStringSubmatch(viewName)
+
+ if len(match) != 3 {
+ return "", "", errors.Errorf("invalid view name: %s", viewName)
+ }
+
+ return match[1], match[2], nil
+}
+
+func (d *DatabaseState) existedViewList(viewMap map[string]bool) ([]string, *WalkThroughError) {
+ var result []string
+ for viewName := range viewMap {
+ schemaName, viewName, err := parseViewName(viewName)
+ if err != nil {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeInternal,
+ Content: fmt.Sprintf("failed to check view dependency: %s", err.Error()),
+ }
+ }
+ schemaMeta, exists := d.schemaSet[schemaName]
+ if !exists {
+ continue
+ }
+ if _, exists := schemaMeta.viewSet[viewName]; !exists {
+ continue
+ }
+
+ result = append(result, fmt.Sprintf("%q.%q", schemaName, viewName))
+ }
+ return result, nil
+}
+
+func (s *SchemaState) pgGeneratePrimaryKeyName(tableName string) string {
+ pkName := fmt.Sprintf("%s_pkey", tableName)
+ if _, exists := s.identifierMap[pkName]; !exists {
+ return pkName
+ }
+ suffix := 1
+ for {
+ if _, exists := s.identifierMap[fmt.Sprintf("%s%d", pkName, suffix)]; !exists {
+ return fmt.Sprintf("%s%d", pkName, suffix)
+ }
+ suffix++
+ }
+}
+
+func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThroughError) {
+ if schemaName == "" {
+ schemaName = publicSchemaName
+ }
+ schema, exists := d.schemaSet[schemaName]
+ if !exists {
+ if schemaName != publicSchemaName {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeSchemaNotExists,
+ Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),
+ }
+ }
+ schema = &SchemaState{
+ ctx: d.ctx.Copy(),
+ name: publicSchemaName,
+ tableSet: make(tableStateMap),
+ viewSet: make(viewStateMap),
+ identifierMap: make(identifierMap),
+ }
+ d.schemaSet[publicSchemaName] = schema
+ }
+ return schema, nil
+}
+
+func (t *TableState) getColumn(columnName string) (*ColumnState, *WalkThroughError) {
+ column, exists := t.columnSet[columnName]
+ if !exists {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeColumnNotExists,
+ Content: fmt.Sprintf("The column %q does not exist in the table %q", columnName, t.name),
+ }
+ }
+ return column, nil
+}
+
+func (s *SchemaState) pgGetTable(tableName string) (*TableState, *WalkThroughError) {
+ table, exists := s.tableSet[tableName]
+ if !exists {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeTableNotExists,
+ Content: fmt.Sprintf("The table %q does not exist in schema %q", tableName, s.name),
+ }
+ }
+ return table, nil
+}
+
+func (s *SchemaState) getIndex(indexName string) (*TableState, *IndexState, *WalkThroughError) {
+ for _, table := range s.tableSet {
+ if index, exists := table.indexSet[indexName]; exists {
+ return table, index, nil
+ }
+ }
+
+ return nil, nil, &WalkThroughError{
+ Type: ErrorTypeIndexNotExists,
+ Content: fmt.Sprintf("Index %q does not exists in schema %q", indexName, s.name),
+ }
+}
diff --git a/backend/plugin/advisor/catalog/walk_through_for_pg.go b/backend/plugin/advisor/catalog/walk_through_for_pg.go
deleted file mode 100644
index c7310184d0..0000000000
--- a/backend/plugin/advisor/catalog/walk_through_for_pg.go
+++ /dev/null
@@ -1,1115 +0,0 @@
-package catalog
-
-import (
- "fmt"
- "regexp"
- "strings"
-
- "github.com/pkg/errors"
-
- pgrawparser "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy"
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-)
-
-const (
- publicSchemaName = "public"
-)
-
-func (d *DatabaseState) pgWalkThrough(pgAst any) error {
- nodeList, ok := pgAst.([]ast.Node)
- if !ok {
- return errors.Errorf("invalid ast type %T", pgAst)
- }
- for _, node := range nodeList {
- if err := d.pgChangeState(node); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (d *DatabaseState) pgChangeState(in ast.Node) (err *WalkThroughError) {
- defer func() {
- if err == nil {
- return
- }
- if err.Line == 0 {
- err.Line = in.LastLine()
- }
- }()
-
- if d.deleted {
- return &WalkThroughError{
- Type: ErrorTypeDatabaseIsDeleted,
- Content: fmt.Sprintf(`Database %q is deleted`, d.name),
- }
- }
- switch node := in.(type) {
- case *ast.CreateTableStmt:
- return d.pgCreateTable(node)
- case *ast.CreateIndexStmt:
- return d.pgCreateIndex(node)
- case *ast.CreateViewStmt:
- return d.pgCreateView(node)
- case *ast.AlterTableStmt:
- return d.pgAlterTable(node)
- case *ast.RenameIndexStmt:
- return d.pgRenameIndex(node)
- case *ast.CreateSchemaStmt:
- return d.pgCreateSchema(node)
- case *ast.DropSchemaStmt:
- return d.pgDropSchema(node)
- case *ast.DropTableStmt:
- return d.pgDropTableList(node)
- case *ast.DropIndexStmt:
- return d.pgDropIndexList(node)
- default:
- return nil
- }
-}
-
-func (d *DatabaseState) pgDropIndexList(node *ast.DropIndexStmt) *WalkThroughError {
- for _, indexDef := range node.IndexList {
- if err := d.pgDropIndex(indexDef, node.IfExists, node.Behavior); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (d *DatabaseState) pgDropIndex(indexDef *ast.IndexDef, ifExists bool, _ ast.DropBehavior) *WalkThroughError {
- schemaName := ""
- if indexDef.Table != nil {
- schemaName = indexDef.Table.Schema
- }
- schema, err := d.getSchema(schemaName)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
-
- table, index, err := schema.getIndex(indexDef.Name)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
-
- delete(schema.identifierMap, index.name)
- delete(table.indexSet, index.name)
- return nil
-}
-
-func (d *DatabaseState) pgDropTableList(node *ast.DropTableStmt) *WalkThroughError {
- for _, tableName := range node.TableList {
- if tableName.Type == ast.TableTypeView {
- if err := d.pgDropView(tableName, node.IfExists, node.Behavior); err != nil {
- return err
- }
- } else {
- if err := d.pgDropTable(tableName, node.IfExists, node.Behavior); err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-func (d *DatabaseState) pgDropView(tableDef *ast.TableDef, ifExists bool, _ ast.DropBehavior) *WalkThroughError {
- schema, err := d.getSchema(tableDef.Schema)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
-
- delete(schema.identifierMap, tableDef.Name)
- delete(schema.viewSet, tableDef.Name)
- return nil
-}
-
-func parseViewName(viewName string) (string, string, error) {
- pattern := `^"(.+?)"\."(.+?)"$`
-
- re := regexp.MustCompile(pattern)
-
- match := re.FindStringSubmatch(viewName)
-
- if len(match) != 3 {
- return "", "", errors.Errorf("invalid view name: %s", viewName)
- }
-
- return match[1], match[2], nil
-}
-
-func (d *DatabaseState) existedViewList(viewMap map[string]bool) ([]string, *WalkThroughError) {
- var result []string
- for viewName := range viewMap {
- schemaName, viewName, err := parseViewName(viewName)
- if err != nil {
- return nil, &WalkThroughError{
- Type: ErrorTypeInternal,
- Content: fmt.Sprintf("failed to check view dependency: %s", err.Error()),
- }
- }
- schemaMeta, exists := d.schemaSet[schemaName]
- if !exists {
- continue
- }
- if _, exists := schemaMeta.viewSet[viewName]; !exists {
- continue
- }
-
- result = append(result, fmt.Sprintf("%q.%q", schemaName, viewName))
- }
- return result, nil
-}
-
-func (d *DatabaseState) pgDropTable(tableDef *ast.TableDef, ifExists bool, _ ast.DropBehavior) *WalkThroughError {
- schema, err := d.getSchema(tableDef.Schema)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
-
- table, err := schema.pgGetTable(tableDef.Name)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
-
- viewList, err := d.existedViewList(table.dependencyView)
- if err != nil {
- return err
- }
- if len(viewList) > 0 {
- return &WalkThroughError{
- Type: ErrorTypeTableIsReferencedByView,
- Content: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", schema.name, table.name, strings.Join(viewList, ", ")),
- Payload: viewList,
- }
- }
-
- for indexName := range table.indexSet {
- delete(schema.identifierMap, indexName)
- }
-
- delete(schema.identifierMap, table.name)
- delete(schema.tableSet, table.name)
- return nil
-}
-
-func (d *DatabaseState) pgDropSchema(node *ast.DropSchemaStmt) *WalkThroughError {
- for _, schemaName := range node.SchemaList {
- schema, err := d.getSchema(schemaName)
- if err != nil {
- if node.IfExists {
- continue
- }
- return err
- }
-
- delete(d.schemaSet, schema.name)
- }
-
- return nil
-}
-
-func (d *DatabaseState) pgCreateSchema(node *ast.CreateSchemaStmt) *WalkThroughError {
- if _, exists := d.schemaSet[node.Name]; exists {
- return &WalkThroughError{
- Type: ErrorTypeSchemaExists,
- Content: fmt.Sprintf("Schema %q already exists", node.Name),
- }
- }
-
- schema := &SchemaState{
- ctx: d.ctx.Copy(),
- name: node.Name,
- identifierMap: make(identifierMap),
- tableSet: make(tableStateMap),
- viewSet: make(viewStateMap),
- }
- d.schemaSet[schema.name] = schema
-
- for _, item := range node.SchemaElementList {
- switch itemNode := item.(type) {
- // TODO(rebelice): deal with other item type here.
- case *ast.CreateTableStmt:
- if err := d.pgCreateTable(itemNode); err != nil {
- return err
- }
- default:
- // TODO: hack the linter.
- }
- }
-
- return nil
-}
-
-func (d *DatabaseState) pgRenameIndex(node *ast.RenameIndexStmt) *WalkThroughError {
- schema, err := d.getSchema(node.Table.Schema)
- if err != nil {
- return err
- }
- table, index, err := schema.getIndex(node.IndexName)
- if err != nil {
- return err
- }
- if _, exists := schema.identifierMap[node.NewName]; exists {
- return NewRelationExistsError(node.NewName, schema.name)
- }
-
- delete(schema.identifierMap, index.name)
- delete(table.indexSet, index.name)
- index.name = node.NewName
- schema.identifierMap[index.name] = true
- table.indexSet[index.name] = index
- return nil
-}
-
-func (d *DatabaseState) pgAlterTable(node *ast.AlterTableStmt) *WalkThroughError {
- if node.Table.Type != ast.TableTypeBaseTable {
- return nil
- }
-
- schema, err := d.getSchema(node.Table.Schema)
- if err != nil {
- return err
- }
- table, err := schema.pgGetTable(node.Table.Name)
- if err != nil {
- return err
- }
-
- for _, item := range node.AlterItemList {
- switch itemNode := item.(type) {
- case *ast.RenameColumnStmt:
- if err := table.pgRenameColumn(itemNode); err != nil {
- return err
- }
- case *ast.RenameConstraintStmt:
- if err := schema.pgRenameConstraint(table, itemNode); err != nil {
- return err
- }
- case *ast.RenameTableStmt:
- if err := schema.pgRenameTable(table, itemNode); err != nil {
- return err
- }
- case *ast.SetSchemaStmt:
- if err := d.pgSetSchema(schema, table, itemNode); err != nil {
- return err
- }
- case *ast.AddColumnListStmt:
- if err := schema.pgAddColumn(table, itemNode); err != nil {
- return err
- }
- case *ast.DropColumnStmt:
- if err := d.pgDropColumn(schema, table, itemNode); err != nil {
- return err
- }
- case *ast.AlterColumnTypeStmt:
- if err := d.pgAlterColumnType(schema, table, itemNode); err != nil {
- return err
- }
- case *ast.SetDefaultStmt:
- if err := table.pgSetDefault(itemNode); err != nil {
- return err
- }
- case *ast.DropDefaultStmt:
- if err := table.pgDropDefault(itemNode); err != nil {
- return err
- }
- case *ast.SetNotNullStmt:
- if err := table.pgSetNotNull(itemNode); err != nil {
- return err
- }
- case *ast.DropNotNullStmt:
- if err := table.pgDropNotNull(itemNode); err != nil {
- return err
- }
- case *ast.AddConstraintStmt:
- if err := schema.pgCreateTableConstraint(table, itemNode.Constraint); err != nil {
- return err
- }
- case *ast.DropConstraintStmt:
- if err := schema.pgDropConstraint(table, itemNode); err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-func (s *SchemaState) pgDropConstraint(t *TableState, node *ast.DropConstraintStmt) *WalkThroughError {
- if index, exists := t.indexSet[node.ConstraintName]; exists {
- delete(s.identifierMap, index.name)
- delete(t.indexSet, index.name)
- }
-
- // TODO(rebelice): deal with other constraints
-
- // TODO(rebelice): deal with CASCADE
-
- return nil
-}
-
-func (t *TableState) pgDropNotNull(node *ast.DropNotNullStmt) *WalkThroughError {
- column, err := t.getColumn(node.ColumnName)
- if err != nil {
- return err
- }
-
- column.nullable = newTruePointer()
- return nil
-}
-
-func (t *TableState) pgSetNotNull(node *ast.SetNotNullStmt) *WalkThroughError {
- column, err := t.getColumn(node.ColumnName)
- if err != nil {
- return err
- }
-
- column.nullable = newFalsePointer()
- return nil
-}
-
-func (t *TableState) pgDropDefault(node *ast.DropDefaultStmt) *WalkThroughError {
- column, err := t.getColumn(node.ColumnName)
- if err != nil {
- return err
- }
-
- column.defaultValue = nil
- return nil
-}
-
-func (t *TableState) pgSetDefault(node *ast.SetDefaultStmt) *WalkThroughError {
- column, err := t.getColumn(node.ColumnName)
- if err != nil {
- return err
- }
-
- column.defaultValue = newStringPointer(node.Expression.Text())
- return nil
-}
-
-func (d *DatabaseState) pgAlterColumnType(schema *SchemaState, t *TableState, node *ast.AlterColumnTypeStmt) *WalkThroughError {
- column, err := t.getColumn(node.ColumnName)
- if err != nil {
- return err
- }
-
- viewList, err := d.existedViewList(column.dependencyView)
- if err != nil {
- return err
- }
- if len(viewList) > 0 {
- return &WalkThroughError{
- Type: ErrorTypeColumnIsReferencedByView,
- Content: fmt.Sprintf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, t.name, strings.Join(viewList, ", ")),
- Payload: viewList,
- }
- }
-
- typeString, deparseErr := pgrawparser.Deparse(pgrawparser.DeparseContext{}, node.Type)
- if deparseErr != nil {
- return &WalkThroughError{
- Type: ErrorTypeDeparseError,
- Content: err.Error(),
- }
- }
- column.columnType = &typeString
- column.collation = newStringPointer(normalizeCollation(node.Collation))
- // TODO(rebelice): support USING expression
- return nil
-}
-
-func (d *DatabaseState) pgDropColumn(schema *SchemaState, t *TableState, node *ast.DropColumnStmt) *WalkThroughError {
- column, exists := t.columnSet[node.ColumnName]
- if !exists {
- if node.IfExists {
- return nil
- }
- return NewColumnNotExistsError(t.name, node.ColumnName)
- }
-
- viewList, err := d.existedViewList(column.dependencyView)
- if err != nil {
- return err
- }
- if len(viewList) > 0 {
- return &WalkThroughError{
- Type: ErrorTypeColumnIsReferencedByView,
- Content: fmt.Sprintf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, t.name, strings.Join(viewList, ", ")),
- Payload: viewList,
- }
- }
-
- // Drop the constraints and indexes involving the column.
- var dropIndexList []string
-
- for _, index := range t.indexSet {
- for _, key := range index.expressionList {
- // TODO(rebelice): deal with expression key.
- if key == node.ColumnName {
- dropIndexList = append(dropIndexList, index.name)
- break // Once we find the column in this index, mark for deletion and move to next index
- }
- }
- }
- for _, indexName := range dropIndexList {
- delete(t.indexSet, indexName)
- }
-
- // TODO(rebelice): deal with other constraints.
-
- // TODO(rebelice): deal with CASCADE.
-
- delete(t.columnSet, node.ColumnName)
- return nil
-}
-
-func (s *SchemaState) pgAddColumn(t *TableState, node *ast.AddColumnListStmt) *WalkThroughError {
- if len(node.ColumnList) != 1 {
- return &WalkThroughError{
- Type: ErrorTypeInvalidStatement,
- Content: "PostgreSQL doesn't support to add multi-columns in one ADD COLUMN statement",
- }
- }
- return s.pgCreateColumn(t, node.ColumnList[0], node.IfNotExists)
-}
-
-func (d *DatabaseState) pgSetSchema(oldSchema *SchemaState, t *TableState, node *ast.SetSchemaStmt) *WalkThroughError {
- newSchema, exists := d.schemaSet[node.NewSchema]
- if !exists {
- return &WalkThroughError{
- Type: ErrorTypeSchemaNotExists,
- Content: fmt.Sprintf("Schema %q does not exist", node.NewSchema),
- }
- }
-
- if _, exists := newSchema.identifierMap[t.name]; exists {
- return NewRelationExistsError(t.name, newSchema.name)
- }
-
- for indexName := range t.indexSet {
- if _, exists := newSchema.identifierMap[indexName]; exists {
- return NewRelationExistsError(indexName, newSchema.name)
- }
- }
-
- // TODO(rebelice): check other constraints and sequences here.
-
- for indexName := range t.indexSet {
- delete(oldSchema.identifierMap, indexName)
- newSchema.identifierMap[indexName] = true
- }
-
- delete(oldSchema.identifierMap, t.name)
- delete(oldSchema.tableSet, t.name)
- newSchema.identifierMap[t.name] = true
- newSchema.tableSet[t.name] = t
- return nil
-}
-
-func (s *SchemaState) pgRenameTable(t *TableState, node *ast.RenameTableStmt) *WalkThroughError {
- if _, exists := s.identifierMap[node.NewName]; exists {
- return NewRelationExistsError(node.NewName, s.name)
- }
-
- delete(s.identifierMap, t.name)
- delete(s.tableSet, t.name)
- t.name = node.NewName
- s.identifierMap[t.name] = true
- s.tableSet[t.name] = t
- return nil
-}
-
-func (s *SchemaState) pgRenameConstraint(t *TableState, node *ast.RenameConstraintStmt) *WalkThroughError {
- index, exists := t.indexSet[node.ConstraintName]
- if !exists {
- // We haven't deal with foreign and check constraints, so skip if not exists.
- return nil
- }
- // TODO(rebelice): check other constraints here.
-
- if !index.isConstraint {
- return &WalkThroughError{
- Type: ErrorTypeConstraintNotExists,
- Content: fmt.Sprintf("Constraint %q for table %q does not exist", node.ConstraintName, t.name),
- }
- }
-
- if _, exists := s.identifierMap[node.NewName]; exists {
- return NewRelationExistsError(node.NewName, s.name)
- }
-
- delete(s.identifierMap, node.ConstraintName)
- delete(t.indexSet, node.ConstraintName)
- index.name = node.NewName
- s.identifierMap[index.name] = true
- t.indexSet[index.name] = index
- return nil
-}
-
-func (t *TableState) pgRenameColumn(node *ast.RenameColumnStmt) *WalkThroughError {
- column, err := t.getColumn(node.ColumnName)
- if err != nil {
- return err
- }
- if node.ColumnName == node.NewName {
- return nil
- }
- if _, exists := t.columnSet[node.NewName]; exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("The column %q already exists in table %q", node.NewName, t.name),
- }
- }
-
- delete(t.columnSet, column.name)
-
- for _, index := range t.indexSet {
- for i, key := range index.expressionList {
- // TODO(rebelice): only deal with the column type index key here.
- if key == column.name {
- index.expressionList[i] = node.NewName
- }
- }
- }
-
- column.name = node.NewName
- t.columnSet[node.NewName] = column
- return nil
-}
-
-func (d *DatabaseState) pgCreateIndex(node *ast.CreateIndexStmt) *WalkThroughError {
- schema, err := d.getSchema(node.Index.Table.Schema)
- if err != nil {
- return err
- }
- return schema.pgCreateIndex(node, false /* isPrimary */, false /* isConstraint */)
-}
-
-func (d *DatabaseState) pgCreateView(node *ast.CreateViewStmt) *WalkThroughError {
- if node.Name.Database != "" && d.name != node.Name.Database {
- return &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", node.Name.Database, d.name),
- }
- }
-
- schema, err := d.getSchema(node.Name.Schema)
- if err != nil {
- return err
- }
-
- if _, exists := schema.viewSet[node.Name.Name]; exists {
- // TODO: currently we don't check views.
- return nil
- }
-
- view := &ViewState{
- name: node.Name.Name,
- }
- schema.viewSet[view.name] = view
-
- return nil
-}
-
-func (d *DatabaseState) pgCreateTable(node *ast.CreateTableStmt) *WalkThroughError {
- if node.Name.Database != "" && d.name != node.Name.Database {
- return &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", node.Name.Database, d.name),
- }
- }
-
- schema, err := d.getSchema(node.Name.Schema)
- if err != nil {
- return err
- }
-
- if _, exists := schema.tableSet[node.Name.Name]; exists {
- if node.IfNotExists {
- return nil
- }
- return &WalkThroughError{
- Type: ErrorTypeTableExists,
- Content: fmt.Sprintf(`The table %q already exists in the schema %q`, node.Name.Name, schema.name),
- }
- }
-
- table := &TableState{
- name: node.Name.Name,
- columnSet: make(columnStateMap),
- indexSet: make(IndexStateMap),
- }
- schema.tableSet[table.name] = table
-
- for _, column := range node.ColumnList {
- if err := schema.pgCreateColumn(table, column, false /* ifNotExists */); err != nil {
- err.Line = column.LastLine()
- return err
- }
- }
-
- for _, constraint := range node.ConstraintList {
- if err := schema.pgCreateTableConstraint(table, constraint); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *SchemaState) pgCreateTableConstraint(t *TableState, constraint *ast.ConstraintDef) *WalkThroughError {
- switch constraint.Type {
- case ast.ConstraintTypePrimary:
- return s.pgCreatePrimaryKey(t, constraint)
- case ast.ConstraintTypePrimaryUsingIndex:
- return s.pgCreatePrimaryKeyUsingIndex(t, constraint)
- case ast.ConstraintTypeUnique:
- var indexKeyList []*ast.IndexKeyDef
- for _, key := range constraint.KeyList {
- indexKeyList = append(indexKeyList, &ast.IndexKeyDef{
- Type: ast.IndexKeyTypeColumn,
- Key: key,
- })
- }
- return s.pgCreateIndex(&ast.CreateIndexStmt{
- IfNotExists: false,
- Index: &ast.IndexDef{
- Name: constraint.Name,
- Table: &ast.TableDef{
- Name: t.name,
- Schema: s.name,
- },
- Unique: true,
- Method: ast.IndexMethodTypeBTree,
- KeyList: indexKeyList,
- },
- }, false /* isPrimary */, true /* isConstraint */)
- case ast.ConstraintTypeUniqueUsingIndex:
- return s.pgCreateUniqueUsingIndex(t, constraint)
- case ast.ConstraintTypeCheck:
- // We do not deal with CHECK constraint.
- case ast.ConstraintTypeExclusion:
- // We do not deal with EXCLUSION constraint.
- case ast.ConstraintTypeForeign:
- // We do not deal with FOREIGN constraint.
- default:
- // For any other constraint types, skip processing
- }
- return nil
-}
-
-func (s *SchemaState) pgCreateColumn(t *TableState, column *ast.ColumnDef, ifNotExists bool) *WalkThroughError {
- if _, exists := t.columnSet[column.ColumnName]; exists {
- if ifNotExists {
- return nil
- }
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("The column %q already exists in table %q", column.ColumnName, t.name),
- }
- }
-
- pos := len(t.columnSet) + 1
- typeString, err := pgrawparser.Deparse(pgrawparser.DeparseContext{}, column.Type)
- if err != nil {
- return &WalkThroughError{
- Type: ErrorTypeDeparseError,
- Content: err.Error(),
- }
- }
-
- columnState := &ColumnState{
- name: column.ColumnName,
- position: &pos,
- defaultValue: nil,
- nullable: newTruePointer(),
- columnType: &typeString,
- collation: newStringPointer(normalizeCollation(column.Collation)),
- // TODO(rebelice): support comment here.
- }
- t.columnSet[columnState.name] = columnState
-
- for _, constraint := range column.ConstraintList {
- switch constraint.Type {
- case ast.ConstraintTypePrimary:
- if err := s.pgCreatePrimaryKey(t, constraint); err != nil {
- return err
- }
- case ast.ConstraintTypePrimaryUsingIndex:
- if err := s.pgCreatePrimaryKeyUsingIndex(t, constraint); err != nil {
- return err
- }
- case ast.ConstraintTypeNotNull:
- columnState.nullable = newFalsePointer()
- case ast.ConstraintTypeDefault:
- columnState.defaultValue = newStringPointer(constraint.Expression.Text())
- case ast.ConstraintTypeUnique:
- if err := s.pgCreateIndex(&ast.CreateIndexStmt{
- IfNotExists: false,
- Index: &ast.IndexDef{
- Table: &ast.TableDef{
- Schema: s.name,
- Name: t.name,
- },
- Unique: true,
- KeyList: []*ast.IndexKeyDef{
- {
- Type: ast.IndexKeyTypeColumn,
- Key: column.ColumnName,
- },
- },
- Method: ast.IndexMethodTypeBTree,
- },
- }, false /* isPrimary */, true /* isConstraint */); err != nil {
- return err
- }
- case ast.ConstraintTypeUniqueUsingIndex:
- if err := s.pgCreateUniqueUsingIndex(t, constraint); err != nil {
- return err
- }
- case ast.ConstraintTypeCheck:
- // We do not deal with CHECK constraint.
- case ast.ConstraintTypeExclusion:
- // We do not deal with EXCLUSION constraint.
- case ast.ConstraintTypeForeign:
- // We do not deal with FOREIGN constraint.
- default:
- // Other constraint types
- }
- }
-
- return nil
-}
-
-func (s *SchemaState) pgCreateUniqueUsingIndex(t *TableState, constraint *ast.ConstraintDef) *WalkThroughError {
- index, exists := t.indexSet[constraint.IndexName]
- if !exists {
- return NewIndexNotExistsError(t.name, constraint.IndexName)
- }
-
- var indexKeyList []*ast.IndexKeyDef
- for _, key := range index.expressionList {
- indexKeyList = append(indexKeyList, &ast.IndexKeyDef{
- Type: ast.IndexKeyTypeColumn,
- Key: key,
- })
- }
- if err := t.checkIndexKey(indexKeyList); err != nil {
- return err
- }
-
- index.unique = newTruePointer()
-
- if constraint.Name != "" && constraint.Name != index.name {
- if _, exists := s.identifierMap[constraint.Name]; exists {
- return NewRelationExistsError(constraint.Name, s.name)
- }
- delete(s.identifierMap, index.name)
- delete(t.indexSet, index.name)
- s.identifierMap[constraint.Name] = true
- index.name = constraint.Name
- t.indexSet[index.name] = index
- }
- return nil
-}
-
-func (s *SchemaState) pgCreatePrimaryKeyUsingIndex(t *TableState, constraint *ast.ConstraintDef) *WalkThroughError {
- index, exists := t.indexSet[constraint.IndexName]
- if !exists {
- return NewIndexNotExistsError(t.name, constraint.IndexName)
- }
-
- pkName := constraint.Name
- if pkName == "" {
- pkName = constraint.IndexName
- }
-
- createPK := &ast.ConstraintDef{
- Type: ast.ConstraintTypePrimary,
- Name: pkName,
- KeyList: index.expressionList,
- }
- delete(s.identifierMap, index.name)
- delete(t.indexSet, index.name)
- return s.pgCreatePrimaryKey(t, createPK)
-}
-
-func (s *SchemaState) pgCreatePrimaryKey(t *TableState, createPrimaryKey *ast.ConstraintDef) *WalkThroughError {
- for _, columnName := range createPrimaryKey.KeyList {
- column, exists := t.columnSet[columnName]
- if !exists {
- return NewColumnNotExistsError(t.name, columnName)
- }
- column.nullable = newFalsePointer()
- }
-
- pkName := createPrimaryKey.Name
- if pkName == "" {
- pkName = s.pgGeneratePrimaryKeyName(t.name)
- }
-
- return s.pgCreateIndex(&ast.CreateIndexStmt{
- IfNotExists: false,
- Index: &ast.IndexDef{
- Name: pkName,
- Table: &ast.TableDef{
- Name: t.name,
- Schema: s.name,
- },
- Unique: true,
- Method: ast.IndexMethodTypeBTree,
- KeyList: pgColumnNameListToKeyList(createPrimaryKey.KeyList),
- },
- }, true /* isPrimary */, true /* isConstraint */)
-}
-
-func pgColumnNameListToKeyList(columnList []string) []*ast.IndexKeyDef {
- var result []*ast.IndexKeyDef
- for _, columnName := range columnList {
- result = append(result, &ast.IndexKeyDef{
- Type: ast.IndexKeyTypeColumn,
- Key: columnName,
- })
- }
- return result
-}
-
-func (s *SchemaState) pgGeneratePrimaryKeyName(tableName string) string {
- pkName := fmt.Sprintf("%s_pkey", tableName)
- if _, exists := s.identifierMap[pkName]; !exists {
- return pkName
- }
- suffix := 1
- for {
- if _, exists := s.identifierMap[fmt.Sprintf("%s%d", pkName, suffix)]; !exists {
- return fmt.Sprintf("%s%d", pkName, suffix)
- }
- suffix++
- }
-}
-
-func (s *SchemaState) pgCreateIndex(createIndex *ast.CreateIndexStmt, isPrimary bool, isConstraint bool) *WalkThroughError {
- indexName := createIndex.Index.Name
- if len(createIndex.Index.KeyList) == 0 {
- return &WalkThroughError{
- Type: ErrorTypeIndexEmptyKeys,
- Content: fmt.Sprintf("Index %q in table %q has empty key", indexName, createIndex.Index.Table.Name),
- }
- }
-
- table, exists := s.tableSet[createIndex.Index.Table.Name]
- if !exists {
- return NewTableNotExistsError(createIndex.Index.Table.Name)
- }
-
- if indexName != "" {
- if _, exists := s.identifierMap[indexName]; exists {
- if createIndex.IfNotExists {
- return nil
- }
- return NewRelationExistsError(indexName, s.name)
- }
- } else {
- var err error
- indexName, err = s.pgGenerateIndexName(createIndex)
- if err != nil {
- return &WalkThroughError{
- Type: ErrorTypeInternal,
- Content: fmt.Sprintf("Failed to generate PostgreSQL index name: %s", err.Error()),
- }
- }
- }
-
- if err := table.checkIndexKey(createIndex.Index.KeyList); err != nil {
- return err
- }
-
- index := &IndexState{
- name: indexName,
- expressionList: pgKeyListToStringList(createIndex.Index.KeyList),
- indexType: newStringPointer(getIndexMethod(createIndex.Index.Method)),
- unique: newBoolPointer(createIndex.Index.Unique),
- primary: newBoolPointer(isPrimary),
- isConstraint: isConstraint,
- }
-
- table.indexSet[index.name] = index
- s.identifierMap[index.name] = true
- return nil
-}
-
-func (t *TableState) checkIndexKey(keyList []*ast.IndexKeyDef) *WalkThroughError {
- for _, key := range keyList {
- if key.Type == ast.IndexKeyTypeColumn {
- if _, exists := t.columnSet[key.Key]; !exists {
- return NewColumnNotExistsError(t.name, key.Key)
- }
- }
- }
- return nil
-}
-
-func getIndexMethod(method ast.IndexMethodType) string {
- switch method {
- case ast.IndexMethodTypeBTree:
- return "btree"
- case ast.IndexMethodTypeHash:
- return "hash"
- case ast.IndexMethodTypeGiST:
- return "gist"
- case ast.IndexMethodTypeSpGiST:
- return "spgist"
- case ast.IndexMethodTypeGin:
- return "gin"
- case ast.IndexMethodTypeBrin:
- return "brin"
- case ast.IndexMethodTypeIvfflat:
- return "ivfflat"
- default:
- return ""
- }
-}
-
-func pgKeyListToStringList(keyList []*ast.IndexKeyDef) []string {
- var result []string
- for _, key := range keyList {
- result = append(result, key.Key)
- }
- return result
-}
-
-func (s *SchemaState) pgGenerateIndexName(createIndex *ast.CreateIndexStmt) (string, error) {
- buf := &strings.Builder{}
- if _, err := buf.WriteString(createIndex.Index.Table.Name); err != nil {
- return "", err
- }
- exprText := "expr"
- expressionID := 0
- for _, key := range createIndex.Index.KeyList {
- if err := buf.WriteByte('_'); err != nil {
- return "", err
- }
- switch key.Type {
- case ast.IndexKeyTypeColumn:
- if _, err := buf.WriteString(key.Key); err != nil {
- return "", err
- }
- case ast.IndexKeyTypeExpression:
- if _, err := buf.WriteString(exprText); err != nil {
- return "", err
- }
- if expressionID != 0 {
- if _, err := fmt.Fprintf(buf, "%d", expressionID); err != nil {
- return "", err
- }
- }
- expressionID++
- default:
- // Other key types
- }
- }
- if _, err := buf.WriteString("_idx"); err != nil {
- return "", err
- }
- indexName := buf.String()
- if _, exists := s.identifierMap[indexName]; !exists {
- return indexName, nil
- }
- suffix := 1
- for {
- if _, exists := s.identifierMap[fmt.Sprintf("%s%d", indexName, suffix)]; !exists {
- return fmt.Sprintf("%s%d", indexName, suffix), nil
- }
- suffix++
- }
-}
-
-func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThroughError) {
- if schemaName == "" {
- schemaName = publicSchemaName
- }
- schema, exists := d.schemaSet[schemaName]
- if !exists {
- if schemaName != publicSchemaName {
- return nil, &WalkThroughError{
- Type: ErrorTypeSchemaNotExists,
- Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),
- }
- }
- schema = &SchemaState{
- ctx: d.ctx.Copy(),
- name: publicSchemaName,
- tableSet: make(tableStateMap),
- viewSet: make(viewStateMap),
- identifierMap: make(identifierMap),
- }
- d.schemaSet[publicSchemaName] = schema
- }
- return schema, nil
-}
-
-func (s *SchemaState) pgGetTable(tableName string) (*TableState, *WalkThroughError) {
- table, exists := s.tableSet[tableName]
- if !exists {
- return nil, &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("The table %q does not exist in schema %q", tableName, s.name),
- }
- }
- return table, nil
-}
-
-func (s *SchemaState) getIndex(indexName string) (*TableState, *IndexState, *WalkThroughError) {
- for _, table := range s.tableSet {
- if index, exists := table.indexSet[indexName]; exists {
- return table, index, nil
- }
- }
-
- return nil, nil, &WalkThroughError{
- Type: ErrorTypeIndexNotExists,
- Content: fmt.Sprintf("Index %q does not exists in schema %q", indexName, s.name),
- }
-}
-
-func (t *TableState) getColumn(columnName string) (*ColumnState, *WalkThroughError) {
- column, exists := t.columnSet[columnName]
- if !exists {
- return nil, &WalkThroughError{
- Type: ErrorTypeColumnNotExists,
- Content: fmt.Sprintf("The column %q does not exist in the table %q", columnName, t.name),
- }
- }
- return column, nil
-}
-
-func normalizeCollation(collation *ast.CollationNameDef) string {
- if collation == nil {
- return ""
- }
-
- if collation.Schema == "" || collation.Schema == "public" {
- return collation.Name
- }
-
- return fmt.Sprintf("%q.%q", collation.Schema, collation.Name)
-}
diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.go
index 6dba632145..510b47c4c2 100644
--- a/backend/plugin/advisor/catalog/walk_through_test.go
+++ b/backend/plugin/advisor/catalog/walk_through_test.go
@@ -12,13 +12,10 @@ import (
"google.golang.org/protobuf/testing/protocmp"
"gopkg.in/yaml.v3"
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
-
- // Register postgresql parser driver.
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/sheet"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
- _ "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy"
)
type testData struct {
diff --git a/backend/plugin/parser/base/interface.go b/backend/plugin/parser/base/interface.go
index 48b67ce0b8..6fc64da060 100644
--- a/backend/plugin/parser/base/interface.go
+++ b/backend/plugin/parser/base/interface.go
@@ -267,7 +267,7 @@ func RegisterParseFunc(engine storepb.Engine, f ParseFunc) {
// The return type (any) varies by database engine:
// - TiDB: []ast.StmtNode (github.com/pingcap/tidb/pkg/parser/ast)
// - MySQL, MariaDB, OceanBase: []*ParseResult (github.com/bytebase/bytebase/backend/plugin/parser/mysql)
-// - PostgreSQL: []ast.Node (github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast)
+// - PostgreSQL: *ParseResult (github.com/bytebase/bytebase/backend/plugin/parser/pg) - ANTLR-based
// - CockroachDB: statements.Statements (github.com/cockroachdb/cockroachdb-parser/pkg/sql/parser/statements)
// - Redshift: antlr.Tree
// - Oracle: antlr.Tree
diff --git a/backend/plugin/parser/pg/legacy/ast/add_column_list_stmt.go b/backend/plugin/parser/pg/legacy/ast/add_column_list_stmt.go
deleted file mode 100644
index b9b9143c8b..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/add_column_list_stmt.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package ast
-
-// AddColumnListStmt is the struct for add columns statement.
-// For PostgreSQL dialect is ALTER TABLE ADD COLUMN.
-type AddColumnListStmt struct {
- node
-
- Table *TableDef
- ColumnList []*ColumnDef
- IfNotExists bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/add_constraint_stmt.go b/backend/plugin/parser/pg/legacy/ast/add_constraint_stmt.go
deleted file mode 100644
index b468260cf2..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/add_constraint_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// AddConstraintStmt is the struct for add constraint statement.
-type AddConstraintStmt struct {
- node
-
- Table *TableDef
- Constraint *ConstraintDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/add_enum_label_stmt.go b/backend/plugin/parser/pg/legacy/ast/add_enum_label_stmt.go
deleted file mode 100644
index c2c69d7b14..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/add_enum_label_stmt.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package ast
-
-// PositionType is the type of new label position.
-type PositionType int
-
-const (
- // PositionTypeEnd is the type of new label at the end of the list labels. It's default label.
- PositionTypeEnd PositionType = iota
- // PositionTypeAfter is the type of after neighbor label.
- PositionTypeAfter
- // PositionTypeBefore is the type of before neighbor label.
- PositionTypeBefore
-)
-
-// AddEnumLabelStmt is the struct of add enum label statements.
-type AddEnumLabelStmt struct {
- node
-
- EnumType *TypeNameDef
- NewLabel string
- Position PositionType
- NeighborLabel string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/alter_column_type_stmt.go b/backend/plugin/parser/pg/legacy/ast/alter_column_type_stmt.go
deleted file mode 100644
index 3cd5223b0a..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/alter_column_type_stmt.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package ast
-
-// AlterColumnTypeStmt is the struct for alter column type statement.
-type AlterColumnTypeStmt struct {
- node
-
- Table *TableDef
- ColumnName string
- Type DataType
- Collation *CollationNameDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/alter_sequence_stmt.go b/backend/plugin/parser/pg/legacy/ast/alter_sequence_stmt.go
deleted file mode 100644
index f764025681..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/alter_sequence_stmt.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package ast
-
-// AlterSequenceStmt is the struct for alter sequence statements.
-type AlterSequenceStmt struct {
- ddl
-
- Name *SequenceNameDef
- IfExists bool
- Type *Integer
- IncrementBy *int64
- NoMinValue bool
- MinValue *int64
- NoMaxValue bool
- MaxValue *int64
- StartWith *int64
- RestartWith *int64
- Cache *int64
- Cycle *bool
- OwnedByNone bool
- OwnedBy *ColumnNameDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/alter_table_stmt.go b/backend/plugin/parser/pg/legacy/ast/alter_table_stmt.go
deleted file mode 100644
index cf410ee172..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/alter_table_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// AlterTableStmt is the struct for alter table or view statement.
-type AlterTableStmt struct {
- ddl
-
- Table *TableDef
- AlterItemList []Node
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/alter_type_stmt.go b/backend/plugin/parser/pg/legacy/ast/alter_type_stmt.go
deleted file mode 100644
index f0e65f17b7..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/alter_type_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// AlterTypeStmt is the struct for ALTER TYPE statements.
-type AlterTypeStmt struct {
- ddl
-
- Type *TypeNameDef
- AlterItemList []Node
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/attach_partition_stmt.go b/backend/plugin/parser/pg/legacy/ast/attach_partition_stmt.go
deleted file mode 100644
index 15bb16ed7b..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/attach_partition_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// AttachPartitionStmt is the attach partition statement.
-type AttachPartitionStmt struct {
- node
-
- Table *TableDef
- Partition *TableDef
- // TODO(rebelice): convert more attach partition statement fields.
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/bool_def.go b/backend/plugin/parser/pg/legacy/ast/bool_def.go
deleted file mode 100644
index b73b9bf210..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/bool_def.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// BoolDef is the struct for bool definition.
-type BoolDef struct {
- expression
-
- Value bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/change_column_stmt.go b/backend/plugin/parser/pg/legacy/ast/change_column_stmt.go
deleted file mode 100644
index 5c0da5b161..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/change_column_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// ChangeColumnStmt is the strcut for change column statement.
-type ChangeColumnStmt struct {
- node
-
- Table *TableDef
- OldColumnName string
- Column *ColumnDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/character.go b/backend/plugin/parser/pg/legacy/ast/character.go
deleted file mode 100644
index f6c50ee093..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/character.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ast
-
-import (
- "fmt"
- "strings"
-)
-
-var (
- _ DataType = (*Character)(nil)
-)
-
-// Character is the struct for the character.
-type Character struct {
- characterType
-
- // the storage size(characters, not bytes)
- Size int
-}
-
-// EquivalentType implements the DataType interface.
-func (c *Character) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- return tp == fmt.Sprintf("char(%d)", c.Size) || tp == fmt.Sprintf("character(%d)", c.Size)
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/character_varying.go b/backend/plugin/parser/pg/legacy/ast/character_varying.go
deleted file mode 100644
index 29c87214e2..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/character_varying.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ast
-
-import (
- "fmt"
- "strings"
-)
-
-var (
- _ DataType = (*CharacterVarying)(nil)
-)
-
-// CharacterVarying is the struct for the character varying(varchar).
-type CharacterVarying struct {
- characterType
-
- // the storage size(characters, not bytes)
- Size int
-}
-
-// EquivalentType implements the DataType interface.
-func (c *CharacterVarying) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- return tp == fmt.Sprintf("varchar(%d)", c.Size) || tp == fmt.Sprintf("character varying(%d)", c.Size)
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/column_def.go b/backend/plugin/parser/pg/legacy/ast/column_def.go
deleted file mode 100644
index f0896216f0..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/column_def.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ast
-
-// ColumnDef is struct for column definition.
-type ColumnDef struct {
- node
-
- ColumnName string
- Type DataType
- Collation *CollationNameDef
- ConstraintList []*ConstraintDef
-}
-
-// CollationNameDef is the struct for collation name.
-type CollationNameDef struct {
- node
-
- Schema string
- Name string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/column_name_def.go b/backend/plugin/parser/pg/legacy/ast/column_name_def.go
deleted file mode 100644
index 431755855a..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/column_name_def.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// ColumnNameDef is the struct for column name definition.
-type ColumnNameDef struct {
- expression
-
- Table *TableDef
- ColumnName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/comment_stmt.go b/backend/plugin/parser/pg/legacy/ast/comment_stmt.go
deleted file mode 100644
index f4b96e3f80..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/comment_stmt.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ast
-
-type ObjectType int
-
-const (
- ObjectTypeUndefined ObjectType = iota
- ObjectTypeTable
- ObjectTypeView
- ObjectTypeColumn
-)
-
-// CommentStmt is the struct for comment statement.
-type CommentStmt struct {
- node
-
- Type ObjectType
- Object Node
- Comment string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/commit_stmt.go b/backend/plugin/parser/pg/legacy/ast/commit_stmt.go
deleted file mode 100644
index 5a0d2b0a96..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/commit_stmt.go
+++ /dev/null
@@ -1,6 +0,0 @@
-package ast
-
-// CommitStmt is the struct for commit statement.
-type CommitStmt struct {
- node
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/constraint_def.go b/backend/plugin/parser/pg/legacy/ast/constraint_def.go
deleted file mode 100644
index 97f720a3b3..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/constraint_def.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package ast
-
-// ConstraintType is the type for constraints.
-type ConstraintType int
-
-const (
- // ConstraintTypeUndefined is the undefined type.
- ConstraintTypeUndefined ConstraintType = iota
- // ConstraintTypePrimary is the primary key constraint.
- ConstraintTypePrimary
- // ConstraintTypeUnique is the unique constraint.
- ConstraintTypeUnique
- // ConstraintTypeForeign is the foreign key constraint.
- ConstraintTypeForeign
- // ConstraintTypePrimaryUsingIndex is the primary key constraint only for the PostgreSQL table_constraint_using_index.
- // See https://www.postgresql.org/docs/current/sql-altertable.html.
- ConstraintTypePrimaryUsingIndex
- // ConstraintTypeUniqueUsingIndex is the unique constraint only for the PostgreSQL table_constraint_using_index.
- // See https://www.postgresql.org/docs/current/sql-altertable.html.
- ConstraintTypeUniqueUsingIndex
- // ConstraintTypeNotNull is the not null constraint.
- ConstraintTypeNotNull
- // ConstraintTypeCheck is the check constraint.
- ConstraintTypeCheck
- // ConstraintTypeExclusion is the exclude constraint.
- ConstraintTypeExclusion
- // ConstraintTypeDefault is the default constraint.
- ConstraintTypeDefault
- // ConstraintTypeGenerated is the generated constraint.
- ConstraintTypeGenerated
- // ConstraintTypeNull is the null constraint.
- ConstraintTypeNull
-)
-
-// ConstraintDef is struct for constraint definition.
-// For PRIMARY:
-//
-// Name: It's the PK constraint name.
-// KeyList: It's the name list of the columns in PK.
-//
-// For UNIQUE
-//
-// Name: It's the UK constraint name.
-// KeyList: It's the name list of the columns in UK.
-//
-// For Foreign
-//
-// Name: It's the FK constraint name.
-// KeyList: It's the name list of the columns in FK.
-// Foreign: It's the reference content for this FK.
-type ConstraintDef struct {
- node
-
- Type ConstraintType
- Name string
- // KeyList is the list for constraint key.
- // Whether it is a column constraint or a table constraint,
- // there is a corresponding key list.
- KeyList []string
- // Foreign is a FOREIGN type specific field.
- Foreign *ForeignDef
- // IndexName is a ConstraintTypePrimaryUsingIndex or ConstraintTypeUniqueUsingIndex type specific field.
- // See https://www.postgresql.org/docs/current/sql-altertable.html.
- IndexName string
- // For PG, the option SkipValidation is currently only allowed for foreign key and CHECK constraints.
- // If SkipValidation is true, the constraint will only be enforced against subsequent inserts or updates.
- SkipValidation bool
- // Expression is the expression for
- // 1. CHECK constraint
- // 2. DEFAULT constraint
- Expression ExpressionNode
- // WhereClause is the where clause for the EXCLUDE constraint.
- WhereClause string
- // Exclusions is the list of exclusion elements for the EXCLUDE constraint.
- Exclusions string
- // AccessMethod is the access method for the EXCLUDE constraint.
- AccessMethod IndexMethodType
- // https://www.postgresql.org/docs/14/sql-altertable.html
- Deferrable bool
- Initdeferred bool
- Including []string
- IndexTableSpace string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/copy_stmt.go b/backend/plugin/parser/pg/legacy/ast/copy_stmt.go
deleted file mode 100644
index 18f72413e7..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/copy_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// CopyStmt is the struct for copy statement.
-type CopyStmt struct {
- dml
-
- Table *TableDef
- FilePath string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_database_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_database_stmt.go
deleted file mode 100644
index 0f947be610..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_database_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// CreateDatabaseStmt is the struct for create database stmt.
-type CreateDatabaseStmt struct {
- ddl
-
- Name string
- OptionList []*DatabaseOptionDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_extension_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_extension_stmt.go
deleted file mode 100644
index 5e45b71680..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_extension_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// CreateExtensionStmt is the struct for create extension statement.
-type CreateExtensionStmt struct {
- ddl
-
- Name string
- Schema string
- IfNotExists bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_function_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_function_stmt.go
deleted file mode 100644
index 34fdf1a056..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_function_stmt.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package ast
-
-import (
- pgquery "github.com/pganalyze/pg_query_go/v6"
-)
-
-// CreateFunctionStmt is the struct for create function statement.
-type CreateFunctionStmt struct {
- ddl
-
- Function *FunctionDef
-
- originalNode *pgquery.Node_CreateFunctionStmt
-}
-
-func (cv *CreateFunctionStmt) SetOriginalNode(node *pgquery.Node_CreateFunctionStmt) {
- cv.originalNode = node
-}
-
-func (cv *CreateFunctionStmt) GetOriginalNode() *pgquery.Node_CreateFunctionStmt {
- return cv.originalNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_index_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_index_stmt.go
deleted file mode 100644
index e8d14f9f98..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_index_stmt.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package ast
-
-// CreateIndexStmt is the struct for create index statement.
-// TODO(rebelice): fully support CREATE INDEX statements.
-// Currently, only support:
-// ```
-// CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON table_name [ USING method ]
-// ( { column_name | ( expression ) } [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
-// ```.
-type CreateIndexStmt struct {
- ddl
-
- Index *IndexDef
- IfNotExists bool
- Concurrently bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_materialized_view_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_materialized_view_stmt.go
deleted file mode 100644
index 0340530156..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_materialized_view_stmt.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ast
-
-import pgquery "github.com/pganalyze/pg_query_go/v6"
-
-type CreateMaterializedViewStmt struct {
- ddl
-
- Name *TableDef
-
- originalNode *pgquery.Node_CreateTableAsStmt
-}
-
-func (cv *CreateMaterializedViewStmt) SetOriginalNode(node *pgquery.Node_CreateTableAsStmt) {
- cv.originalNode = node
-}
-
-func (cv *CreateMaterializedViewStmt) GetOriginalNode() *pgquery.Node_CreateTableAsStmt {
- return cv.originalNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_schema_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_schema_stmt.go
deleted file mode 100644
index c4a3db4b36..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_schema_stmt.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package ast
-
-// CreateSchemaStmt is the struct for create schema statement.
-type CreateSchemaStmt struct {
- ddl
-
- Name string
- IfNotExists bool
- RoleSpec *RoleSpec
- SchemaElementList []Node
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_sequence_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_sequence_stmt.go
deleted file mode 100644
index 57906a20be..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_sequence_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// CreateSequenceStmt is a statement to create a sequence.
-// https://www.postgresql.org/docs/13/sql-createsequence.html
-type CreateSequenceStmt struct {
- ddl
- SequenceDef SequenceDef
- IfNotExists bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_table_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_table_stmt.go
deleted file mode 100644
index 4974fb3833..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_table_stmt.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package ast
-
-// CreateTableStmt is the struct for create table stmt.
-type CreateTableStmt struct {
- ddl
-
- IfNotExists bool
- Name *TableDef
- ColumnList []*ColumnDef
- ConstraintList []*ConstraintDef
- PartitionDef *PartitionDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_trigger_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_trigger_stmt.go
deleted file mode 100644
index 572d314133..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_trigger_stmt.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// CreateTriggerStmt is the definition of create trigger statements.
-type CreateTriggerStmt struct {
- ddl
-
- Trigger *TriggerDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_type_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_type_stmt.go
deleted file mode 100644
index 6fc5c6ca05..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_type_stmt.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// CreateTypeStmt is the struct for CREATE TYPE statements.
-type CreateTypeStmt struct {
- ddl
-
- Type UserDefinedType
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/create_view_stmt.go b/backend/plugin/parser/pg/legacy/ast/create_view_stmt.go
deleted file mode 100644
index b5e987dfcf..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/create_view_stmt.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package ast
-
-import pgquery "github.com/pganalyze/pg_query_go/v6"
-
-type CreateViewStmt struct {
- ddl
-
- Name *TableDef
- Aliases []string
- Select *SelectStmt
- Replace bool
-
- originalNode *pgquery.Node_ViewStmt
-}
-
-func (cv *CreateViewStmt) SetOriginalNode(node *pgquery.Node_ViewStmt) {
- cv.originalNode = node
-}
-
-func (cv *CreateViewStmt) GetOriginalNode() *pgquery.Node_ViewStmt {
- return cv.originalNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/data_type.go b/backend/plugin/parser/pg/legacy/ast/data_type.go
deleted file mode 100644
index 2e4457da4b..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/data_type.go
+++ /dev/null
@@ -1,75 +0,0 @@
-package ast
-
-var (
- _ DataType = (*dataType)(nil)
- _ NumericType = (*numericType)(nil)
- _ UserDefinedType = (*userDefinedType)(nil)
-)
-
-// DataType is the interface for data type.
-type DataType interface {
- Node
-
- EquivalentType(string) bool
- dataTypeInterface()
-}
-
-type dataType struct {
- node
-}
-
-func (*dataType) dataTypeInterface() {}
-
-func (*dataType) EquivalentType(_ string) bool {
- return false
-}
-
-// NumericType is the interface for numeric type.
-type NumericType interface {
- DataType
-
- numericTypeInterface()
-}
-
-type numericType struct {
- dataType
-}
-
-func (*numericType) numericTypeInterface() {}
-
-// CharacterType is the interface for character type.
-type CharacterType interface {
- DataType
-
- characterTypeInterface()
-}
-
-type characterType struct {
- dataType
-}
-
-func (*characterType) characterTypeInterface() {}
-
-// UserDefinedType is the interface for user defined types.
-type UserDefinedType interface {
- DataType
-
- TypeName() *TypeNameDef
-}
-
-type userDefinedType struct {
- dataType
-}
-
-// TypeName implements the UserDefinedType interface.
-func (*userDefinedType) TypeName() *TypeNameDef {
- return &TypeNameDef{}
-}
-
-// TypeNameDef is the struct for user defined type names.
-type TypeNameDef struct {
- node
-
- Schema string
- Name string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/database_option_def.go b/backend/plugin/parser/pg/legacy/ast/database_option_def.go
deleted file mode 100644
index 87b830e511..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/database_option_def.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package ast
-
-// DatabaseOptionType is the type for database options.
-type DatabaseOptionType int
-
-const (
- // DatabaseOptionEncoding is the type for the database encoding option.
- DatabaseOptionEncoding DatabaseOptionType = iota
-)
-
-// DatabaseOptionDef is the struct for database option.
-type DatabaseOptionDef struct {
- node
-
- Type DatabaseOptionType
- Value string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/ddl_node.go b/backend/plugin/parser/pg/legacy/ast/ddl_node.go
deleted file mode 100644
index bee00dd10e..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/ddl_node.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package ast
-
-var (
- _ DDLNode = (*ddl)(nil)
-)
-
-// DDLNode is the interface for DDL.
-type DDLNode interface {
- Node
-
- ddlNode()
-}
-
-type ddl struct {
- node
-}
-
-func (*ddl) ddlNode() {}
diff --git a/backend/plugin/parser/pg/legacy/ast/decimal.go b/backend/plugin/parser/pg/legacy/ast/decimal.go
deleted file mode 100644
index 19f1c2ceaf..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/decimal.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package ast
-
-import "strings"
-
-// Decimal is the struct for decimal.
-type Decimal struct {
- numericType
-
- // See https://www.postgresql.org/docs/14/datatype-numeric.html.
- Precision int
- Scale int
-}
-
-// EquivalentType implements the DataType interface.
-func (*Decimal) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- return strings.HasPrefix(tp, "decimal") || strings.HasPrefix(tp, "numeric")
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/delete_stmt.go b/backend/plugin/parser/pg/legacy/ast/delete_stmt.go
deleted file mode 100644
index 9911d2dd76..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/delete_stmt.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package ast
-
-// DeleteStmt is the struct for delete statement.
-type DeleteStmt struct {
- dml
-
- Table *TableDef
- WhereClause ExpressionNode
-
- // TODO(rebelice): support all expression and remove them.
- // We define them because we cannot convert all expression now.
- // And we only need to check the following nodes currently.
- //
- // PatternLikeList is the list of the patternLike nodes.
- PatternLikeList []*PatternLikeDef
- // SubqueryList is the list of the subquery nodes.
- SubqueryList []*SubqueryDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/dml_node.go b/backend/plugin/parser/pg/legacy/ast/dml_node.go
deleted file mode 100644
index 7c71fc0e9d..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/dml_node.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package ast
-
-var (
- _ DMLNode = (*dml)(nil)
-)
-
-// DMLNode is the interface for DML.
-type DMLNode interface {
- Node
-
- dmlNode()
-}
-
-type dml struct {
- node
-}
-
-func (*dml) dmlNode() {}
diff --git a/backend/plugin/parser/pg/legacy/ast/docs.go b/backend/plugin/parser/pg/legacy/ast/docs.go
deleted file mode 100644
index 636b5d2467..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/docs.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package ast implements a simple ast for SQL.
-package ast
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_column_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_column_stmt.go
deleted file mode 100644
index ab7fc73142..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_column_stmt.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package ast
-
-// DropColumnStmt is the struct for drop column statement.
-type DropColumnStmt struct {
- node
-
- Table *TableDef
- ColumnName string
- IfExists bool
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_constraint_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_constraint_stmt.go
deleted file mode 100644
index 9f798ba27d..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_constraint_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// DropConstraintStmt is the struct for drop constraint statement.
-type DropConstraintStmt struct {
- node
-
- Table *TableDef
- ConstraintName string
- IfExists bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_database_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_database_stmt.go
deleted file mode 100644
index 092672a150..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_database_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// DropDatabaseStmt is the struct for drop database statement.
-type DropDatabaseStmt struct {
- ddl
-
- DatabaseName string
- IfExists bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_default_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_default_stmt.go
deleted file mode 100644
index fbc4656c96..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_default_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// DropDefaultStmt is the struct for drop default statement.
-type DropDefaultStmt struct {
- node
-
- Table *TableDef
- ColumnName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_extension_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_extension_stmt.go
deleted file mode 100644
index cc228b2900..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_extension_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// DropExtensionStmt is the struct for drop extension statement.
-type DropExtensionStmt struct {
- ddl
-
- NameList []string
- IfExists bool
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_function_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_function_stmt.go
deleted file mode 100644
index f1f172f209..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_function_stmt.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package ast
-
-// DropFunctionStmt is the struct for drop function statement.
-type DropFunctionStmt struct {
- ddl
-
- // Here use FunctionDef because the drop function statement needs:
- // 1. the schema name
- // 2. the function name
- // 3. the IN/INOUT/VARIADIC parameter type
- // hint: pg_query_go will skip the OUT parameters and only parse the parameter data type for DROP FUNCTION statements.
- FunctionList []*FunctionDef
- IfExists bool
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_index_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_index_stmt.go
deleted file mode 100644
index 5c3bf2a503..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_index_stmt.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package ast
-
-// DropIndexStmt is the struct for drop index statement.
-type DropIndexStmt struct {
- ddl
-
- // Here use IndexDef because the drop index statement needs the schema name for PostgreSQL.
- // If the drop index statement doesn't contain schema name, the Table of this index is nil.
- IndexList []*IndexDef
- IfExists bool
- Concurrently bool
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_not_null_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_not_null_stmt.go
deleted file mode 100644
index 1d373d77ec..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_not_null_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// DropNotNullStmt is the struct for set not null statement.
-type DropNotNullStmt struct {
- node
-
- Table *TableDef
- ColumnName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_schema_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_schema_stmt.go
deleted file mode 100644
index 87d8db7a22..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_schema_stmt.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package ast
-
-// DropBehavior is the type for drop object statements.
-type DropBehavior int
-
-const (
- // DropBehaviorNone is the default type for drop object statements.
- DropBehaviorNone DropBehavior = iota
- // DropBehaviorCascade is the type for drop object statements with cascade.
- DropBehaviorCascade
- // DropBehaviorRestrict is the type for drop object statement with restrict.
- DropBehaviorRestrict
-)
-
-// DropSchemaStmt is the struct for drop schema statement.
-type DropSchemaStmt struct {
- ddl
-
- IfExists bool
- SchemaList []string
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_sequence_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_sequence_stmt.go
deleted file mode 100644
index 51c32a8adb..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_sequence_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// DropSequenceStmt is the struct for drop sequence statement.
-type DropSequenceStmt struct {
- ddl
-
- IfExists bool
- SequenceNameList []*SequenceNameDef
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_table_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_table_stmt.go
deleted file mode 100644
index c977245b56..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_table_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// DropTableStmt is the struct for drop table or view statement.
-type DropTableStmt struct {
- ddl
-
- IfExists bool
- Behavior DropBehavior
- TableList []*TableDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_trigger_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_trigger_stmt.go
deleted file mode 100644
index f0c5016cd2..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_trigger_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// DropTriggerStmt is the definition of drop trigger statements.
-type DropTriggerStmt struct {
- ddl
-
- Trigger *TriggerDef
- IfExists bool
- Behavior DropBehavior
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/drop_type_stmt.go b/backend/plugin/parser/pg/legacy/ast/drop_type_stmt.go
deleted file mode 100644
index 2bea6b1213..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/drop_type_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// DropTypeStmt is the struct for DROP TYPE statements.
-type DropTypeStmt struct {
- ddl
-
- IfExists bool
- Behavior DropBehavior
- TypeNameList []*TypeNameDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/enum_type_def.go b/backend/plugin/parser/pg/legacy/ast/enum_type_def.go
deleted file mode 100644
index ce5777ec76..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/enum_type_def.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ast
-
-// EnumTypeDef is the struct for enum types.
-type EnumTypeDef struct {
- userDefinedType
-
- Name *TypeNameDef
- LabelList []string
-}
-
-// EquivalentType implements the DataType interface.
-func (e *EnumTypeDef) EquivalentType(tp string) bool {
- return tp == e.Name.Name
-}
-
-// TypeName implements the UserDefinedType interface.
-func (e EnumTypeDef) TypeName() *TypeNameDef {
- return e.Name
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/explain_stmt.go b/backend/plugin/parser/pg/legacy/ast/explain_stmt.go
deleted file mode 100644
index efe2e360fc..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/explain_stmt.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package ast
-
-// ExplainStmt is the struct for explain statement.
-type ExplainStmt struct {
- node
-
- // For PostgreSQL, the Statement can be SELECT, INSERT, UPDATE, DELETE, VALUES, EXECUTE, DECLARE, CREATE TABLE AS, or CREATE MATERIALIZED VIEW AS statement.
- // Here we only support SELECT now.
- // TODO(rebelice): support more.
- Statement Node
- Analyze bool
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/expression_def.go b/backend/plugin/parser/pg/legacy/ast/expression_def.go
deleted file mode 100644
index 1053385c9b..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/expression_def.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ast
-
-var (
- _ ExpressionNode = (*expression)(nil)
-)
-
-// ExpressionNode is the interface for expressions.
-type ExpressionNode interface {
- Node
-
- expressionNode()
-}
-
-// expression is the base struct for expression nodes.
-type expression struct {
- node
-}
-
-func (*expression) expressionNode() {}
diff --git a/backend/plugin/parser/pg/legacy/ast/float.go b/backend/plugin/parser/pg/legacy/ast/float.go
deleted file mode 100644
index 47f50070b6..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/float.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ast
-
-import "strings"
-
-// Float is the struct for floating-point.
-type Float struct {
- numericType
-
- // the storage size(bytes)
- Size int
-}
-
-// EquivalentType implements the DataType interface.
-func (f *Float) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- switch f.Size {
- case 4:
- return tp == "float4" || tp == "real"
- case 8:
- return tp == "float" || tp == "float8" || tp == "double precision"
- default:
- return false
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/foreign_def.go b/backend/plugin/parser/pg/legacy/ast/foreign_def.go
deleted file mode 100644
index 39d40e7033..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/foreign_def.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ast
-
-// ForeignMatchType is the match type for referencing columns and referenced columns.
-type ForeignMatchType int
-
-const (
- // ForeignMatchTypeSimple is the match type which allows any of the foreign key columns to be null.
- ForeignMatchTypeSimple ForeignMatchType = iota
- // ForeignMatchTypeFull is the match type which doesn't allow one column of a multi-column foreign key to be null unless all foreign key columns are null.
- ForeignMatchTypeFull
- // ForeignMatchTypePartial is not yet implemented.
- ForeignMatchTypePartial
-)
-
-// ForeignDef is struct for foreign key reference.
-type ForeignDef struct {
- node
-
- Table *TableDef
- ColumnList []string
- MatchType ForeignMatchType
- OnDelete *ReferentialActionDef
- OnUpdate *ReferentialActionDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/function_def.go b/backend/plugin/parser/pg/legacy/ast/function_def.go
deleted file mode 100644
index 9041a7f621..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/function_def.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package ast
-
-// FunctionParameterMode is the definition for function parameter mode.
-type FunctionParameterMode int
-
-const (
- // FunctionParameterModeUndefined is the undefined parameter mode.
- FunctionParameterModeUndefined FunctionParameterMode = iota
- // FunctionParameterModeIn is mode for the IN parameters. It's the default value.
- FunctionParameterModeIn
- // FunctionParameterModeOut is mode for the OUT parameters.
- FunctionParameterModeOut
- // FunctionParameterModeInOut is mode for the OUT parameters.
- FunctionParameterModeInOut
- // FunctionParameterModeVariadic is mode for the VARIADIC parameters.
- FunctionParameterModeVariadic
- // FunctionParameterModeTable is mode for the TABLE parameters.
- FunctionParameterModeTable
- // FunctionParameterModeDefault is mode for the DEFAULT parameters.
- FunctionParameterModeDefault
-)
-
-// FunctionParameterDef is the struct for function parameter definition.
-type FunctionParameterDef struct {
- Name string
- Type DataType
- Mode FunctionParameterMode
-}
-
-// FunctionDef is the struct for function definition.
-type FunctionDef struct {
- node
-
- Schema string
- Name string
- ParameterList []*FunctionParameterDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/index_def.go b/backend/plugin/parser/pg/legacy/ast/index_def.go
deleted file mode 100644
index d7d795c834..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/index_def.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package ast
-
-// IndexMethodType is the index method type.
-type IndexMethodType int
-
-const (
- // IndexMethodTypeBTree is the index method type for B-Tree. It's the default type.
- IndexMethodTypeBTree = iota
- // IndexMethodTypeHash is the index method type for hash.
- IndexMethodTypeHash
- // IndexMethodTypeGiST is the index method type for GiST.
- IndexMethodTypeGiST
- // IndexMethodTypeSpGiST is the index method type for SP-GiST.
- IndexMethodTypeSpGiST
- // IndexMethodTypeGin is the index method type for GIN.
- IndexMethodTypeGin
- // IndexMethodTypeBrin is the index method type for BRIN.
- IndexMethodTypeBrin
- // IndexMethodTypeIvfflat is the index method type for ivfflat.
- // https://github.com/bytebase/bytebase/issues/6783.
- // https://github.com/pgvector/pgvector.
- IndexMethodTypeIvfflat
-)
-
-// String implements fmt.Stringer interface.
-func (tp IndexMethodType) String() string {
- switch tp {
- case IndexMethodTypeBTree:
- return "btree"
- case IndexMethodTypeHash:
- return "hash"
- case IndexMethodTypeGiST:
- return "gist"
- case IndexMethodTypeSpGiST:
- return "spgist"
- case IndexMethodTypeGin:
- return "gin"
- case IndexMethodTypeBrin:
- return "brin"
- case IndexMethodTypeIvfflat:
- return "ivfflat"
- default:
- return ""
- }
-}
-
-// IndexDef is the struct for index definition.
-type IndexDef struct {
- node
-
- Name string
- Table *TableDef
- Unique bool
- KeyList []*IndexKeyDef
- Method IndexMethodType
-}
-
-// GetKeyNameList to get the name from KeyList.
-func (id IndexDef) GetKeyNameList() []string {
- nameList := []string{}
- for _, key := range id.KeyList {
- nameList = append(nameList, key.Key)
- }
- return nameList
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/index_key_def.go b/backend/plugin/parser/pg/legacy/ast/index_key_def.go
deleted file mode 100644
index c967e856a1..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/index_key_def.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package ast
-
-// SortOrderType is the sort order type for the index.
-type SortOrderType int
-
-const (
- // SortOrderTypeDefault is the sort order type for default value.
- SortOrderTypeDefault = iota
- // SortOrderTypeAscending is the sort order type for ASC.
- SortOrderTypeAscending
- // SortOrderTypeDescending is the sort order type for DESC.
- SortOrderTypeDescending
-)
-
-// NullOrderType is the null sort order type for the index.
-type NullOrderType int
-
-const (
- // NullOrderTypeDefault is the default null sort order type.
- NullOrderTypeDefault = iota
- // NullOrderTypeFirst is the null sort order type that nulls sort before non-nulls.
- // This is the default when DESC is specified.
- NullOrderTypeFirst
- // NullOrderTypeLast is the null sort order type that nulls sort after non-nulls.
- // This is the default when DESC is not specified.
- NullOrderTypeLast
-)
-
-// IndexKeyType is the type for index key.
-type IndexKeyType int
-
-const (
- // IndexKeyTypeColumn is the type for the column.
- IndexKeyTypeColumn IndexKeyType = iota
- // IndexKeyTypeExpression is the type for the expression.
- IndexKeyTypeExpression
-)
-
-// IndexKeyDef is the struct for index key definition.
-type IndexKeyDef struct {
- node
-
- Type IndexKeyType
- Key string
- SortOrder SortOrderType
- NullOrder NullOrderType
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/insert_stmt.go b/backend/plugin/parser/pg/legacy/ast/insert_stmt.go
deleted file mode 100644
index cecec77779..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/insert_stmt.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package ast
-
-// InsertStmt is the struct for insert statement.
-type InsertStmt struct {
- dml
-
- Table *TableDef
- ColumnList []string
- ValueList [][]ExpressionNode
- Select *SelectStmt
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/integer.go b/backend/plugin/parser/pg/legacy/ast/integer.go
deleted file mode 100644
index 19f268afc6..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/integer.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package ast
-
-import "strings"
-
-// Integer is the struct for integer.
-type Integer struct {
- numericType
-
- // the storage size(bytes)
- Size int
-}
-
-// EquivalentType implements the DataType interface.
-func (i *Integer) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- switch i.Size {
- case 2:
- return tp == "smallint" || tp == "int2"
- case 4:
- return tp == "int" || tp == "int4" || tp == "integer"
- case 8:
- return tp == "bigint" || tp == "int8"
- default:
- return false
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/integer_def.go b/backend/plugin/parser/pg/legacy/ast/integer_def.go
deleted file mode 100644
index 898c80844c..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/integer_def.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// IntegerDef is the struct for integer definition.
-type IntegerDef struct {
- expression
-
- Value int32
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/json.go b/backend/plugin/parser/pg/legacy/ast/json.go
deleted file mode 100644
index b15fe8e21a..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/json.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package ast
-
-import (
- "strings"
-)
-
-var (
- _ DataType = (*JSON)(nil)
-)
-
-// Text is the struct for the character.
-type JSON struct {
- dataType
- JSONB bool
-}
-
-// EquivalentType implements the DataType interface.
-func (j *JSON) EquivalentType(tp string) bool {
- if j.JSONB {
- return strings.EqualFold(tp, "jsonb")
- }
- return strings.EqualFold(tp, "json")
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/node.go b/backend/plugin/parser/pg/legacy/ast/node.go
deleted file mode 100644
index 74a9bfa659..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/node.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package ast
-
-import (
- pgquery "github.com/pganalyze/pg_query_go/v6"
-)
-
-var (
- _ Node = (*node)(nil)
-)
-
-// Node is the interface for node.
-type Node interface {
- Text() string
- SetText(text string)
- LastLine() int
- SetLastLine(line int)
-}
-
-// node is the base struct for all Node.
-type node struct {
- text string
- lastline int
- *pgquery.ParseResult
-}
-
-// Text implements the Node interface.
-func (n *node) Text() string {
- return n.text
-}
-
-// SetText implements the Node interface.
-func (n *node) SetText(text string) {
- n.text = text
-}
-
-func (n *node) LastLine() int {
- return n.lastline
-}
-
-func (n *node) SetLastLine(line int) {
- n.lastline = line
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/parition_key_def.go b/backend/plugin/parser/pg/legacy/ast/parition_key_def.go
deleted file mode 100644
index dd94c5d702..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/parition_key_def.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ast
-
-// PartitionKeyType is the type of partition key.
-type PartitionKeyType int
-
-const (
- // PartitionKeyTypeColumn is the type of partition key column.
- PartitionKeyTypeColumn PartitionKeyType = iota
- // PartitionKeyTypeExpression is the type of partition key expression.
- PartitionKeyTypeExpression
-)
-
-// PartitionKeyDef is the struct for partition key definition.
-type PartitionKeyDef struct {
- node
-
- Type PartitionKeyType
- Key string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/partition_def.go b/backend/plugin/parser/pg/legacy/ast/partition_def.go
deleted file mode 100644
index 832a6a3907..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/partition_def.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package ast
-
-import (
- pgquery "github.com/pganalyze/pg_query_go/v6"
-)
-
-// PartitionDef is the struct for partition specification.
-type PartitionDef struct {
- node
-
- Strategy pgquery.PartitionStrategy
- KeyList []*PartitionKeyDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/pattern_like_def.go b/backend/plugin/parser/pg/legacy/ast/pattern_like_def.go
deleted file mode 100644
index 9e1e0309ca..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/pattern_like_def.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// PatternLikeDef is the struct for LIKE expression definition, e.g. a LIKE '%abc'.
-type PatternLikeDef struct {
- expression
-
- Not bool
- Expression ExpressionNode
- Pattern ExpressionNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/referential_action_def.go b/backend/plugin/parser/pg/legacy/ast/referential_action_def.go
deleted file mode 100644
index e3b8afe0cc..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/referential_action_def.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package ast
-
-// ReferentialActionType is the type for referential action.
-type ReferentialActionType int
-
-const (
- // ReferentialActionTypeNoAction is the referential action type which will produce an error indicating that the deletion or update would create a foreign key constraint violation.
- // If the constraint is deferred, this error will be produced at constraint check time if there still exist any referencing rows. This is the default action.
- ReferentialActionTypeNoAction ReferentialActionType = iota
- // ReferentialActionTypeRestrict is the referential action type which will produce an error indicating that the deletion or update would create a foreign key constraint violation.
- // This is the same as NO ACTION except that the check is not deferrable.
- ReferentialActionTypeRestrict
- // ReferentialActionTypeCascade is the referential action type which will delete any rows referencing the deleted row, or update the values of the referencing column(s) to the new values of the referenced columns, respectively.
- ReferentialActionTypeCascade
- // ReferentialActionTypeSetNull is the referential action type which will set all of the referencing columns, or a specified subset of the referencing columns(pg 15), to null. A subset of columns can only be specified for ON DELETE actions.
- ReferentialActionTypeSetNull
- // ReferentialActionTypeSetDefault is the referential action type which will set all of the referencing columns, or a specified subset of the referencing columns(pg 15), to their default values.
- // A subset of columns can only be specified for ON DELETE actions.
- // There must be a row in the referenced table matching the default values, if they are not null, or the operation will fail.
- ReferentialActionTypeSetDefault
-)
-
-// ReferentialActionDef is the struct for referential actions.
-// See https://www.postgresql.org/docs/current/sql-createtable.html for more details.
-//
-// In the PostgreSQL 15, users can specify the subset of the referencing columns to set null or default.
-// This parser only support PostgreSQL 13 currently. But we also define the ReferentialAction as a struct instead of an int.
-// It's for supporting PostgreSQL 15 in the future.
-type ReferentialActionDef struct {
- node
-
- Type ReferentialActionType
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/rename_column_stmt.go b/backend/plugin/parser/pg/legacy/ast/rename_column_stmt.go
deleted file mode 100644
index b4644f1c40..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/rename_column_stmt.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package ast
-
-// RenameColumnStmt is the rename column statement.
-// For PostgreSQL dialect is the ALTER TABLE RENAME COLUMN.
-type RenameColumnStmt struct {
- node
-
- Table *TableDef
- ColumnName string
- NewName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/rename_constraint_stmt.go b/backend/plugin/parser/pg/legacy/ast/rename_constraint_stmt.go
deleted file mode 100644
index d05c250dfc..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/rename_constraint_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// RenameConstraintStmt is the struct for rename constraint statement.
-type RenameConstraintStmt struct {
- node
-
- Table *TableDef
- ConstraintName string
- NewName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/rename_index_stmt.go b/backend/plugin/parser/pg/legacy/ast/rename_index_stmt.go
deleted file mode 100644
index 25accec5d8..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/rename_index_stmt.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package ast
-
-// RenameIndexStmt is the struct for the rename index statement.
-type RenameIndexStmt struct {
- ddl
-
- // For PostgreSQL, we only use TableDef.Schema.
- // If this rename index statement doesn't contain schema name, Table will be not nil and the Schema name is empty string.
- Table *TableDef
- IndexName string
- NewName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/rename_schema_stmt.go b/backend/plugin/parser/pg/legacy/ast/rename_schema_stmt.go
deleted file mode 100644
index 87b11f6308..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/rename_schema_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// RenameSchemaStmt is the struct for the rename schema statement.
-type RenameSchemaStmt struct {
- ddl
-
- Schema string
- NewName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/rename_table_stmt.go b/backend/plugin/parser/pg/legacy/ast/rename_table_stmt.go
deleted file mode 100644
index 390bd83a22..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/rename_table_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// RenameTableStmt is the struct for rename table or view statement.
-// For PostgreSQL dialect is ALTER TABLE RENAME and ALTER VIEW RENAME.
-type RenameTableStmt struct {
- node
-
- Table *TableDef
- NewName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/role_spec.go b/backend/plugin/parser/pg/legacy/ast/role_spec.go
deleted file mode 100644
index 7d63718efd..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/role_spec.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ast
-
-// RoleSpecType is the type of a role specification.
-type RoleSpecType int
-
-const (
- // RoleSpecTypeNone is the default value for RoleSpecType.
- RoleSpecTypeNone RoleSpecType = iota
- // RoleSpecTypeUser is a user role.
- RoleSpecTypeUser
- // RoleSpecTypeCurrentRole is CURRENT_ROLE.
- RoleSpecTypeCurrentRole
- // RoleSpecTypeCurrentUser is CURRENT_USER.
- RoleSpecTypeCurrentUser
- // RoleSpecTypeSessionUser is SESSION_USER.
- RoleSpecTypeSessionUser
-)
-
-// RoleSpec is the struct for role specification.
-type RoleSpec struct {
- Type RoleSpecType
- // Value only used when Tp is RoleSpecTypeUser.
- Value string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/select_stmt.go b/backend/plugin/parser/pg/legacy/ast/select_stmt.go
deleted file mode 100644
index fe82cab1a8..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/select_stmt.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package ast
-
-import (
- pgquery "github.com/pganalyze/pg_query_go/v6"
-)
-
-// SetOperationType is the type for set operations.
-type SetOperationType int
-
-const (
- // SetOperationTypeNone is the type for no set operation, which means a SELECT stmt.
- SetOperationTypeNone SetOperationType = iota
- // SetOperationTypeUnion is the type for UNION.
- SetOperationTypeUnion
- // SetOperationTypeIntersect is the type for INTERSECT.
- SetOperationTypeIntersect
- // SetOperationTypeExcept is the type for EXCEPT.
- SetOperationTypeExcept
-)
-
-// SelectStmt is the struct for select statement.
-type SelectStmt struct {
- node
-
- // if SetOperation is SetOperationTypeNode:
- // LQuery and RQuery is nil and SELECT fields is useful
- // otherwise:
- // only use LQuery and RQuery
- SetOperation SetOperationType
- // LQuery and RQuery are used for set operation, such as UNION.
- // In this case, we define the SQL as:
- // LQuery UNION RQuery;
- // Easy to know, LQuery and RQuery are SELECT statement, also.
- // Details at https://www.postgresql.org/docs/current/sql-select.html
- LQuery *SelectStmt
- RQuery *SelectStmt
-
- // SELECT fields
- FieldList []ExpressionNode
- WhereClause ExpressionNode
- OrderByClause []*ByItemDef
- Limit *int32
-
- // TODO(rebelice): support all expression and remove them.
- // We define them because we cannot convert all expression now.
- // And we only need to check the following nodes currently.
- //
- // PatternLikeList is the list of the patternLike nodes.
- PatternLikeList []*PatternLikeDef
- // SubqueryList is the list of the subquery nodes.
- SubqueryList []*SubqueryDef
- // fromClause is the raw pgquery from clause nodes.
- fromClause []*pgquery.Node
-
- originalNode *pgquery.SelectStmt
-}
-
-func (ss *SelectStmt) SetOriginalNode(node *pgquery.SelectStmt) {
- ss.originalNode = node
-}
-
-func (ss *SelectStmt) GetOriginalNode() *pgquery.SelectStmt {
- return ss.originalNode
-}
-
-// SetFromClause sets the from clause for select statement.
-func (ss *SelectStmt) SetFromClause(fromClause []*pgquery.Node) {
- ss.fromClause = fromClause
-}
-
-// GetFromClause gets the from clause for select statement.
-func (ss *SelectStmt) GetFromClause() []*pgquery.Node {
- return ss.fromClause
-}
-
-// ByItemDef is the struct for item in order by or group by.
-type ByItemDef struct {
- node
-
- Expression ExpressionNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/sequence_def.go b/backend/plugin/parser/pg/legacy/ast/sequence_def.go
deleted file mode 100644
index 3fda19a9c2..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/sequence_def.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package ast
-
-// SequenceNameDef is the name of a sequence.
-type SequenceNameDef struct {
- node
-
- Schema string
- Name string
-}
-
-// SequenceDef is the struct for sequence definition.
-type SequenceDef struct {
- node
-
- SequenceName *SequenceNameDef
- SequenceDataType *Integer
- // No cycle is default
- Cycle bool
- StartWith *int64
- IncrementBy *int64
- MinValue *int64
- MaxValue *int64
- Cache *int64
- OwnedBy *ColumnNameDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/serial.go b/backend/plugin/parser/pg/legacy/ast/serial.go
deleted file mode 100644
index 8b6b49c8c2..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/serial.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package ast
-
-import "strings"
-
-// Serial is the struct for serial.
-type Serial struct {
- numericType
-
- // the storage size(bytes)
- Size int
-}
-
-// EquivalentType implements the DataType interface.
-func (s *Serial) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- switch s.Size {
- case 2:
- return tp == "smallserial" || tp == "serial2"
- case 4:
- return tp == "serial" || tp == "serial4"
- case 8:
- return tp == "bigserial" || tp == "serial8"
- default:
- return false
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/set_default_stmt.go b/backend/plugin/parser/pg/legacy/ast/set_default_stmt.go
deleted file mode 100644
index 16c5209a33..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/set_default_stmt.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package ast
-
-// SetDefaultStmt is the struct for set default statement.
-type SetDefaultStmt struct {
- node
-
- Table *TableDef
- ColumnName string
- Expression ExpressionNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/set_not_null_stmt.go b/backend/plugin/parser/pg/legacy/ast/set_not_null_stmt.go
deleted file mode 100644
index 8ed563960e..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/set_not_null_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// SetNotNullStmt is the struct for set not null statement.
-type SetNotNullStmt struct {
- node
-
- Table *TableDef
- ColumnName string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/set_schema_stmt.go b/backend/plugin/parser/pg/legacy/ast/set_schema_stmt.go
deleted file mode 100644
index d3634b2515..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/set_schema_stmt.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// SetSchemaStmt is the struct for set schema statement.
-type SetSchemaStmt struct {
- node
-
- Table *TableDef
- NewSchema string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/string_def.go b/backend/plugin/parser/pg/legacy/ast/string_def.go
deleted file mode 100644
index 56734ebf21..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/string_def.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// StringDef is the struct for string definition.
-type StringDef struct {
- expression
-
- Value string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/subquery_def.go b/backend/plugin/parser/pg/legacy/ast/subquery_def.go
deleted file mode 100644
index 14eaf59ebb..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/subquery_def.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// SubqueryDef is the struct for subquery definition.
-type SubqueryDef struct {
- expression
-
- Select *SelectStmt
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/table_def.go b/backend/plugin/parser/pg/legacy/ast/table_def.go
deleted file mode 100644
index 5f2651e777..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/table_def.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package ast
-
-// TableType is the type for table.
-type TableType int
-
-const (
- // TableTypeUnknown is the type for table or view, which means we can't be sure of it.
- TableTypeUnknown TableType = iota
- // TableTypeBaseTable is the type for table.
- TableTypeBaseTable
- // TableTypeView is the type for view.
- TableTypeView
- // TableTypeMaterializedView is the type for materialized view.
- TableTypeMaterializedView
-)
-
-// TableDef is the strcut for table.
-type TableDef struct {
- node
-
- // Type is the table type for table: base table or view.
- Type TableType
- // Database is the name of database.
- // It's also called "catalog" in PostgreSQL.
- Database string
- // Schema is a PostgreSQL specific field.
- // See https://www.postgresql.org/docs/current/ddl-schemas.html.
- Schema string
- // Name is the name of the table.
- Name string
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/text.go b/backend/plugin/parser/pg/legacy/ast/text.go
deleted file mode 100644
index 5eeac50465..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/text.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package ast
-
-import (
- "strings"
-)
-
-var (
- _ DataType = (*Text)(nil)
-)
-
-// Text is the struct for the character.
-type Text struct {
- characterType
-}
-
-// EquivalentType implements the DataType interface.
-func (*Text) EquivalentType(tp string) bool {
- tp = strings.ToLower(tp)
- return tp == "text"
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/trigger_def.go b/backend/plugin/parser/pg/legacy/ast/trigger_def.go
deleted file mode 100644
index 77539a36ee..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/trigger_def.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ast
-
-// TriggerDef is the definition of trigger.
-type TriggerDef struct {
- node
-
- Name string
- Table *TableDef
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/unconverted_data_type.go b/backend/plugin/parser/pg/legacy/ast/unconverted_data_type.go
deleted file mode 100644
index 81eee2ba8f..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/unconverted_data_type.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package ast
-
-// UnconvertedDataType is the struct for unconverted data type.
-// TODO(rebelice): remove it.
-// We define this because we cannot convert all data types now.
-type UnconvertedDataType struct {
- dataType
-
- Name []string
-}
-
-// EquivalentType implements the DataType interface.
-func (u *UnconvertedDataType) EquivalentType(tp string) bool {
- return u.Text() == tp
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/unconverted_expression_def.go b/backend/plugin/parser/pg/legacy/ast/unconverted_expression_def.go
deleted file mode 100644
index 1f5b4a326e..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/unconverted_expression_def.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// UnconvertedExpressionDef is the struct for unconveted expression definition.
-// TODO(rebelice): remove it.
-// We define this because we cannot convert all expression types now.
-type UnconvertedExpressionDef struct {
- expression
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/unconverted_stmt.go b/backend/plugin/parser/pg/legacy/ast/unconverted_stmt.go
deleted file mode 100644
index 690b27af02..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/unconverted_stmt.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package ast
-
-// UnconvertedStmt is the struct for unconverted statement definition.
-// TODO(rebelice): remove it.
-// We define this because we cannot convert all statement types now.
-type UnconvertedStmt struct {
- node
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/update_stmt.go b/backend/plugin/parser/pg/legacy/ast/update_stmt.go
deleted file mode 100644
index 75f723c7dd..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/update_stmt.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package ast
-
-import pgquery "github.com/pganalyze/pg_query_go/v6"
-
-// UpdateStmt is the struct for update statement.
-type UpdateStmt struct {
- dml
-
- Table *TableDef
- WhereClause ExpressionNode
-
- // TODO(rebelice): support all expression and remove them.
- // We define them because we cannot convert all expression now.
- // And we only need to check the following nodes currently.
- //
- // PatternLikeList is the list of the patternLike nodes.
- PatternLikeList []*PatternLikeDef
- // SubqueryList is the list of the subquery nodes.
- SubqueryList []*SubqueryDef
-
- originalNode *pgquery.Node_UpdateStmt
-}
-
-func (us *UpdateStmt) SetOriginalNode(node *pgquery.Node_UpdateStmt) {
- us.originalNode = node
-}
-
-func (us *UpdateStmt) GetOriginalNode() *pgquery.Node_UpdateStmt {
- return us.originalNode
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/utils.go b/backend/plugin/parser/pg/legacy/ast/utils.go
deleted file mode 100644
index 12639660b0..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/utils.go
+++ /dev/null
@@ -1,212 +0,0 @@
-package ast
-
-// Visitor is the interface for visitor pattern.
-type Visitor interface {
- Visit(Node) Visitor
-}
-
-// Walk walks the AST.
-func Walk(v Visitor, node Node) {
- if v = v.Visit(node); v == nil {
- return
- }
-
- switch n := node.(type) {
- case *AddColumnListStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- for _, col := range n.ColumnList {
- Walk(v, col)
- }
- case *AddConstraintStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- if n.Constraint != nil {
- Walk(v, n.Constraint)
- }
- case *AlterTableStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- for _, cmd := range n.AlterItemList {
- Walk(v, cmd)
- }
- case *ChangeColumnStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- if n.Column != nil {
- Walk(v, n.Column)
- }
- case *ColumnDef:
- if n.Type != nil {
- Walk(v, n.Type)
- }
- for _, cons := range n.ConstraintList {
- Walk(v, cons)
- }
- case *ColumnNameDef:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *ConstraintDef:
- if n.Foreign != nil {
- Walk(v, n.Foreign)
- }
- case *CopyStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *CreateIndexStmt:
- if n.Index != nil {
- Walk(v, n.Index)
- }
- case *CreateTableStmt:
- if n.Name != nil {
- Walk(v, n.Name)
- }
- for _, col := range n.ColumnList {
- Walk(v, col)
- }
- for _, cons := range n.ConstraintList {
- Walk(v, cons)
- }
- case *DeleteStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- if n.WhereClause != nil {
- Walk(v, n.WhereClause)
- }
-
- for _, like := range n.PatternLikeList {
- Walk(v, like)
- }
- for _, subquery := range n.SubqueryList {
- Walk(v, subquery)
- }
- case *DropColumnStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *DropConstraintStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *DropDatabaseStmt:
- // No members to walk through.
- case *DropIndexStmt:
- for _, indexDef := range n.IndexList {
- Walk(v, indexDef)
- }
- case *DropNotNullStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *DropTableStmt:
- for _, tableDef := range n.TableList {
- Walk(v, tableDef)
- }
- case *ExplainStmt:
- if n.Statement != nil {
- Walk(v, n.Statement)
- }
- case *ForeignDef:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *IndexDef:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- for _, keyDef := range n.KeyList {
- Walk(v, keyDef)
- }
- case *IndexKeyDef:
- // No members to walk through.
- case *InsertStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- if n.Select != nil {
- Walk(v, n.Select)
- }
- case *PatternLikeDef:
- if n.Expression != nil {
- Walk(v, n.Expression)
- }
- if n.Pattern != nil {
- Walk(v, n.Pattern)
- }
- case *RenameColumnStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *RenameConstraintStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *RenameIndexStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *RenameTableStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *SelectStmt:
- if n.LQuery != nil {
- Walk(v, n.LQuery)
- }
- if n.RQuery != nil {
- Walk(v, n.RQuery)
- }
- for _, field := range n.FieldList {
- Walk(v, field)
- }
- if n.WhereClause != nil {
- Walk(v, n.WhereClause)
- }
-
- for _, like := range n.PatternLikeList {
- Walk(v, like)
- }
- for _, subquery := range n.SubqueryList {
- Walk(v, subquery)
- }
- case *SetNotNullStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *SetSchemaStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- case *StringDef:
- // No members to walk through.
- case *SubqueryDef:
- if n.Select != nil {
- Walk(v, n.Select)
- }
- case *TableDef:
- // No members to walk through.
- case *UnconvertedExpressionDef:
- // No members to walk through.
- case *UpdateStmt:
- if n.Table != nil {
- Walk(v, n.Table)
- }
- if n.WhereClause != nil {
- Walk(v, n.WhereClause)
- }
-
- for _, like := range n.PatternLikeList {
- Walk(v, like)
- }
- for _, subquery := range n.SubqueryList {
- Walk(v, subquery)
- }
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/variable_set_stmt.go b/backend/plugin/parser/pg/legacy/ast/variable_set_stmt.go
deleted file mode 100644
index 1908743705..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/variable_set_stmt.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package ast
-
-type VariableSetStmt struct {
- node
-
- Name string
- Args []ExpressionNode
- IsLocal bool
-}
-
-func (s *VariableSetStmt) GetRoleName() string {
- if len(s.Args) != 1 {
- return ""
- }
-
- if v, ok := s.Args[0].(*StringDef); ok {
- return v.Value
- }
-
- return ""
-}
diff --git a/backend/plugin/parser/pg/legacy/ast/variable_show_stmt.go b/backend/plugin/parser/pg/legacy/ast/variable_show_stmt.go
deleted file mode 100644
index 99f6d51110..0000000000
--- a/backend/plugin/parser/pg/legacy/ast/variable_show_stmt.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package ast
-
-type VariableShowStmt struct {
- node
-
- Name string
-}
diff --git a/backend/plugin/parser/pg/legacy/convert.go b/backend/plugin/parser/pg/legacy/convert.go
deleted file mode 100644
index c1967c2fe5..0000000000
--- a/backend/plugin/parser/pg/legacy/convert.go
+++ /dev/null
@@ -1,2064 +0,0 @@
-package legacy
-
-import (
- "fmt"
- "strconv"
- "strings"
-
- pgquery "github.com/pganalyze/pg_query_go/v6"
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- "github.com/bytebase/bytebase/backend/plugin/parser/tokenizer"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-)
-
-// convert converts the pg_query.Node to ast.Node.
-func convert(node *pgquery.Node, statement base.SingleSQL) (res ast.Node, err error) {
- defer func() {
- if err == nil && res != nil {
- res.SetText(strings.TrimSpace(statement.Text))
- res.SetLastLine(int(statement.End.Line))
- switch n := res.(type) {
- case *ast.CreateTableStmt:
- err = setLineForCreateTableStmt(n)
- case *ast.AlterTableStmt:
- for _, item := range n.AlterItemList {
- item.SetLastLine(n.LastLine())
- }
- }
- }
- }()
- switch in := node.Node.(type) {
- case *pgquery.Node_AlterTableStmt:
- if in.AlterTableStmt.Objtype != pgquery.ObjectType_OBJECT_TABLE {
- // We only support ALTER TABLE.
- return nil, nil
- }
- alterTable := &ast.AlterTableStmt{
- Table: convertRangeVarToTableName(in.AlterTableStmt.Relation, ast.TableTypeBaseTable),
- AlterItemList: []ast.Node{},
- }
- for _, cmd := range in.AlterTableStmt.Cmds {
- if cmdNode, ok := cmd.Node.(*pgquery.Node_AlterTableCmd); ok {
- alterCmd := cmdNode.AlterTableCmd
-
- switch alterCmd.Subtype {
- case pgquery.AlterTableType_AT_AddColumn:
- def, ok := alterCmd.Def.Node.(*pgquery.Node_ColumnDef)
- if !ok {
- return nil, NewConvertErrorf("expected ColumnDef but found %t", alterCmd.Def.Node)
- }
-
- column, err := convertColumnDef(def)
- if err != nil {
- return nil, err
- }
-
- addColumn := &ast.AddColumnListStmt{
- Table: alterTable.Table,
- ColumnList: []*ast.ColumnDef{column},
- IfNotExists: alterCmd.MissingOk,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, addColumn)
- case pgquery.AlterTableType_AT_DropColumn:
- dropColumn := &ast.DropColumnStmt{
- Table: alterTable.Table,
- ColumnName: alterCmd.Name,
- IfExists: alterCmd.MissingOk,
- Behavior: convertDropBehavior(alterCmd.Behavior),
- }
- alterTable.AlterItemList = append(alterTable.AlterItemList, dropColumn)
- case pgquery.AlterTableType_AT_AddConstraint:
- def, ok := alterCmd.Def.Node.(*pgquery.Node_Constraint)
- if !ok {
- return nil, NewConvertErrorf("expected Constraint but found %t", alterCmd.Def.Node)
- }
- constraint, err := convertConstraint(def)
- if err != nil {
- return nil, err
- }
-
- addConstraint := &ast.AddConstraintStmt{
- Table: alterTable.Table,
- Constraint: constraint,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, addConstraint)
- case pgquery.AlterTableType_AT_DropConstraint:
- dropConstraint := &ast.DropConstraintStmt{
- Table: alterTable.Table,
- ConstraintName: alterCmd.Name,
- IfExists: alterCmd.MissingOk,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, dropConstraint)
- case pgquery.AlterTableType_AT_SetNotNull:
- setNotNull := &ast.SetNotNullStmt{
- Table: alterTable.Table,
- ColumnName: alterCmd.Name,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, setNotNull)
- case pgquery.AlterTableType_AT_DropNotNull:
- dropNotNull := &ast.DropNotNullStmt{
- Table: alterTable.Table,
- ColumnName: alterCmd.Name,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, dropNotNull)
- case pgquery.AlterTableType_AT_AlterColumnType:
- column, ok := alterCmd.Def.Node.(*pgquery.Node_ColumnDef)
- if !ok {
- return nil, NewConvertErrorf("expected ColumnDef but found %t", alterCmd.Def.Node)
- }
- dataType, err := convertDataType(column.ColumnDef.TypeName)
- if err != nil {
- return nil, err
- }
- collation := (*ast.CollationNameDef)(nil)
- if column.ColumnDef.CollClause != nil {
- collation, err = convertCollationName(column.ColumnDef.CollClause)
- if err != nil {
- return nil, err
- }
- }
- alterColumType := &ast.AlterColumnTypeStmt{
- Table: alterTable.Table,
- ColumnName: alterCmd.Name,
- Type: dataType,
- Collation: collation,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, alterColumType)
- case pgquery.AlterTableType_AT_ColumnDefault:
- if alterCmd.Def == nil {
- dropDefault := &ast.DropDefaultStmt{
- Table: alterTable.Table,
- ColumnName: alterCmd.Name,
- }
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, dropDefault)
- } else {
- var err error
- setDefault := &ast.SetDefaultStmt{
- Table: alterTable.Table,
- ColumnName: alterCmd.Name,
- }
- if setDefault.Expression, _, _, err = convertExpressionNode(alterCmd.Def); err != nil {
- return nil, err
- }
- text, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, alterCmd.Def)
- if err != nil {
- return nil, err
- }
- setDefault.Expression.SetText(text)
-
- alterTable.AlterItemList = append(alterTable.AlterItemList, setDefault)
- }
- case pgquery.AlterTableType_AT_AttachPartition:
- attachPartition := &ast.AttachPartitionStmt{
- Table: alterTable.Table,
- }
- if alterCmd.Def != nil {
- if partitionCmd, ok := alterCmd.Def.Node.(*pgquery.Node_PartitionCmd); ok {
- attachPartition.Partition = convertRangeVarToTableName(partitionCmd.PartitionCmd.Name, ast.TableTypeBaseTable)
- }
- }
- alterTable.AlterItemList = append(alterTable.AlterItemList, attachPartition)
- default:
- // Ignore unsupported alter table commands
- }
- }
- }
- return alterTable, nil
- case *pgquery.Node_CreateStmt:
- return convertCreateStmt(in.CreateStmt)
- case *pgquery.Node_RenameStmt:
- switch in.RenameStmt.RenameType {
- case pgquery.ObjectType_OBJECT_COLUMN:
- tableType, err := convertToTableType(in.RenameStmt.RelationType)
- if err != nil {
- return nil, err
- }
- table := convertRangeVarToTableName(in.RenameStmt.Relation, tableType)
- return &ast.AlterTableStmt{
- Table: table,
- AlterItemList: []ast.Node{
- &ast.RenameColumnStmt{
- Table: table,
- ColumnName: in.RenameStmt.Subname,
- NewName: in.RenameStmt.Newname,
- },
- },
- }, nil
- case pgquery.ObjectType_OBJECT_TABLE:
- table := convertRangeVarToTableName(in.RenameStmt.Relation, ast.TableTypeBaseTable)
- return &ast.AlterTableStmt{
- Table: table,
- AlterItemList: []ast.Node{
- &ast.RenameTableStmt{
- Table: table,
- NewName: in.RenameStmt.Newname,
- },
- },
- }, nil
- case pgquery.ObjectType_OBJECT_TABCONSTRAINT:
- table := convertRangeVarToTableName(in.RenameStmt.Relation, ast.TableTypeBaseTable)
- return &ast.AlterTableStmt{
- Table: table,
- AlterItemList: []ast.Node{
- &ast.RenameConstraintStmt{
- Table: table,
- ConstraintName: in.RenameStmt.Subname,
- NewName: in.RenameStmt.Newname,
- },
- },
- }, nil
- case pgquery.ObjectType_OBJECT_VIEW:
- view := convertRangeVarToTableName(in.RenameStmt.Relation, ast.TableTypeView)
- return &ast.AlterTableStmt{
- Table: view,
- AlterItemList: []ast.Node{
- &ast.RenameTableStmt{
- Table: view,
- NewName: in.RenameStmt.Newname,
- },
- },
- }, nil
- case pgquery.ObjectType_OBJECT_INDEX:
- return &ast.RenameIndexStmt{
- Table: convertRangeVarToIndexTableName(in.RenameStmt.Relation, ast.TableTypeUnknown),
- IndexName: in.RenameStmt.Relation.Relname,
- NewName: in.RenameStmt.Newname,
- }, nil
- case pgquery.ObjectType_OBJECT_SCHEMA:
- return &ast.RenameSchemaStmt{
- Schema: in.RenameStmt.Subname,
- NewName: in.RenameStmt.Newname,
- }, nil
- default:
- }
- case *pgquery.Node_IndexStmt:
- indexDef := &ast.IndexDef{
- Table: convertRangeVarToTableName(in.IndexStmt.Relation, ast.TableTypeUnknown),
- Name: in.IndexStmt.Idxname,
- Unique: in.IndexStmt.Unique,
- }
-
- method := convertMethodType(in.IndexStmt.AccessMethod)
- indexDef.Method = method
-
- for _, key := range in.IndexStmt.IndexParams {
- index, ok := key.Node.(*pgquery.Node_IndexElem)
- if !ok {
- return nil, NewConvertErrorf("expected IndexElem but found %t", key.Node)
- }
- indexKey := &ast.IndexKeyDef{}
- if index.IndexElem.Name != "" {
- indexKey.Type = ast.IndexKeyTypeColumn
- indexKey.Key = index.IndexElem.Name
- } else {
- expression, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, index.IndexElem.Expr)
- if err != nil {
- return nil, err
- }
- indexKey.Type = ast.IndexKeyTypeExpression
- indexKey.Key = expression
- }
-
- order, err := convertSortOrder(index.IndexElem.Ordering)
- if err != nil {
- return nil, err
- }
- indexKey.SortOrder = order
-
- nullOrder, err := convertNullOrder(index.IndexElem.NullsOrdering)
- if err != nil {
- return nil, err
- }
- indexKey.NullOrder = nullOrder
-
- indexDef.KeyList = append(indexDef.KeyList, indexKey)
- }
-
- return &ast.CreateIndexStmt{Index: indexDef, IfNotExists: in.IndexStmt.IfNotExists, Concurrently: in.IndexStmt.Concurrent}, nil
- case *pgquery.Node_DropStmt:
- switch in.DropStmt.RemoveType {
- case pgquery.ObjectType_OBJECT_INDEX:
- dropIndex := &ast.DropIndexStmt{
- IfExists: in.DropStmt.MissingOk,
- Concurrently: in.DropStmt.Concurrent,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, object := range in.DropStmt.Objects {
- list, ok := object.Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected List but found %t", object.Node)
- }
- indexDef, err := convertListToIndexDef(list, ast.TableTypeUnknown)
- if err != nil {
- return nil, err
- }
- dropIndex.IndexList = append(dropIndex.IndexList, indexDef)
- }
- return dropIndex, nil
- case pgquery.ObjectType_OBJECT_TABLE:
- dropTable := &ast.DropTableStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, object := range in.DropStmt.Objects {
- list, ok := object.Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected List but found %t", object.Node)
- }
- tableDef, err := convertListToTableDef(list, ast.TableTypeBaseTable)
- if err != nil {
- return nil, err
- }
- dropTable.TableList = append(dropTable.TableList, tableDef)
- }
- return dropTable, nil
- case pgquery.ObjectType_OBJECT_VIEW:
- dropView := &ast.DropTableStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, object := range in.DropStmt.Objects {
- list, ok := object.Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected List but found %t", object.Node)
- }
- viewDef, err := convertListToTableDef(list, ast.TableTypeView)
- if err != nil {
- return nil, err
- }
- dropView.TableList = append(dropView.TableList, viewDef)
- }
- return dropView, nil
- case pgquery.ObjectType_OBJECT_SCHEMA:
- dropSchema := &ast.DropSchemaStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, object := range in.DropStmt.Objects {
- strNode, ok := object.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", object.Node)
- }
- dropSchema.SchemaList = append(dropSchema.SchemaList, strNode.String_.Sval)
- }
- return dropSchema, nil
- case pgquery.ObjectType_OBJECT_SEQUENCE:
- dropSequence := &ast.DropSequenceStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, sequence := range in.DropStmt.Objects {
- list, ok := sequence.Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected List but found %t", sequence.Node)
- }
- sequenceDef, err := convertListToSequenceNameDef(list)
- if err != nil {
- return nil, err
- }
- dropSequence.SequenceNameList = append(dropSequence.SequenceNameList, sequenceDef)
- }
- return dropSequence, nil
- case pgquery.ObjectType_OBJECT_EXTENSION:
- dropExtension := &ast.DropExtensionStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, extension := range in.DropStmt.Objects {
- extensionName, ok := extension.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", extension.Node)
- }
- dropExtension.NameList = append(dropExtension.NameList, extensionName.String_.Sval)
- }
- return dropExtension, nil
- case pgquery.ObjectType_OBJECT_FUNCTION:
- dropFunctionStmt := &ast.DropFunctionStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
- for _, function := range in.DropStmt.Objects {
- functionNode, ok := function.Node.(*pgquery.Node_ObjectWithArgs)
- if !ok {
- return nil, NewConvertErrorf("expected ObjectWithArgs but found %t", function.Node)
- }
- functionDef := &ast.FunctionDef{}
- var err error
- functionDef.Schema, functionDef.Name, err = convertObjectName(functionNode.ObjectWithArgs.Objname)
- if err != nil {
- return nil, err
- }
- functionDef.ParameterList, err = convertFunctionParameterList(functionNode.ObjectWithArgs.Objargs)
- if err != nil {
- return nil, err
- }
-
- dropFunctionStmt.FunctionList = append(dropFunctionStmt.FunctionList, functionDef)
- }
-
- return dropFunctionStmt, nil
- case pgquery.ObjectType_OBJECT_TRIGGER:
- dropTriggerStmt := &ast.DropTriggerStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
-
- if len(in.DropStmt.Objects) != 1 {
- return nil, NewConvertErrorf("expected one trigger but found %d", len(in.DropStmt.Objects))
- }
- listNode, ok := in.DropStmt.Objects[0].Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected List but found %d", in.DropStmt.Objects[0].Node)
- }
-
- list, err := convertListToStringList(listNode)
- if err != nil {
- return nil, err
- }
- switch len(list) {
- case 3:
- dropTriggerStmt.Trigger = &ast.TriggerDef{
- Name: list[2],
- Table: &ast.TableDef{
- Type: ast.TableTypeUnknown,
- Schema: list[0],
- Name: list[1],
- },
- }
- case 2:
- dropTriggerStmt.Trigger = &ast.TriggerDef{
- Name: list[1],
- Table: &ast.TableDef{
- Type: ast.TableTypeUnknown,
- Schema: "",
- Name: list[0],
- },
- }
- default:
- return nil, NewConvertErrorf("expected one or two but found %d", len(list))
- }
-
- return dropTriggerStmt, nil
- case pgquery.ObjectType_OBJECT_TYPE:
- dropTypeStmt := &ast.DropTypeStmt{
- IfExists: in.DropStmt.MissingOk,
- Behavior: convertDropBehavior(in.DropStmt.Behavior),
- }
-
- for _, object := range in.DropStmt.Objects {
- typeName, ok := object.Node.(*pgquery.Node_TypeName)
- if !ok {
- return nil, NewConvertErrorf("expected TypeName but found %t", object.Node)
- }
- schema, name, err := convertObjectName(typeName.TypeName.Names)
- if err != nil {
- return nil, err
- }
- dropTypeStmt.TypeNameList = append(dropTypeStmt.TypeNameList, &ast.TypeNameDef{
- Schema: schema,
- Name: name,
- })
- }
-
- return dropTypeStmt, nil
- default:
- }
- case *pgquery.Node_DropdbStmt:
- return &ast.DropDatabaseStmt{
- DatabaseName: in.DropdbStmt.Dbname,
- IfExists: in.DropdbStmt.MissingOk,
- }, nil
- case *pgquery.Node_SelectStmt:
- return convertSelectStmt(in.SelectStmt)
- case *pgquery.Node_UpdateStmt:
- update := &ast.UpdateStmt{
- Table: convertRangeVarToTableName(in.UpdateStmt.Relation, ast.TableTypeBaseTable),
- }
- // Convert FROM clause
- // Here we only find the SELECT stmt in FROM clause
- for _, item := range in.UpdateStmt.FromClause {
- if node, ok := item.Node.(*pgquery.Node_RangeSubselect); ok {
- subselect, err := convertRangeSubselect(node.RangeSubselect)
- if err != nil {
- return nil, err
- }
- update.SubqueryList = append(update.SubqueryList, subselect)
- }
- }
- // Convert WHERE clause
- if in.UpdateStmt.WhereClause != nil {
- var err error
- var subqueryList []*ast.SubqueryDef
- update.WhereClause, update.PatternLikeList, subqueryList, err = convertExpressionNode(in.UpdateStmt.WhereClause)
- if err != nil {
- return nil, err
- }
- update.SubqueryList = append(update.SubqueryList, subqueryList...)
- }
- update.SetOriginalNode(in)
- return update, nil
- case *pgquery.Node_DeleteStmt:
- deleteStmt := &ast.DeleteStmt{
- Table: convertRangeVarToTableName(in.DeleteStmt.Relation, ast.TableTypeBaseTable),
- }
- if in.DeleteStmt.WhereClause != nil {
- var err error
- if deleteStmt.WhereClause, deleteStmt.PatternLikeList, deleteStmt.SubqueryList, err = convertExpressionNode(in.DeleteStmt.WhereClause); err != nil {
- return nil, err
- }
- }
- return deleteStmt, nil
- case *pgquery.Node_CreateSeqStmt:
- createSeqStmt := &ast.CreateSequenceStmt{
- IfNotExists: in.CreateSeqStmt.IfNotExists,
- }
- if in.CreateSeqStmt.Sequence == nil {
- // Unexpected case.
- return nil, NewConvertErrorf("CreateSeqStmt.Sequence is nil")
- }
- createSeqStmt.SequenceDef.SequenceName = convertRangeVarToSeqName(in.CreateSeqStmt.Sequence)
- for _, option := range in.CreateSeqStmt.Options {
- defElemNode, ok := option.Node.(*pgquery.Node_DefElem)
- if !ok {
- return nil, NewConvertErrorf("expected DefElem but found %t", option.Node)
- }
- switch defElemNode.DefElem.Defname {
- case "as":
- if createSeqStmt.SequenceDef.SequenceDataType, err = convertDefElemToSeqType(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "increment":
- if createSeqStmt.SequenceDef.IncrementBy, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "start":
- if createSeqStmt.SequenceDef.StartWith, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "minvalue":
- if createSeqStmt.SequenceDef.MinValue, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "maxvalue":
- if createSeqStmt.SequenceDef.MaxValue, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "cache":
- if createSeqStmt.SequenceDef.Cache, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "cycle":
- if createSeqStmt.SequenceDef.Cycle, err = convertDefElemNodeIntegerToBool(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "owned_by":
- if createSeqStmt.SequenceDef.OwnedBy, err = convertDefElemNodeListToColumnNameDef(defElemNode.DefElem); err != nil {
- return nil, err
- }
- default:
- return nil, NewConvertErrorf("unsupported option %s", defElemNode.DefElem.Defname)
- }
- }
- return createSeqStmt, nil
- case *pgquery.Node_AlterSeqStmt:
- return convertAlterSequence(in.AlterSeqStmt)
- case *pgquery.Node_AlterObjectSchemaStmt:
- switch in.AlterObjectSchemaStmt.ObjectType {
- case pgquery.ObjectType_OBJECT_TABLE:
- table := convertRangeVarToTableName(in.AlterObjectSchemaStmt.Relation, ast.TableTypeBaseTable)
- return &ast.AlterTableStmt{
- Table: table,
- AlterItemList: []ast.Node{
- &ast.SetSchemaStmt{
- Table: table,
- NewSchema: in.AlterObjectSchemaStmt.Newschema,
- },
- },
- }, nil
- case pgquery.ObjectType_OBJECT_VIEW:
- view := convertRangeVarToTableName(in.AlterObjectSchemaStmt.Relation, ast.TableTypeView)
- return &ast.AlterTableStmt{
- Table: view,
- AlterItemList: []ast.Node{
- &ast.SetSchemaStmt{
- Table: view,
- NewSchema: in.AlterObjectSchemaStmt.Newschema,
- },
- },
- }, nil
- default:
- return nil, NewConvertErrorf("unexpected object type: %q", in.AlterObjectSchemaStmt.ObjectType.String())
- }
- case *pgquery.Node_ExplainStmt:
- explainStmt := &ast.ExplainStmt{}
- if query, ok := in.ExplainStmt.Query.Node.(*pgquery.Node_SelectStmt); ok {
- if explainStmt.Statement, err = convertSelectStmt(query.SelectStmt); err != nil {
- return nil, err
- }
- }
- for _, option := range in.ExplainStmt.Options {
- switch option := option.Node.(type) {
- case *pgquery.Node_DefElem:
- if option.DefElem.Defname == "analyze" {
- explainStmt.Analyze = true
- }
- default:
- }
- }
- return explainStmt, nil
- case *pgquery.Node_InsertStmt:
- insertStmt := &ast.InsertStmt{
- Table: convertRangeVarToTableName(in.InsertStmt.Relation, ast.TableTypeBaseTable),
- }
-
- for _, columnNode := range in.InsertStmt.Cols {
- if column, ok := columnNode.Node.(*pgquery.Node_ResTarget); ok {
- insertStmt.ColumnList = append(insertStmt.ColumnList, column.ResTarget.Name)
- } else {
- return nil, NewConvertErrorf("expected ResTarget but found %t", columnNode.Node)
- }
- }
-
- if in.InsertStmt.SelectStmt != nil {
- if selectNode, ok := in.InsertStmt.SelectStmt.Node.(*pgquery.Node_SelectStmt); ok {
- // PG parser will parse the value list as a SELECT statement.
- if selectNode.SelectStmt.ValuesLists == nil {
- if insertStmt.Select, err = convertSelectStmt(selectNode.SelectStmt); err != nil {
- return nil, err
- }
- } else {
- for _, list := range selectNode.SelectStmt.ValuesLists {
- var valueList []ast.ExpressionNode
- listNode, ok := list.Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected Node_List but found %t", list.Node)
- }
- for _, item := range listNode.List.Items {
- value, _, _, err := convertExpressionNode(item)
- if err != nil {
- return nil, err
- }
- valueList = append(valueList, value)
- }
- insertStmt.ValueList = append(insertStmt.ValueList, valueList)
- }
- }
- } else {
- return nil, NewConvertErrorf("expected SelectStmt but found %t", in.InsertStmt.SelectStmt.Node)
- }
- }
- return insertStmt, nil
- case *pgquery.Node_CopyStmt:
- copyStmt := ast.CopyStmt{
- Table: convertRangeVarToTableName(in.CopyStmt.Relation, ast.TableTypeBaseTable),
- FilePath: in.CopyStmt.Filename,
- }
-
- return &copyStmt, nil
- case *pgquery.Node_CommentStmt:
- commentStmt := ast.CommentStmt{
- // unescape single quote
- Comment: strings.ReplaceAll(in.CommentStmt.Comment, "''", "'"),
- }
-
- switch in.CommentStmt.Objtype {
- case pgquery.ObjectType_OBJECT_COLUMN:
- commentStmt.Type = ast.ObjectTypeColumn
- switch node := in.CommentStmt.Object.Node.(type) {
- case *pgquery.Node_List:
- columnNameDef, err := ConvertNodeListToColumnNameDef(node.List.Items)
- if err != nil {
- return nil, err
- }
- commentStmt.Object = columnNameDef
- default:
- return nil, errors.Errorf("expect to get a list node but got %T", node)
- }
- case pgquery.ObjectType_OBJECT_TABLE:
- commentStmt.Type = ast.ObjectTypeTable
- switch node := in.CommentStmt.Object.Node.(type) {
- case *pgquery.Node_List:
- tableDef, err := convertNodeListToTableDef(node.List.Items)
- if err != nil {
- return nil, err
- }
- commentStmt.Object = tableDef
- default:
- return nil, errors.Errorf("expect to get a list node but got %T", node)
- }
- case pgquery.ObjectType_OBJECT_VIEW:
- commentStmt.Type = ast.ObjectTypeView
- switch node := in.CommentStmt.Object.Node.(type) {
- case *pgquery.Node_List:
- tableDef, err := convertNodeListToTableDef(node.List.Items)
- if err != nil {
- return nil, err
- }
- commentStmt.Object = tableDef
- default:
- return nil, errors.Errorf("expect to get a list node but got %T", node)
- }
- default:
- return nil, NewConvertErrorf("unexpected comment object type: %q", in.CommentStmt.Objtype.String())
- }
-
- return &commentStmt, nil
- case *pgquery.Node_CreatedbStmt:
- createDatabaseStmt := ast.CreateDatabaseStmt{
- Name: in.CreatedbStmt.Dbname,
- }
- for _, option := range in.CreatedbStmt.Options {
- if item, ok := option.Node.(*pgquery.Node_DefElem); ok && item.DefElem.Defname == "encoding" {
- value, ok := item.DefElem.Arg.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", item.DefElem.Arg.Node)
- }
- createDatabaseStmt.OptionList = append(createDatabaseStmt.OptionList, &ast.DatabaseOptionDef{
- Type: ast.DatabaseOptionEncoding,
- Value: value.String_.Sval,
- })
- }
- }
-
- return &createDatabaseStmt, nil
- case *pgquery.Node_CreateSchemaStmt:
- createSchemaStmt := ast.CreateSchemaStmt{
- Name: in.CreateSchemaStmt.Schemaname,
- IfNotExists: in.CreateSchemaStmt.IfNotExists,
- }
- roleSpec, err := convertRoleSpec(in.CreateSchemaStmt.Authrole)
- if err != nil {
- return nil, err
- }
- createSchemaStmt.RoleSpec = roleSpec
- for _, elt := range in.CreateSchemaStmt.SchemaElts {
- switch stmt := elt.Node.(type) {
- // Currently, only CREATE TABLE, CREATE VIEW, CREATE INDEX, CREATE SEQUENCE,
- // CREATE TRIGGER and GRANT are accepted as clauses within CREATE SCHEMA.
- // TODO(zp): support other statement list above.
- case *pgquery.Node_CreateStmt:
- createStmt, err := convertCreateStmt(stmt.CreateStmt)
- if err != nil {
- return nil, err
- }
- createSchemaStmt.SchemaElementList = append(createSchemaStmt.SchemaElementList, createStmt)
- default:
- }
- }
- return &createSchemaStmt, nil
- case *pgquery.Node_CreateExtensionStmt:
- createExtensionStmt := &ast.CreateExtensionStmt{
- Name: in.CreateExtensionStmt.Extname,
- IfNotExists: in.CreateExtensionStmt.IfNotExists,
- }
-
- for _, option := range in.CreateExtensionStmt.Options {
- if item, ok := option.Node.(*pgquery.Node_DefElem); ok {
- if item.DefElem.Defname == "schema" {
- schemaName, ok := item.DefElem.Arg.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", item.DefElem.Arg.Node)
- }
- createExtensionStmt.Schema = schemaName.String_.Sval
- }
- }
- }
-
- return createExtensionStmt, nil
- case *pgquery.Node_CreateFunctionStmt:
- var err error
- functionDef := &ast.FunctionDef{}
-
- functionDef.Schema, functionDef.Name, err = convertObjectName(in.CreateFunctionStmt.Funcname)
- if err != nil {
- return nil, err
- }
-
- functionDef.ParameterList, err = convertFunctionParameterList(in.CreateFunctionStmt.Parameters)
- if err != nil {
- return nil, err
- }
-
- createFunc := &ast.CreateFunctionStmt{Function: functionDef}
- createFunc.SetOriginalNode(in)
-
- return createFunc, nil
- case *pgquery.Node_CreateTrigStmt:
- createTriggerStmt := &ast.CreateTriggerStmt{
- Trigger: &ast.TriggerDef{
- Name: in.CreateTrigStmt.Trigname,
- Table: convertRangeVarToTableName(in.CreateTrigStmt.Relation, ast.TableTypeUnknown),
- },
- }
-
- return createTriggerStmt, nil
- case *pgquery.Node_CreateEnumStmt:
- var err error
- enumTypeDef := &ast.EnumTypeDef{Name: &ast.TypeNameDef{}}
-
- enumTypeDef.Name.Schema, enumTypeDef.Name.Name, err = convertObjectName(in.CreateEnumStmt.TypeName)
- if err != nil {
- return nil, err
- }
-
- enumTypeDef.LabelList, err = convertEnumLabelList(in.CreateEnumStmt.Vals)
- if err != nil {
- return nil, err
- }
-
- return &ast.CreateTypeStmt{Type: enumTypeDef}, nil
- case *pgquery.Node_AlterEnumStmt:
- if in.AlterEnumStmt.OldVal == "" {
- schema, name, err := convertObjectName(in.AlterEnumStmt.TypeName)
- if err != nil {
- return nil, err
- }
- typeName := &ast.TypeNameDef{
- Schema: schema,
- Name: name,
- }
- // ADD ENUM VALUE STATEMENT
- addEnumValueStmt := &ast.AddEnumLabelStmt{
- EnumType: typeName,
- NewLabel: in.AlterEnumStmt.NewVal,
- NeighborLabel: in.AlterEnumStmt.NewValNeighbor,
- }
- if in.AlterEnumStmt.NewValNeighbor == "" {
- addEnumValueStmt.Position = ast.PositionTypeEnd
- } else if in.AlterEnumStmt.NewValIsAfter {
- addEnumValueStmt.Position = ast.PositionTypeAfter
- } else {
- addEnumValueStmt.Position = ast.PositionTypeBefore
- }
-
- return &ast.AlterTypeStmt{
- Type: typeName,
- AlterItemList: []ast.Node{addEnumValueStmt},
- }, nil
- }
- // TODO(rebelice): support RENAME ENUM VALUE statements
- case *pgquery.Node_TransactionStmt:
- if in.TransactionStmt.Kind == pgquery.TransactionStmtKind_TRANS_STMT_COMMIT {
- return &ast.CommitStmt{}, nil
- }
- case *pgquery.Node_VariableSetStmt:
- args := []ast.ExpressionNode{}
- for _, arg := range in.VariableSetStmt.Args {
- exprNode, _, _, err := convertExpressionNode(arg)
- if err != nil {
- return nil, err
- }
- args = append(args, exprNode)
- }
- return &ast.VariableSetStmt{
- Name: in.VariableSetStmt.Name,
- Args: args,
- IsLocal: in.VariableSetStmt.IsLocal,
- }, nil
- case *pgquery.Node_ViewStmt:
- viewStmt := &ast.CreateViewStmt{
- Replace: in.ViewStmt.Replace,
- Name: convertRangeVarToTableName(in.ViewStmt.View, ast.TableTypeView),
- }
-
- if query, ok := in.ViewStmt.Query.Node.(*pgquery.Node_SelectStmt); ok {
- if viewStmt.Select, err = convertSelectStmt(query.SelectStmt); err != nil {
- return nil, err
- }
- }
-
- for _, alias := range in.ViewStmt.Aliases {
- if alias, ok := alias.Node.(*pgquery.Node_String_); ok {
- viewStmt.Aliases = append(viewStmt.Aliases, alias.String_.Sval)
- }
- }
-
- viewStmt.SetOriginalNode(in)
- return viewStmt, nil
- case *pgquery.Node_VariableShowStmt:
- variableShowStmt := &ast.VariableShowStmt{
- Name: in.VariableShowStmt.GetName(),
- }
- return variableShowStmt, nil
- case *pgquery.Node_CreateTableAsStmt:
- if in.CreateTableAsStmt.Objtype != pgquery.ObjectType_OBJECT_MATVIEW {
- return &ast.UnconvertedStmt{}, nil
- }
- materializedViewStmt := &ast.CreateMaterializedViewStmt{
- Name: convertRangeVarToTableName(in.CreateTableAsStmt.Into.Rel, ast.TableTypeMaterializedView),
- }
- materializedViewStmt.SetOriginalNode(in)
- return materializedViewStmt, nil
- default:
- return &ast.UnconvertedStmt{}, nil
- }
-
- return nil, nil
-}
-
-// setLineForCreateTableStmt sets the line for columns and table constraints in CREATE TABLE statements.
-func setLineForCreateTableStmt(node *ast.CreateTableStmt) error {
- t := tokenizer.NewTokenizer(node.Text())
- firstLine := node.LastLine() - strings.Count(node.Text(), "\n")
- return t.SetLineForPGCreateTableStmt(node, firstLine)
-}
-
-func convertEnumLabelList(list []*pgquery.Node) ([]string, error) {
- var result []string
- for _, node := range list {
- stringNode, ok := node.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", node.Node)
- }
- result = append(result, stringNode.String_.Sval)
- }
- return result, nil
-}
-
-func convertFunctionParameterList(parameterList []*pgquery.Node) ([]*ast.FunctionParameterDef, error) {
- var result []*ast.FunctionParameterDef
- for _, node := range parameterList {
- var err error
- switch parameterNode := node.Node.(type) {
- case *pgquery.Node_FunctionParameter:
- parameterDef := &ast.FunctionParameterDef{
- Name: parameterNode.FunctionParameter.Name,
- Mode: convertParameterMode(parameterNode.FunctionParameter.Mode),
- }
- parameterDef.Type, err = convertDataType(parameterNode.FunctionParameter.ArgType)
- if err != nil {
- return nil, err
- }
- result = append(result, parameterDef)
- case *pgquery.Node_TypeName:
- parameterDef := &ast.FunctionParameterDef{}
- parameterDef.Type, err = convertDataType(parameterNode.TypeName)
- if err != nil {
- return nil, err
- }
- result = append(result, parameterDef)
- default:
- return nil, NewConvertErrorf("expected FunctionParameter or TypeName but found %t", node.Node)
- }
- }
- return result, nil
-}
-
-func convertParameterMode(mode pgquery.FunctionParameterMode) ast.FunctionParameterMode {
- switch mode {
- case pgquery.FunctionParameterMode_FUNC_PARAM_IN:
- return ast.FunctionParameterModeIn
- case pgquery.FunctionParameterMode_FUNC_PARAM_OUT:
- return ast.FunctionParameterModeOut
- case pgquery.FunctionParameterMode_FUNC_PARAM_INOUT:
- return ast.FunctionParameterModeInOut
- case pgquery.FunctionParameterMode_FUNC_PARAM_VARIADIC:
- return ast.FunctionParameterModeVariadic
- case pgquery.FunctionParameterMode_FUNC_PARAM_TABLE:
- return ast.FunctionParameterModeTable
- case pgquery.FunctionParameterMode_FUNC_PARAM_DEFAULT:
- return ast.FunctionParameterModeDefault
- default:
- return ast.FunctionParameterModeUndefined
- }
-}
-
-// convertObjectName requires one or two nodes, and return two strings.
-func convertObjectName(list []*pgquery.Node) (string, string, error) {
- switch len(list) {
- case 2:
- schema, err := convertToString(list[0])
- if err != nil {
- return "", "", err
- }
- name, err := convertToString(list[1])
- if err != nil {
- return "", "", err
- }
- return schema, name, nil
- case 1:
- name, err := convertToString(list[0])
- if err != nil {
- return "", "", err
- }
- return "", name, nil
- default:
- return "", "", NewConvertErrorf("expected 1 or 2 items but found %d", len(list))
- }
-}
-
-func convertToString(in *pgquery.Node) (string, error) {
- stringNode, ok := in.Node.(*pgquery.Node_String_)
- if !ok {
- return "", NewConvertErrorf("expected String but found %t", in.Node)
- }
- return stringNode.String_.Sval, nil
-}
-
-func convertAlterSequence(in *pgquery.AlterSeqStmt) (*ast.AlterSequenceStmt, error) {
- alterSequenceStmt := &ast.AlterSequenceStmt{
- IfExists: in.MissingOk,
- }
-
- if in.Sequence == nil {
- return nil, NewConvertErrorf("AlterSeqStmt.Sequence is nil")
- }
-
- alterSequenceStmt.Name = convertRangeVarToSeqName(in.Sequence)
-
- for _, option := range in.Options {
- defElemNode, ok := option.Node.(*pgquery.Node_DefElem)
- if !ok {
- return nil, NewConvertErrorf("expected DefElem but found %t", option.Node)
- }
- var err error
- switch defElemNode.DefElem.Defname {
- case "as":
- if alterSequenceStmt.Type, err = convertDefElemToSeqType(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "increment":
- if alterSequenceStmt.IncrementBy, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "start":
- if alterSequenceStmt.StartWith, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "restart":
- if alterSequenceStmt.RestartWith, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "minvalue":
- if alterSequenceStmt.MinValue, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- if alterSequenceStmt.MinValue == nil {
- alterSequenceStmt.NoMinValue = true
- }
- case "maxvalue":
- if alterSequenceStmt.MaxValue, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- if alterSequenceStmt.MaxValue == nil {
- alterSequenceStmt.NoMaxValue = true
- }
- case "cache":
- if alterSequenceStmt.Cache, err = convertDefElemNodeIntegerToInt64(defElemNode.DefElem); err != nil {
- return nil, err
- }
- case "cycle":
- var cycle bool
- if cycle, err = convertDefElemNodeIntegerToBool(defElemNode.DefElem); err != nil {
- return nil, err
- }
- alterSequenceStmt.Cycle = &cycle
- case "owned_by":
- owner, err := convertDefElemNodeListToColumnNameDef(defElemNode.DefElem)
- if err != nil {
- return nil, err
- }
- if owner.Table.Database == "" &&
- owner.Table.Schema == "" &&
- owner.Table.Name == "" &&
- owner.ColumnName == "none" {
- alterSequenceStmt.OwnedByNone = true
- } else {
- alterSequenceStmt.OwnedBy = owner
- }
- default:
- return nil, NewConvertErrorf("unsupported option %s", defElemNode.DefElem.Defname)
- }
- }
-
- return alterSequenceStmt, nil
-}
-
-func convertDropBehavior(behavior pgquery.DropBehavior) ast.DropBehavior {
- switch behavior {
- case pgquery.DropBehavior_DROP_CASCADE:
- return ast.DropBehaviorCascade
- case pgquery.DropBehavior_DROP_RESTRICT:
- return ast.DropBehaviorRestrict
- default:
- return ast.DropBehaviorNone
- }
-}
-
-func convertRoleSpec(in *pgquery.RoleSpec) (*ast.RoleSpec, error) {
- if in == nil {
- return nil, nil
- }
- switch in.Roletype {
- case pgquery.RoleSpecType_ROLE_SPEC_TYPE_UNDEFINED:
- return &ast.RoleSpec{
- Type: ast.RoleSpecTypeNone,
- Value: "",
- }, nil
- case pgquery.RoleSpecType_ROLESPEC_CSTRING:
- return &ast.RoleSpec{
- Type: ast.RoleSpecTypeUser,
- Value: in.Rolename,
- }, nil
- case pgquery.RoleSpecType_ROLESPEC_CURRENT_USER:
- return &ast.RoleSpec{
- Type: ast.RoleSpecTypeCurrentUser,
- Value: "",
- }, nil
- case pgquery.RoleSpecType_ROLESPEC_SESSION_USER:
- return &ast.RoleSpec{
- Type: ast.RoleSpecTypeSessionUser,
- Value: "",
- }, nil
- default:
- return nil, NewConvertErrorf("unexpected role spec type: %q", in.Roletype.String())
- }
-}
-
-func convertNullOrder(order pgquery.SortByNulls) (ast.NullOrderType, error) {
- switch order {
- case pgquery.SortByNulls_SORTBY_NULLS_DEFAULT:
- return ast.NullOrderTypeDefault, nil
- case pgquery.SortByNulls_SORTBY_NULLS_FIRST:
- return ast.NullOrderTypeFirst, nil
- case pgquery.SortByNulls_SORTBY_NULLS_LAST:
- return ast.NullOrderTypeLast, nil
- default:
- return ast.NullOrderTypeDefault, NewConvertErrorf("unsupported null sort order: %d", order)
- }
-}
-
-func convertSortOrder(order pgquery.SortByDir) (ast.SortOrderType, error) {
- switch order {
- case pgquery.SortByDir_SORTBY_DEFAULT:
- return ast.SortOrderTypeDefault, nil
- case pgquery.SortByDir_SORTBY_ASC:
- return ast.SortOrderTypeAscending, nil
- case pgquery.SortByDir_SORTBY_DESC:
- return ast.SortOrderTypeDescending, nil
- default:
- return ast.NullOrderTypeDefault, NewConvertErrorf("unsupported sort order: %d", order)
- }
-}
-
-func convertMethodType(method string) ast.IndexMethodType {
- switch method {
- case "btree":
- return ast.IndexMethodTypeBTree
- case "hash":
- return ast.IndexMethodTypeHash
- case "gist":
- return ast.IndexMethodTypeGiST
- case "spgist":
- return ast.IndexMethodTypeSpGiST
- case "gin":
- return ast.IndexMethodTypeGin
- case "brin":
- return ast.IndexMethodTypeBrin
- case "ivfflat":
- return ast.IndexMethodTypeIvfflat
- default:
- // Fallback to btree for index from plugins.
- return ast.IndexMethodTypeBTree
- }
-}
-
-func convertExpressionNode(node *pgquery.Node) (ast.ExpressionNode, []*ast.PatternLikeDef, []*ast.SubqueryDef, error) {
- if node == nil || node.Node == nil {
- return &ast.UnconvertedExpressionDef{}, nil, nil, nil
- }
- switch in := node.Node.(type) {
- case *pgquery.Node_AConst:
- switch val := in.AConst.Val.(type) {
- case *pgquery.A_Const_Sval:
- return &ast.StringDef{Value: val.Sval.Sval}, nil, nil, nil
- case *pgquery.A_Const_Ival:
- return &ast.IntegerDef{Value: val.Ival.Ival}, nil, nil, nil
- case *pgquery.A_Const_Boolval:
- return &ast.BoolDef{Value: val.Boolval.Boolval}, nil, nil, nil
- default:
- return &ast.UnconvertedExpressionDef{}, nil, nil, nil
- }
- case *pgquery.Node_String_:
- return &ast.StringDef{Value: in.String_.Sval}, nil, nil, nil
- case *pgquery.Node_ResTarget:
- return convertExpressionNode(in.ResTarget.Val)
- case *pgquery.Node_TypeCast:
- _, likeList, subqueryList, err := convertExpressionNode(in.TypeCast.Arg)
- if err != nil {
- return nil, nil, nil, err
- }
- return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil
- case *pgquery.Node_ColumnRef:
- columnDef, err := ConvertNodeListToColumnNameDef(in.ColumnRef.Fields)
- return columnDef, nil, nil, err
- case *pgquery.Node_FuncCall:
- var likeList []*ast.PatternLikeDef
- var subqueryList []*ast.SubqueryDef
- for _, arg := range in.FuncCall.Args {
- _, interLike, interSubquery, err := convertExpressionNode(arg)
- if err != nil {
- return nil, nil, nil, err
- }
- likeList = append(likeList, interLike...)
- subqueryList = append(subqueryList, interSubquery...)
- }
- return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil
- case *pgquery.Node_AExpr:
- var likeList, interLike []*ast.PatternLikeDef
- var subqueryList, interSubquery []*ast.SubqueryDef
- var lExpr, rExpr ast.ExpressionNode
- var err error
- if in.AExpr.Lexpr != nil {
- if lExpr, interLike, interSubquery, err = convertExpressionNode(in.AExpr.Lexpr); err != nil {
- return nil, nil, nil, err
- }
- likeList = append(likeList, interLike...)
- subqueryList = append(subqueryList, interSubquery...)
- }
- if in.AExpr.Rexpr != nil {
- if rExpr, interLike, interSubquery, err = convertExpressionNode(in.AExpr.Rexpr); err != nil {
- return nil, nil, nil, err
- }
- likeList = append(likeList, interLike...)
- subqueryList = append(subqueryList, interSubquery...)
- }
- if len(in.AExpr.Name) == 1 {
- name, ok := in.AExpr.Name[0].Node.(*pgquery.Node_String_)
- if !ok {
- return nil, nil, nil, NewConvertErrorf("expected String but found %t", in.AExpr.Name[0].Node)
- }
- switch name.String_.Sval {
- // LIKE
- case operatorLike, operatorNotLike:
- like := &ast.PatternLikeDef{
- Not: (name.String_.Sval == operatorNotLike),
- Expression: lExpr,
- Pattern: rExpr,
- }
- likeList = append(likeList, like)
- return like, likeList, interSubquery, nil
- default:
- // Other operators
- }
- }
- return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil
- case *pgquery.Node_BoolExpr:
- var likeList []*ast.PatternLikeDef
- var subqueryList []*ast.SubqueryDef
- for _, arg := range in.BoolExpr.Args {
- _, interLike, interSubquery, err := convertExpressionNode(arg)
- if err != nil {
- return nil, nil, nil, err
- }
- likeList = append(likeList, interLike...)
- subqueryList = append(subqueryList, interSubquery...)
- }
- return &ast.UnconvertedExpressionDef{}, likeList, subqueryList, nil
- case *pgquery.Node_SubLink:
- if subselectNode, ok := in.SubLink.Subselect.Node.(*pgquery.Node_SelectStmt); ok {
- subselect, err := convertSelectStmt(subselectNode.SelectStmt)
- if err != nil {
- return nil, nil, nil, err
- }
- subQuery := &ast.SubqueryDef{Select: subselect}
- return subQuery, nil, []*ast.SubqueryDef{subQuery}, nil
- }
- case *pgquery.Node_SqlvalueFunction:
- return &ast.UnconvertedExpressionDef{}, nil, nil, nil
- }
- return &ast.UnconvertedExpressionDef{}, nil, nil, nil
-}
-
-// convertCreateStmt convert pgquery create stmt to Bytebase create table stmt node.
-func convertCreateStmt(in *pgquery.CreateStmt) (*ast.CreateTableStmt, error) {
- table := &ast.CreateTableStmt{
- IfNotExists: in.IfNotExists,
- Name: convertRangeVarToTableName(in.Relation, ast.TableTypeBaseTable),
- }
-
- for _, elt := range in.TableElts {
- switch item := elt.Node.(type) {
- case *pgquery.Node_ColumnDef:
- column, err := convertColumnDef(item)
- if err != nil {
- return nil, err
- }
- table.ColumnList = append(table.ColumnList, column)
- case *pgquery.Node_Constraint:
- cons, err := convertConstraint(item)
- if err != nil {
- return nil, err
- }
- table.ConstraintList = append(table.ConstraintList, cons)
- }
- }
-
- if in.Partspec != nil {
- table.PartitionDef = &ast.PartitionDef{
- Strategy: in.Partspec.Strategy,
- }
- for _, item := range in.Partspec.PartParams {
- partElem, ok := item.Node.(*pgquery.Node_PartitionElem)
- if !ok {
- return nil, NewConvertErrorf("expected PartitionElem but found %t", item.Node)
- }
- if partElem.PartitionElem.Name != "" {
- table.PartitionDef.KeyList = append(table.PartitionDef.KeyList, &ast.PartitionKeyDef{
- Type: ast.PartitionKeyTypeColumn,
- Key: partElem.PartitionElem.Name,
- })
- } else if partElem.PartitionElem.Expr != nil {
- expr, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, partElem.PartitionElem.Expr)
- if err != nil {
- return nil, err
- }
- table.PartitionDef.KeyList = append(table.PartitionDef.KeyList, &ast.PartitionKeyDef{
- Type: ast.PartitionKeyTypeExpression,
- Key: expr,
- })
- }
- }
- }
- return table, nil
-}
-
-func convertSelectStmt(in *pgquery.SelectStmt) (*ast.SelectStmt, error) {
- selectStmt := &ast.SelectStmt{}
- selectStmt.SetOriginalNode(in)
-
- setOperation, err := convertSetOperation(in.Op)
- if err != nil {
- return nil, err
- }
-
- selectStmt.SetOperation = setOperation
- if setOperation != ast.SetOperationTypeNone {
- lQuery, err := convertSelectStmt(in.Larg)
- if err != nil {
- return nil, err
- }
- rQuery, err := convertSelectStmt(in.Rarg)
- if err != nil {
- return nil, err
- }
- selectStmt.LQuery = lQuery
- selectStmt.RQuery = rQuery
- return selectStmt, nil
- }
-
- // Convert target list
- for _, node := range in.TargetList {
- convertedNode, _, _, err := convertExpressionNode(node)
- if err != nil {
- return nil, err
- }
- selectStmt.FieldList = append(selectStmt.FieldList, convertedNode)
- }
- // Convert FROM clause
- // Here we only find the SELECT stmt in FROM clause
- for _, item := range in.FromClause {
- if node, ok := item.Node.(*pgquery.Node_RangeSubselect); ok {
- subselect, err := convertRangeSubselect(node.RangeSubselect)
- if err != nil {
- return nil, err
- }
- selectStmt.SubqueryList = append(selectStmt.SubqueryList, subselect)
- }
- }
- selectStmt.SetFromClause(in.FromClause)
-
- // Convert WHERE clause
- if in.WhereClause != nil {
- var err error
- var subqueryList []*ast.SubqueryDef
- selectStmt.WhereClause, selectStmt.PatternLikeList, subqueryList, err = convertExpressionNode(in.WhereClause)
- if err != nil {
- return nil, err
- }
- selectStmt.SubqueryList = append(selectStmt.SubqueryList, subqueryList...)
- }
-
- if in.LimitCount != nil {
- limitConst := in.LimitCount.GetAConst()
- if limitConst != nil && limitConst.GetIval() != nil {
- selectStmt.Limit = &limitConst.GetIval().Ival
- }
- }
-
- // Convert ORDER BY clause.
- for _, itemNode := range in.SortClause {
- item, ok := itemNode.Node.(*pgquery.Node_SortBy)
- if !ok {
- return nil, NewConvertErrorf("expected SortBy but found %t", itemNode.Node)
- }
- expression, _, _, err := convertExpressionNode(item.SortBy.Node)
- if err != nil {
- return nil, err
- }
-
- text, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, item.SortBy.Node)
- if err != nil {
- fmt.Printf("itemNode %t %v", itemNode.Node, item)
- return nil, err
- }
- expression.SetText(text)
- selectStmt.OrderByClause = append(selectStmt.OrderByClause, &ast.ByItemDef{Expression: expression})
- }
- return selectStmt, nil
-}
-
-func convertRangeSubselect(node *pgquery.RangeSubselect) (*ast.SubqueryDef, error) {
- subselect, ok := node.Subquery.Node.(*pgquery.Node_SelectStmt)
- if !ok {
- return nil, NewConvertErrorf("expected SELECT but found %t", node.Subquery.Node)
- }
- res, err := convertSelectStmt(subselect.SelectStmt)
- if err != nil {
- return nil, err
- }
- return &ast.SubqueryDef{Select: res}, nil
-}
-
-func convertSetOperation(t pgquery.SetOperation) (ast.SetOperationType, error) {
- switch t {
- case pgquery.SetOperation_SETOP_NONE:
- return ast.SetOperationTypeNone, nil
- case pgquery.SetOperation_SETOP_UNION:
- return ast.SetOperationTypeUnion, nil
- case pgquery.SetOperation_SETOP_INTERSECT:
- return ast.SetOperationTypeIntersect, nil
- case pgquery.SetOperation_SETOP_EXCEPT:
- return ast.SetOperationTypeExcept, nil
- default:
- return 0, errors.Errorf("failed to parse set operation: unknown type %s", t)
- }
-}
-
-func convertListToSequenceNameDef(in *pgquery.Node_List) (*ast.SequenceNameDef, error) {
- stringList, err := convertListToStringList(in)
- if err != nil {
- return &ast.SequenceNameDef{}, err
- }
- switch len(in.List.Items) {
- case 2:
- return &ast.SequenceNameDef{
- Schema: stringList[0],
- Name: stringList[1],
- }, nil
- case 1:
- return &ast.SequenceNameDef{
- Name: stringList[0],
- }, nil
- default:
- return &ast.SequenceNameDef{}, NewConvertErrorf("expected length is 1 or 2, but found %d", len(in.List.Items))
- }
-}
-
-func convertListToTableDef(in *pgquery.Node_List, tableType ast.TableType) (*ast.TableDef, error) {
- stringList, err := convertListToStringList(in)
- if err != nil {
- return nil, err
- }
- switch len(in.List.Items) {
- case 2:
- return &ast.TableDef{
- Type: tableType,
- Schema: stringList[0],
- Name: stringList[1],
- }, nil
- case 1:
- return &ast.TableDef{
- Type: tableType,
- Name: stringList[0],
- }, nil
- default:
- return nil, NewConvertErrorf("expected length is 1 or 2, but found %d", len(in.List.Items))
- }
-}
-
-func convertListToIndexDef(in *pgquery.Node_List, tableType ast.TableType) (*ast.IndexDef, error) {
- stringList, err := convertListToStringList(in)
- if err != nil {
- return nil, err
- }
- indexDef := &ast.IndexDef{}
- switch len(in.List.Items) {
- case 2:
- indexDef.Table = &ast.TableDef{
- Type: tableType,
- Schema: stringList[0],
- }
- indexDef.Name = stringList[1]
- case 1:
- indexDef.Name = stringList[0]
- default:
- return nil, NewConvertErrorf("expected length is 1 or 2, but found %d", len(in.List.Items))
- }
- return indexDef, nil
-}
-
-func convertListToStringList(in *pgquery.Node_List) ([]string, error) {
- var res []string
- for _, item := range in.List.Items {
- s, ok := item.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", item.Node)
- }
- res = append(res, s.String_.Sval)
- }
- return res, nil
-}
-
-func convertRangeVarToTableName(in *pgquery.RangeVar, tableType ast.TableType) *ast.TableDef {
- return &ast.TableDef{
- Type: tableType,
- Database: in.Catalogname,
- Schema: in.Schemaname,
- Name: in.Relname,
- }
-}
-
-func convertRangeVarToSeqName(in *pgquery.RangeVar) *ast.SequenceNameDef {
- return &ast.SequenceNameDef{
- Schema: in.Schemaname,
- Name: in.Relname,
- }
-}
-
-func convertRangeVarToIndexTableName(in *pgquery.RangeVar, tableType ast.TableType) *ast.TableDef {
- return &ast.TableDef{
- Type: tableType,
- Schema: in.Schemaname,
- }
-}
-
-func convertConstraint(in *pgquery.Node_Constraint) (*ast.ConstraintDef, error) {
- cons := &ast.ConstraintDef{
- Name: in.Constraint.Conname,
- Type: convertConstraintType(in.Constraint.Contype, in.Constraint.Indexname != ""),
- SkipValidation: in.Constraint.SkipValidation,
- Deferrable: in.Constraint.Deferrable,
- Initdeferred: in.Constraint.Initdeferred,
- }
-
- switch cons.Type {
- case ast.ConstraintTypePrimary, ast.ConstraintTypeUnique:
- for _, key := range in.Constraint.Keys {
- name, ok := key.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", key.Node)
- }
- cons.KeyList = append(cons.KeyList, name.String_.Sval)
- }
- for _, col := range in.Constraint.Including {
- name, ok := col.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", col.Node)
- }
- cons.Including = append(cons.Including, name.String_.Sval)
- }
- cons.IndexTableSpace = in.Constraint.Indexspace
- case ast.ConstraintTypeForeign:
- cons.Foreign = &ast.ForeignDef{
- Table: convertRangeVarToTableName(in.Constraint.Pktable, ast.TableTypeBaseTable),
- }
-
- var err error
- if cons.Foreign.MatchType, err = convertForeignMatchType(in.Constraint.FkMatchtype); err != nil {
- return nil, err
- }
- if cons.Foreign.OnUpdate, err = convertReferentialAction(in.Constraint.FkUpdAction); err != nil {
- return nil, err
- }
- if cons.Foreign.OnDelete, err = convertReferentialAction(in.Constraint.FkDelAction); err != nil {
- return nil, err
- }
-
- for _, item := range in.Constraint.PkAttrs {
- name, ok := item.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", item.Node)
- }
- cons.Foreign.ColumnList = append(cons.Foreign.ColumnList, name.String_.Sval)
- }
-
- for _, item := range in.Constraint.FkAttrs {
- name, ok := item.Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", item.Node)
- }
- cons.KeyList = append(cons.KeyList, name.String_.Sval)
- }
- case ast.ConstraintTypePrimaryUsingIndex, ast.ConstraintTypeUniqueUsingIndex:
- cons.IndexName = in.Constraint.Indexname
- case ast.ConstraintTypeCheck, ast.ConstraintTypeDefault, ast.ConstraintTypeGenerated:
- expression, _, _, err := convertExpressionNode(in.Constraint.RawExpr)
- if err != nil {
- return nil, err
- }
- text, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, in.Constraint.RawExpr)
- if err != nil {
- return nil, err
- }
- expression.SetText(text)
- cons.Expression = expression
- case ast.ConstraintTypeExclusion:
- if len(in.Constraint.Exclusions) >= 1 {
- exclusion, err := pgquery.DeparseNodes(pgquery.DeparseTypeExclusion, in.Constraint.Exclusions)
- if err != nil {
- return nil, err
- }
- cons.Exclusions = exclusion
- }
- cons.AccessMethod = convertMethodType(in.Constraint.AccessMethod)
- if in.Constraint.WhereClause != nil {
- whereClause, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, in.Constraint.WhereClause)
- if err != nil {
- return nil, err
- }
- cons.WhereClause = whereClause
- }
- default:
- // Other constraint types
- }
-
- return cons, nil
-}
-
-func convertForeignMatchType(tp string) (ast.ForeignMatchType, error) {
- switch tp {
- case "s":
- return ast.ForeignMatchTypeSimple, nil
- case "f":
- return ast.ForeignMatchTypeFull, nil
- case "p":
- return ast.ForeignMatchTypePartial, nil
- default:
- return ast.ForeignMatchTypeSimple, NewConvertErrorf("unsupported foreign match type: %s", tp)
- }
-}
-
-func convertReferentialAction(action string) (*ast.ReferentialActionDef, error) {
- switch action {
- case "a":
- return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction}, nil
- case "r":
- return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeRestrict}, nil
- case "c":
- return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeCascade}, nil
- case "n":
- return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetNull}, nil
- case "d":
- return &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetDefault}, nil
- default:
- return nil, NewConvertErrorf("unsupported referential action: %s", action)
- }
-}
-
-func convertConstraintType(in pgquery.ConstrType, usingIndex bool) ast.ConstraintType {
- switch in {
- case pgquery.ConstrType_CONSTR_PRIMARY:
- if usingIndex {
- return ast.ConstraintTypePrimaryUsingIndex
- }
- return ast.ConstraintTypePrimary
- case pgquery.ConstrType_CONSTR_UNIQUE:
- if usingIndex {
- return ast.ConstraintTypeUniqueUsingIndex
- }
- return ast.ConstraintTypeUnique
- case pgquery.ConstrType_CONSTR_FOREIGN:
- if usingIndex {
- return ast.ConstraintTypeUndefined
- }
- return ast.ConstraintTypeForeign
- case pgquery.ConstrType_CONSTR_NOTNULL:
- return ast.ConstraintTypeNotNull
- case pgquery.ConstrType_CONSTR_CHECK:
- return ast.ConstraintTypeCheck
- case pgquery.ConstrType_CONSTR_DEFAULT:
- return ast.ConstraintTypeDefault
- case pgquery.ConstrType_CONSTR_EXCLUSION:
- return ast.ConstraintTypeExclusion
- case pgquery.ConstrType_CONSTR_GENERATED:
- return ast.ConstraintTypeGenerated
- case pgquery.ConstrType_CONSTR_NULL:
- return ast.ConstraintTypeNull
- default:
- return ast.ConstraintTypeUndefined
- }
-}
-
-func convertColumnDef(in *pgquery.Node_ColumnDef) (*ast.ColumnDef, error) {
- column := &ast.ColumnDef{
- ColumnName: in.ColumnDef.Colname,
- }
- columnType, err := convertDataType(in.ColumnDef.TypeName)
- if err != nil {
- return nil, err
- }
- column.Type = columnType
-
- for _, cons := range in.ColumnDef.Constraints {
- constraint, ok := cons.Node.(*pgquery.Node_Constraint)
- if !ok {
- return nil, NewConvertErrorf("expected Constraint but found %t", cons.Node)
- }
- columnCons, err := convertConstraint(constraint)
- if err != nil {
- return nil, err
- }
- columnCons.KeyList = append(columnCons.KeyList, in.ColumnDef.Colname)
- column.ConstraintList = append(column.ConstraintList, columnCons)
- }
-
- if in.ColumnDef.CollClause != nil {
- collation, err := convertCollationName(in.ColumnDef.CollClause)
- if err != nil {
- return nil, err
- }
- column.Collation = collation
- }
-
- return column, nil
-}
-
-func convertCollationName(collation *pgquery.CollateClause) (*ast.CollationNameDef, error) {
- result := &ast.CollationNameDef{}
- var err error
- switch len(collation.Collname) {
- case 1:
- result.Name, err = convertToString(collation.Collname[0])
- if err != nil {
- return nil, err
- }
- case 2:
- result.Schema, err = convertToString(collation.Collname[0])
- if err != nil {
- return nil, err
- }
- result.Name, err = convertToString(collation.Collname[1])
- if err != nil {
- return nil, err
- }
- default:
- return nil, NewConvertErrorf("expected one or two length but found %d", len(collation.Collname))
- }
- return result, nil
-}
-
-func convertToTableType(relationType pgquery.ObjectType) (ast.TableType, error) {
- switch relationType {
- case pgquery.ObjectType_OBJECT_TABLE:
- return ast.TableTypeBaseTable, nil
- case pgquery.ObjectType_OBJECT_VIEW:
- return ast.TableTypeView, nil
- default:
- return ast.TableTypeUnknown, NewConvertErrorf("expected TABLE or VIEW but found %s", relationType)
- }
-}
-
-func stripPgCatalogPrefix(tp *pgquery.TypeName) *pgquery.TypeName {
- // The built-in data type may have the "pg_catalog" prefix.
- if len(tp.Names) > 0 {
- if first, ok := tp.Names[0].Node.(*pgquery.Node_String_); ok && first.String_.Sval == "pg_catalog" {
- tp.Names = tp.Names[1:]
- }
- }
- return tp
-}
-
-func convertDataType(tp *pgquery.TypeName) (ast.DataType, error) {
- text, err := pgquery.DeparseNode(pgquery.DeparseTypeDataType, &pgquery.Node{Node: &pgquery.Node_TypeName{TypeName: tp}})
- if err != nil {
- return nil, err
- }
-
- dataType := func() ast.DataType {
- tp = stripPgCatalogPrefix(tp)
- if len(tp.Names) == 1 {
- name, ok := tp.Names[0].Node.(*pgquery.Node_String_)
- if !ok {
- return &ast.UnconvertedDataType{}
- }
- s := name.String_.Sval
- switch {
- case strings.HasPrefix(s, "int"):
- size, err := strconv.Atoi(s[3:])
- if err != nil {
- return convertToUnconvertedDataType(tp)
- }
- return &ast.Integer{Size: size}
- case strings.HasPrefix(s, "float"):
- size, err := strconv.Atoi(s[5:])
- if err != nil {
- return convertToUnconvertedDataType(tp)
- }
- return &ast.Float{Size: size}
- case s == "serial":
- return &ast.Serial{Size: 4}
- case s == "smallserial":
- return &ast.Serial{Size: 2}
- case s == "bigserial":
- return &ast.Serial{Size: 8}
- case strings.HasPrefix(s, "serial"):
- size, err := strconv.Atoi(s[6:])
- if err != nil {
- return convertToUnconvertedDataType(tp)
- }
- return &ast.Serial{Size: size}
- case s == "numeric":
- return convertToDecimal(tp.Typmods)
- case s == "bpchar":
- return convertToCharacter(tp.Typmods)
- case s == "varchar":
- return convertToVarchar(tp.Typmods)
- case s == "text":
- return &ast.Text{}
- case s == "json":
- return &ast.JSON{}
- case s == "jsonb":
- return &ast.JSON{JSONB: true}
- default:
- // Other data types
- }
- }
- return convertToUnconvertedDataType(tp)
- }()
-
- // For UnconvertedDataType, we use the text deparsed by pg_query_go
- if _, ok := dataType.(*ast.UnconvertedDataType); ok {
- dataType.SetText(text)
- }
- return dataType, nil
-}
-
-func convertToUnconvertedDataType(tp *pgquery.TypeName) ast.DataType {
- res := &ast.UnconvertedDataType{}
- for _, name := range tp.Names {
- s, ok := name.Node.(*pgquery.Node_String_)
- if !ok {
- return &ast.UnconvertedDataType{}
- }
- res.Name = append(res.Name, s.String_.Sval)
- }
- return res
-}
-
-func convertToDecimal(typmods []*pgquery.Node) ast.DataType {
- ok := false
- decimal := &ast.Decimal{}
- switch len(typmods) {
- case 0:
- return decimal
- case 1:
- if decimal.Precision, ok = convertToInteger(typmods[0]); !ok {
- return &ast.UnconvertedDataType{}
- }
- return decimal
- case 2:
- if decimal.Precision, ok = convertToInteger(typmods[0]); !ok {
- return &ast.UnconvertedDataType{}
- }
- if decimal.Scale, ok = convertToInteger(typmods[1]); !ok {
- return &ast.UnconvertedDataType{}
- }
- return decimal
- default:
- return &ast.UnconvertedDataType{}
- }
-}
-
-func convertToVarchar(typmods []*pgquery.Node) ast.DataType {
- if len(typmods) != 1 {
- return &ast.UnconvertedDataType{}
- }
- size, ok := convertToInteger(typmods[0])
- if !ok {
- return &ast.UnconvertedDataType{}
- }
- return &ast.CharacterVarying{Size: size}
-}
-
-func convertToCharacter(typmods []*pgquery.Node) ast.DataType {
- if len(typmods) != 1 {
- return &ast.UnconvertedDataType{}
- }
- size, ok := convertToInteger(typmods[0])
- if !ok {
- return &ast.UnconvertedDataType{}
- }
- return &ast.Character{Size: size}
-}
-
-func convertToInteger(in *pgquery.Node) (int, bool) {
- aConst, ok := in.Node.(*pgquery.Node_AConst)
- if !ok {
- return 0, false
- }
- integer, ok := aConst.AConst.Val.(*pgquery.A_Const_Ival)
- if !ok {
- return 0, false
- }
- return int(integer.Ival.Ival), true
-}
-
-func convertDefElemNodeListToColumnNameDef(defElem *pgquery.DefElem) (*ast.ColumnNameDef, error) {
- listNode, ok := defElem.Arg.Node.(*pgquery.Node_List)
- if !ok {
- return nil, NewConvertErrorf("expected List but found %T", defElem.Arg.Node)
- }
- return ConvertNodeListToColumnNameDef(listNode.List.Items)
-}
-
-func convertDefElemNodeIntegerToBool(defElem *pgquery.DefElem) (bool, error) {
- if defElem.Arg == nil {
- return false, nil
- }
- switch node := defElem.Arg.Node.(type) {
- case *pgquery.Node_Integer:
- return node.Integer.Ival == 1, nil
- case *pgquery.Node_Boolean:
- return node.Boolean.Boolval, nil
- default:
- return false, NewConvertErrorf("expected integer or boolean but found %T", defElem.Arg.Node)
- }
-}
-
-func convertDefElemNodeIntegerToInt64(defElem *pgquery.DefElem) (*int64, error) {
- if defElem.Arg == nil {
- return nil, nil
- }
- switch node := defElem.Arg.Node.(type) {
- case *pgquery.Node_Integer:
- val := int64(node.Integer.Ival)
- return &val, nil
- case *pgquery.Node_Float:
- float, err := strconv.ParseFloat(node.Float.Fval, 64)
- if err != nil {
- return nil, errors.Wrap(err, "failed to parse float")
- }
- val := int64(float)
- return &val, nil
- default:
- return nil, NewConvertErrorf("failed to convert DefElemNode:expected integer or float but found %T", defElem.Arg.Node)
- }
-}
-
-func convertDefElemToSeqType(defElem *pgquery.DefElem) (*ast.Integer, error) {
- typeNameNode, ok := defElem.Arg.Node.(*pgquery.Node_TypeName)
- if !ok {
- return nil, NewConvertErrorf("expected TypeName but found %T", defElem.Arg.Node)
- }
- if len(typeNameNode.TypeName.Names) != 2 {
- return nil, NewConvertErrorf("expected TypeName with 2 names but found %d", len(typeNameNode.TypeName.Names))
- }
- dataType, err := convertDataType(typeNameNode.TypeName)
- if err != nil {
- return nil, err
- }
- // Sequence type should be int2(smallint), int4(integer), or int8(bigint)
- intType, ok := dataType.(*ast.Integer)
- if !ok {
- return nil, NewConvertErrorf("expected Integer but found %T", dataType)
- }
- if intType.Size != 2 && intType.Size != 4 && intType.Size != 8 {
- return nil, NewConvertErrorf("expected Integer with size 2, 4, or 8 but found %d", intType.Size)
- }
- return intType, nil
-}
-
-// ConvertNodeListToColumnNameDef converts the node list to ColumnNameDef.
-func ConvertNodeListToColumnNameDef(in []*pgquery.Node) (*ast.ColumnNameDef, error) {
- columnName := &ast.ColumnNameDef{Table: &ast.TableDef{}}
- // There are four cases for column name:
- // 0. dbName.schemaName.tableName.columnName
- // 1. schemaName.tableName.columnName
- // 2. tableName.columnName
- // 3. columnName
- // The pg parser will split them by ".", and use a list to define it.
- // So we need to consider this three cases.
- switch len(in) {
- // dbName.schemaName.tableName.columnName
- case 4:
- dbName, ok := in[0].Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %T", in[0].Node)
- }
- columnName.Table.Database = dbName.String_.Sval
- // need to convert schemaName.tableName.columnName
- in = in[1:]
- fallthrough
- // schemaName.tableName.columnName
- case 3:
- schema, ok := in[0].Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %T", in[0].Node)
- }
- columnName.Table.Schema = schema.String_.Sval
- // need to convert tableName.columnName
- in = in[1:]
- fallthrough
- // tableName.columnName
- case 2:
- table, ok := in[0].Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %T", in[0].Node)
- }
- columnName.Table.Name = table.String_.Sval
- // need to convert columnName
- in = in[1:]
- fallthrough
- // columnName
- case 1:
- switch column := in[0].Node.(type) {
- // column name
- case *pgquery.Node_String_:
- columnName.ColumnName = column.String_.Sval
- // e.g. SELECT * FROM t;
- case *pgquery.Node_AStar:
- columnName.ColumnName = "*"
- default:
- return nil, NewConvertErrorf("expected String or AStar but found %T", in[0].Node)
- }
- default:
- return nil, NewConvertErrorf("failed to convert ColumnRef, column name contains unexpected components: %v", in)
- }
- return columnName, nil
-}
-
-func convertNodeListToTableDef(in []*pgquery.Node) (*ast.TableDef, error) {
- tableDef := &ast.TableDef{
- Type: ast.TableTypeUnknown,
- }
- switch len(in) {
- case 2:
- schema, ok := in[0].Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", in[0].Node)
- }
- tableDef.Schema = schema.String_.Sval
- in = in[1:]
- fallthrough
- case 1:
- table, ok := in[0].Node.(*pgquery.Node_String_)
- if !ok {
- return nil, NewConvertErrorf("expected String but found %t", in[0].Node)
- }
- tableDef.Name = table.String_.Sval
- default:
- return nil, NewConvertErrorf("failed to convert RangeVar, table name contains unexpected components: %v", in)
- }
- return tableDef, nil
-}
diff --git a/backend/plugin/parser/pg/legacy/convert_test.go b/backend/plugin/parser/pg/legacy/convert_test.go
deleted file mode 100644
index 8dd18b241c..0000000000
--- a/backend/plugin/parser/pg/legacy/convert_test.go
+++ /dev/null
@@ -1,3664 +0,0 @@
-package legacy
-
-import (
- "encoding/json"
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-
- pgquery "github.com/pganalyze/pg_query_go/v6"
-)
-
-type testData struct {
- stmt string
- want []ast.Node
- statementList []base.SingleSQL
- columnLine [][]int
- constraintLine [][]int
-}
-
-func runTests(t *testing.T, tests []testData) {
- for _, test := range tests {
- res, err := Parse(ParseContext{}, test.stmt)
- require.NoError(t, err)
- for i := range test.want {
- test.want[i].SetText(test.statementList[i].Text)
- test.want[i].SetLastLine(int(test.statementList[i].End.Line))
-
- switch n := test.want[i].(type) {
- case *ast.CreateTableStmt:
- for j, col := range n.ColumnList {
- col.SetLastLine(test.columnLine[i][j])
- for _, inlineCons := range col.ConstraintList {
- inlineCons.SetLastLine(col.LastLine())
- }
- }
- for j, cons := range n.ConstraintList {
- cons.SetLastLine(test.constraintLine[i][j])
- }
- case *ast.AlterTableStmt:
- for _, item := range n.AlterItemList {
- item.SetLastLine(n.LastLine())
- }
- }
- }
- wantJSON, err := json.Marshal(test.want)
- require.NoError(t, err)
- gotJSON, err := json.Marshal(res)
- require.NoError(t, err)
- require.Equal(t, string(wantJSON), string(gotJSON), test.stmt)
- }
-}
-
-func newUnconvertedDataType(name []string, text string) *ast.UnconvertedDataType {
- tp := &ast.UnconvertedDataType{Name: name}
- tp.SetText(text)
- return tp
-}
-
-func newExpression(expression ast.ExpressionNode, text string) ast.ExpressionNode {
- expression.SetText(text)
- return expression
-}
-
-func TestPGConvertCreateMaterializedViewStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: `CREATE MATERIALIZED VIEW tech_book(a, b) AS SELECT * FROM book`,
- want: []ast.Node{
- &ast.CreateMaterializedViewStmt{
- Name: &ast.TableDef{
- Type: ast.TableTypeMaterializedView,
- Name: "tech_book",
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE MATERIALIZED VIEW tech_book(a, b) AS SELECT * FROM book`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGVariableShowStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: `SHOW TIME ZONE`,
- want: []ast.Node{
- &ast.VariableShowStmt{
- Name: "timezone",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `SHOW TIME ZONE`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
-
- {
- stmt: `SHOW myvar`,
- want: []ast.Node{
- &ast.VariableShowStmt{
- Name: "myvar",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `SHOW myvar`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGConvertCreateViewStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: `CREATE VIEW tech_book(a, b) AS SELECT * FROM book`,
- want: []ast.Node{
- &ast.CreateViewStmt{
- Name: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "tech_book",
- },
- Aliases: []string{"a", "b"},
- Select: &ast.SelectStmt{
- FieldList: []ast.ExpressionNode{
- newExpression(
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- }, "*"),
- },
- },
- Replace: false,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE VIEW tech_book(a, b) AS SELECT * FROM book`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGConvertCreateTableStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: `
- CREATE TABLE tech_book(
- a int,
- b int,
- c text COLLATE public."de_DE"
- )
- PARTITION BY RANGE (a, (a+1))
- `,
- want: []ast.Node{
- &ast.CreateTableStmt{
- IfNotExists: false,
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "b",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "c",
- Type: &ast.Text{},
- Collation: &ast.CollationNameDef{
- Schema: "public",
- Name: "de_DE",
- },
- },
- },
- PartitionDef: &ast.PartitionDef{
- Strategy: pgquery.PartitionStrategy_PARTITION_STRATEGY_RANGE,
- KeyList: []*ast.PartitionKeyDef{
- {
- Type: ast.PartitionKeyTypeColumn,
- Key: "a",
- },
- {
- Type: ast.PartitionKeyTypeExpression,
- Key: "a + 1",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE TABLE tech_book(
- a int,
- b int,
- c text COLLATE public."de_DE"
- )
- PARTITION BY RANGE (a, (a+1))`,
- End: &store.Position{Line: 7, Column: 0},
- },
- },
- columnLine: [][]int{
- {3, 4, 5},
- },
- },
- {
- stmt: `
- CREATE TABLE tech_book(
- a char(20),
- b character(30),
- c varchar(330),
- d character varying(400),
- e text
- )
- `,
- want: []ast.Node{
- &ast.CreateTableStmt{
- IfNotExists: false,
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Character{Size: 20},
- },
- {
- ColumnName: "b",
- Type: &ast.Character{Size: 30},
- },
- {
- ColumnName: "c",
- Type: &ast.CharacterVarying{Size: 330},
- },
- {
- ColumnName: "d",
- Type: &ast.CharacterVarying{Size: 400},
- },
- {
- ColumnName: "e",
- Type: &ast.Text{},
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE TABLE tech_book(
- a char(20),
- b character(30),
- c varchar(330),
- d character varying(400),
- e text
- )`,
- End: &store.Position{Line: 8, Column: 0},
- },
- },
- columnLine: [][]int{
- {3, 4, 5, 6, 7},
- },
- },
- {
- stmt: `CREATE TABLE tech_book(
- a smallint,
- b integer,
- c bigint,
- d decimal(10, 2),
- e numeric(4),
- f real,
- g double precision,
- h smallserial,
- i serial,
- j bigserial,
- k int8,
- l serial8,
- m float8,
- n int,
- o int4,
- p float4,
- q int2,
- r serial2,
- s serial4,
- t decimal,
- u "user defined data type")`,
- want: []ast.Node{
- &ast.CreateTableStmt{
- IfNotExists: false,
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 2},
- },
- {
- ColumnName: "b",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "c",
- Type: &ast.Integer{Size: 8},
- },
- {
- ColumnName: "d",
- Type: &ast.Decimal{Precision: 10, Scale: 2},
- },
- {
- ColumnName: "e",
- Type: &ast.Decimal{Precision: 4, Scale: 0},
- },
- {
- ColumnName: "f",
- Type: &ast.Float{Size: 4},
- },
- {
- ColumnName: "g",
- Type: &ast.Float{Size: 8},
- },
- {
- ColumnName: "h",
- Type: &ast.Serial{Size: 2},
- },
- {
- ColumnName: "i",
- Type: &ast.Serial{Size: 4},
- },
- {
- ColumnName: "j",
- Type: &ast.Serial{Size: 8},
- },
- {
- ColumnName: "k",
- Type: &ast.Integer{Size: 8},
- },
- {
- ColumnName: "l",
- Type: &ast.Serial{Size: 8},
- },
- {
- ColumnName: "m",
- Type: &ast.Float{Size: 8},
- },
- {
- ColumnName: "n",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "o",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "p",
- Type: &ast.Float{Size: 4},
- },
- {
- ColumnName: "q",
- Type: &ast.Integer{Size: 2},
- },
- {
- ColumnName: "r",
- Type: &ast.Serial{Size: 2},
- },
- {
- ColumnName: "s",
- Type: &ast.Serial{Size: 4},
- },
- {
- ColumnName: "t",
- Type: &ast.Decimal{Precision: 0, Scale: 0},
- },
- {
- ColumnName: "u",
- Type: newUnconvertedDataType([]string{"user defined data type"}, `"user defined data type"`),
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE TABLE tech_book(
- a smallint,
- b integer,
- c bigint,
- d decimal(10, 2),
- e numeric(4),
- f real,
- g double precision,
- h smallserial,
- i serial,
- j bigserial,
- k int8,
- l serial8,
- m float8,
- n int,
- o int4,
- p float4,
- q int2,
- r serial2,
- s serial4,
- t decimal,
- u "user defined data type")`,
- End: &store.Position{Line: 22, Column: 0},
- },
- },
- columnLine: [][]int{
- {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22},
- },
- },
- {
- stmt: "CREATE TABLE \"techBook\" (a int NOT NULL, b int CONSTRAINT b_not_null NOT NULL, c int NULL)",
- want: []ast.Node{
- &ast.CreateTableStmt{
- IfNotExists: false,
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techBook",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeNotNull,
- KeyList: []string{"a"},
- },
- },
- },
- {
- ColumnName: "b",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeNotNull,
- Name: "b_not_null",
- KeyList: []string{"b"},
- },
- },
- },
- {
- ColumnName: "c",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeNull,
- KeyList: []string{"c"},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE TABLE \"techBook\" (a int NOT NULL, b int CONSTRAINT b_not_null NOT NULL, c int NULL)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- columnLine: [][]int{
- {1, 1, 1},
- },
- },
- {
- stmt: "CREATE TABLE IF NOT EXISTS techBook (\"A\" int, b int DEFAULT 1+2+3-4+5)",
- want: []ast.Node{
- &ast.CreateTableStmt{
- IfNotExists: true,
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "A",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "b",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeDefault,
- KeyList: []string{"b"},
- Expression: expressionWithText(&ast.UnconvertedExpressionDef{}, "(((1 + 2) + 3) - 4) + 5"),
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE TABLE IF NOT EXISTS techBook (\"A\" int, b int DEFAULT 1+2+3-4+5)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- columnLine: [][]int{
- {1, 1},
- },
- },
- {
- stmt: "CREATE TABLE tech_book(a INT CONSTRAINT t_pk_a PRIMARY KEY)",
- want: []ast.Node{
- &ast.CreateTableStmt{
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Name: "t_pk_a",
- Type: ast.ConstraintTypePrimary,
- KeyList: []string{"a"},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE TABLE tech_book(a INT CONSTRAINT t_pk_a PRIMARY KEY)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- columnLine: [][]int{
- {1},
- },
- },
- {
- stmt: "CREATE TABLE tech_book(a INT, b int CONSTRAINT uk_b UNIQUE, CONSTRAINT t_pk_a PRIMARY KEY(a))",
- want: []ast.Node{
- &ast.CreateTableStmt{
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- },
- {
- ColumnName: "b",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Name: "uk_b",
- Type: ast.ConstraintTypeUnique,
- KeyList: []string{"b"},
- },
- },
- },
- },
- ConstraintList: []*ast.ConstraintDef{
- {
- Name: "t_pk_a",
- Type: ast.ConstraintTypePrimary,
- KeyList: []string{"a"},
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE TABLE tech_book(a INT, b int CONSTRAINT uk_b UNIQUE, CONSTRAINT t_pk_a PRIMARY KEY(a))",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- columnLine: [][]int{
- {1, 1},
- },
- constraintLine: [][]int{
- {1},
- },
- },
- {
- stmt: "CREATE TABLE tech_book(a INT CONSTRAINT fk_a REFERENCES people(id), CONSTRAINT fk_a_people_b FOREIGN KEY (a) REFERENCES people(b))",
- want: []ast.Node{
- &ast.CreateTableStmt{
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Name: "fk_a",
- Type: ast.ConstraintTypeForeign,
- KeyList: []string{"a"},
- Foreign: &ast.ForeignDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "people",
- },
- ColumnList: []string{"id"},
- MatchType: ast.ForeignMatchTypeSimple,
- OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- },
- },
- },
- },
- },
- ConstraintList: []*ast.ConstraintDef{
- {
- Name: "fk_a_people_b",
- Type: ast.ConstraintTypeForeign,
- KeyList: []string{"a"},
- Foreign: &ast.ForeignDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "people",
- },
- ColumnList: []string{"b"},
- MatchType: ast.ForeignMatchTypeSimple,
- OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE TABLE tech_book(a INT CONSTRAINT fk_a REFERENCES people(id), CONSTRAINT fk_a_people_b FOREIGN KEY (a) REFERENCES people(b))",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- columnLine: [][]int{
- {1},
- },
- constraintLine: [][]int{
- {1},
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGAddColumnStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE techbook ADD COLUMN IF NOT EXISTS a int",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.AddColumnListStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- IfNotExists: true,
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE techbook ADD COLUMN IF NOT EXISTS a int",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE techbook ADD COLUMN a int CONSTRAINT uk_techbook_a UNIQUE",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.AddColumnListStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Integer{Size: 4},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeUnique,
- Name: "uk_techbook_a",
- KeyList: []string{"a"},
- },
- },
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE techbook ADD COLUMN a int CONSTRAINT uk_techbook_a UNIQUE",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE techbook ADD COLUMN a text default current_user",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.AddColumnListStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Text{},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeDefault,
- KeyList: []string{"a"},
- Expression: &ast.UnconvertedExpressionDef{},
- },
- },
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE techbook ADD COLUMN a text default current_user",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE techbook ADD COLUMN a text default now()",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.AddColumnListStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "a",
- Type: &ast.Text{},
- ConstraintList: []*ast.ConstraintDef{
- {
- Type: ast.ConstraintTypeDefault,
- KeyList: []string{"a"},
- Expression: &ast.UnconvertedExpressionDef{},
- },
- },
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE techbook ADD COLUMN a text default now()",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGRenameTableStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE techbook RENAME TO \"techBook\"",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.RenameTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- NewName: "techBook",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE techbook RENAME TO \"techBook\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER VIEW techbook RENAME TO \"techBook\"",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.RenameTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "techbook",
- },
- NewName: "techBook",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER VIEW techbook RENAME TO \"techBook\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGRenameColumnStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE techbook RENAME abc TO \"ABC\"",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.RenameColumnStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "techbook",
- },
- ColumnName: "abc",
- NewName: "ABC",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE techbook RENAME abc TO \"ABC\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER VIEW techbook RENAME abc TO \"ABC\"",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "techbook",
- },
- AlterItemList: []ast.Node{
- &ast.RenameColumnStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "techbook",
- },
- ColumnName: "abc",
- NewName: "ABC",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER VIEW techbook RENAME abc TO \"ABC\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGRenameConstraintStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book RENAME CONSTRAINT uk_tech_a to \"UK_TECH_A\"",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.RenameConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ConstraintName: "uk_tech_a",
- NewName: "UK_TECH_A",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book RENAME CONSTRAINT uk_tech_a to \"UK_TECH_A\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGCreateIndexStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",
- want: []ast.Node{
- &ast.CreateIndexStmt{
- IfNotExists: true,
- Concurrently: true,
- Index: &ast.IndexDef{
- Name: "idx_id",
- Table: &ast.TableDef{Name: "tech_book"},
- Unique: false,
- KeyList: []*ast.IndexKeyDef{
- {
- Type: ast.IndexKeyTypeExpression,
- Key: "id + 1",
- SortOrder: ast.SortOrderTypeDescending,
- NullOrder: ast.NullOrderTypeDefault,
- },
- {
- Type: ast.IndexKeyTypeColumn,
- Key: "name",
- SortOrder: ast.NullOrderTypeDefault,
- NullOrder: ast.NullOrderTypeDefault,
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "CREATE INDEX idx_id ON tech_book (id ASC NULLS FIRST)",
- want: []ast.Node{
- &ast.CreateIndexStmt{
- Index: &ast.IndexDef{
- Name: "idx_id",
- Table: &ast.TableDef{Name: "tech_book"},
- Unique: false,
- KeyList: []*ast.IndexKeyDef{
- {
- Type: ast.IndexKeyTypeColumn,
- Key: "id",
- SortOrder: ast.SortOrderTypeAscending,
- NullOrder: ast.NullOrderTypeFirst,
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE INDEX idx_id ON tech_book (id ASC NULLS FIRST)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "CREATE UNIQUE INDEX idx_id ON tech_book (id NULLS LAST)",
- want: []ast.Node{
- &ast.CreateIndexStmt{
- Index: &ast.IndexDef{
- Name: "idx_id",
- Table: &ast.TableDef{Name: "tech_book"},
- Unique: true,
- KeyList: []*ast.IndexKeyDef{
- {
- Type: ast.IndexKeyTypeColumn,
- Key: "id",
- SortOrder: ast.NullOrderTypeDefault,
- NullOrder: ast.NullOrderTypeLast,
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "CREATE UNIQUE INDEX idx_id ON tech_book (id NULLS LAST)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGDropIndexStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "DROP INDEX xschema.idx_id, idx_x",
- want: []ast.Node{
- &ast.DropIndexStmt{
- IfExists: false,
- Behavior: ast.DropBehaviorRestrict,
- IndexList: []*ast.IndexDef{
- {
- Table: &ast.TableDef{Schema: "xschema"},
- Name: "idx_id",
- },
- {Name: "idx_x"},
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP INDEX xschema.idx_id, idx_x",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DROP INDEX xschema.idx_id, idx_x restrict",
- want: []ast.Node{
- &ast.DropIndexStmt{
- IfExists: false,
- Behavior: ast.DropBehaviorRestrict,
- IndexList: []*ast.IndexDef{
- {
- Table: &ast.TableDef{Schema: "xschema"},
- Name: "idx_id",
- },
- {Name: "idx_x"},
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP INDEX xschema.idx_id, idx_x restrict",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DROP INDEX IF EXISTS xschema.idx_id, idx_x cascade",
- want: []ast.Node{
- &ast.DropIndexStmt{
- IfExists: true,
- Behavior: ast.DropBehaviorCascade,
- IndexList: []*ast.IndexDef{
- {
- Table: &ast.TableDef{Schema: "xschema"},
- Name: "idx_id",
- },
- {Name: "idx_x"},
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP INDEX IF EXISTS xschema.idx_id, idx_x cascade",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGAlterIndexStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER INDEX xschema.idx_id RENAME TO \"IDX_ID\"",
- want: []ast.Node{
- &ast.RenameIndexStmt{
- Table: &ast.TableDef{Schema: "xschema"},
- IndexName: "idx_id",
- NewName: "IDX_ID",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER INDEX xschema.idx_id RENAME TO \"IDX_ID\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER INDEX idx_id RENAME TO \"IDX_ID\"",
- want: []ast.Node{
- &ast.RenameIndexStmt{
- Table: &ast.TableDef{Schema: ""},
- IndexName: "idx_id",
- NewName: "IDX_ID",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER INDEX idx_id RENAME TO \"IDX_ID\"",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGDropConstraintStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book DROP CONSTRAINT uk_tech_a",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.DropConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ConstraintName: "uk_tech_a",
- IfExists: false,
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book DROP CONSTRAINT uk_tech_a",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book DROP CONSTRAINT IF EXISTS uk_tech_a",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.DropConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ConstraintName: "uk_tech_a",
- IfExists: true,
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book DROP CONSTRAINT IF EXISTS uk_tech_a",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func expressionWithText(expression ast.ExpressionNode, text string) ast.ExpressionNode {
- expression.SetText(text)
- return expression
-}
-
-func TestPGAddConstraintStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeForeign,
- Name: "fk_tech_book_id",
- KeyList: []string{"id"},
- Foreign: &ast.ForeignDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "people",
- },
- ColumnList: []string{"id"},
- MatchType: ast.ForeignMatchTypeSimple,
- OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH FULL ON UPDATE CASCADE ON DELETE SET DEFAULT",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeForeign,
- Name: "fk_tech_book_id",
- KeyList: []string{"id"},
- Foreign: &ast.ForeignDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "people",
- },
- ColumnList: []string{"id"},
- MatchType: ast.ForeignMatchTypeFull,
- OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeCascade},
- OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetDefault},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH FULL ON UPDATE CASCADE ON DELETE SET DEFAULT",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE SET NULL",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeForeign,
- Name: "fk_tech_book_id",
- KeyList: []string{"id"},
- Foreign: &ast.ForeignDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "people",
- },
- ColumnList: []string{"id"},
- MatchType: ast.ForeignMatchTypeSimple,
- OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeRestrict},
- OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeSetNull},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE SET NULL",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT check_a_bigger_than_b CHECK (a > b) NOT VALID",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeCheck,
- Name: "check_a_bigger_than_b",
- SkipValidation: true,
- Expression: expressionWithText(&ast.UnconvertedExpressionDef{}, "a > b"),
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT check_a_bigger_than_b CHECK (a > b) NOT VALID",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT uk_tech_book_id UNIQUE (id)",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeUnique,
- Name: "uk_tech_book_id",
- KeyList: []string{"id"},
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT uk_tech_book_id UNIQUE (id)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE ONLY s.person ADD CONSTRAINT person_email_email1_key UNIQUE (email) INCLUDE (email) USING INDEX TABLESPACE demo_table_space;",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Schema: "s",
- Name: "person",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Schema: "s",
- Name: "person",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeUnique,
- Name: "person_email_email1_key",
- KeyList: []string{"email"},
- Including: []string{"email"},
- IndexTableSpace: "demo_table_space",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE ONLY s.person ADD CONSTRAINT person_email_email1_key UNIQUE (email) INCLUDE (email) USING INDEX TABLESPACE demo_table_space;",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book_id PRIMARY KEY (id)",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypePrimary,
- Name: "pk_tech_book_id",
- KeyList: []string{"id"},
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book_id PRIMARY KEY (id)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id)",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeForeign,
- Name: "fk_tech_book_id",
- KeyList: []string{"id"},
- Foreign: &ast.ForeignDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "people",
- },
- ColumnList: []string{"id"},
- MatchType: ast.ForeignMatchTypeSimple,
- OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_id FOREIGN KEY (id) REFERENCES people(id)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT uk_tech_book_id UNIQUE USING INDEX uk_id",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeUniqueUsingIndex,
- Name: "uk_tech_book_id",
- IndexName: "uk_id",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT uk_tech_book_id UNIQUE USING INDEX uk_id",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book_id PRIMARY KEY USING INDEX pk_id",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypePrimaryUsingIndex,
- Name: "pk_tech_book_id",
- IndexName: "pk_id",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book_id PRIMARY KEY USING INDEX pk_id",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE ONLY circles ADD CONSTRAINT circles_c_excl EXCLUDE USING gist (c WITH &&, d WITH &&) WHERE (a > 0);",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "circles",
- },
- AlterItemList: []ast.Node{
- &ast.AddConstraintStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "circles",
- },
- Constraint: &ast.ConstraintDef{
- Type: ast.ConstraintTypeExclusion,
- Name: "circles_c_excl",
- Exclusions: "c WITH &&, d WITH &&",
- AccessMethod: ast.IndexMethodTypeGiST,
- WhereClause: "a > 0",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE ONLY circles ADD CONSTRAINT circles_c_excl EXCLUDE USING gist (c WITH &&, d WITH &&) WHERE (a > 0);",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGDropColumnStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book DROP COLUMN IF EXISTS a CASCADE",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.DropColumnStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnName: "a",
- IfExists: true,
- Behavior: ast.DropBehaviorCascade,
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book DROP COLUMN IF EXISTS a CASCADE",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGDropTableStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "DROP TABLE IF EXISTS tech_book, xschema.user CASCADE",
- want: []ast.Node{
- &ast.DropTableStmt{
- IfExists: true,
- Behavior: ast.DropBehaviorCascade,
- TableList: []*ast.TableDef{
- {
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- {
- Type: ast.TableTypeBaseTable,
- Schema: "xschema",
- Name: "user",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP TABLE IF EXISTS tech_book, xschema.user CASCADE",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DROP VIEW tech_book, xschema.user RESTRICT",
- want: []ast.Node{
- &ast.DropTableStmt{
- Behavior: ast.DropBehaviorRestrict,
- TableList: []*ast.TableDef{
- {
- Type: ast.TableTypeView,
- Name: "tech_book",
- },
- {
- Type: ast.TableTypeView,
- Schema: "xschema",
- Name: "user",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP VIEW tech_book, xschema.user RESTRICT",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGNotNullStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book ALTER COLUMN id SET NOT NULL",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.SetNotNullStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnName: "id",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ALTER COLUMN id SET NOT NULL",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ALTER COLUMN id DROP NOT NULL",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.DropNotNullStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnName: "id",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ALTER COLUMN id DROP NOT NULL",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGSelectStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "SELECT public.t.a, t.*, t1.* FROM (SELECT * FROM t) t, t1 ORDER BY t.a, random()",
- want: []ast.Node{
- &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{
- Schema: "public",
- Name: "t",
- },
- ColumnName: "a",
- },
- &ast.ColumnNameDef{
- Table: &ast.TableDef{Name: "t"},
- ColumnName: "*",
- },
- &ast.ColumnNameDef{
- Table: &ast.TableDef{Name: "t1"},
- ColumnName: "*",
- },
- },
- OrderByClause: []*ast.ByItemDef{
- {
- Expression: newExpression(&ast.ColumnNameDef{
- Table: &ast.TableDef{Name: "t"},
- ColumnName: "a",
- }, "t.a"),
- },
- {
- Expression: newExpression(&ast.UnconvertedExpressionDef{}, "random()"),
- },
- },
- SubqueryList: []*ast.SubqueryDef{
- {
- Select: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "SELECT public.t.a, t.*, t1.* FROM (SELECT * FROM t) t, t1 ORDER BY t.a, random()",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "SELECT public.t.a, t.*, * FROM t",
- want: []ast.Node{
- &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{
- Schema: "public",
- Name: "t",
- },
- ColumnName: "a",
- },
- &ast.ColumnNameDef{
- Table: &ast.TableDef{Name: "t"},
- ColumnName: "*",
- },
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "SELECT public.t.a, t.*, * FROM t",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: `
- SELECT
- public.t.a, b, lower(a), b>a
- FROM
- t
- WHERE
- a > 0
- AND (c not LIKE 'xyz' or true)
- AND b LIKE '%csdbc'
- AND a in
- (SELECT * FROM t1 WHERE x LIKE b)
- UNION
- SELECT * FROM t`,
- want: []ast.Node{
- &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeUnion,
- LQuery: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{
- Schema: "public",
- Name: "t",
- },
- ColumnName: "a",
- },
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "b",
- },
- &ast.UnconvertedExpressionDef{},
- &ast.UnconvertedExpressionDef{},
- },
- WhereClause: &ast.UnconvertedExpressionDef{},
- PatternLikeList: []*ast.PatternLikeDef{
- {
- Not: true,
- Expression: &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "c",
- },
- Pattern: &ast.StringDef{Value: "xyz"},
- },
- {
- Expression: &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "b",
- },
- Pattern: &ast.StringDef{Value: "%csdbc"},
- },
- },
- SubqueryList: []*ast.SubqueryDef{
- {
- Select: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- WhereClause: &ast.PatternLikeDef{
- Expression: &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "x",
- },
- Pattern: &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "b",
- },
- },
- PatternLikeList: []*ast.PatternLikeDef{
- {
- Expression: &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "x",
- },
- Pattern: &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "b",
- },
- },
- },
- },
- },
- },
- },
- RQuery: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `SELECT
- public.t.a, b, lower(a), b>a
- FROM
- t
- WHERE
- a > 0
- AND (c not LIKE 'xyz' or true)
- AND b LIKE '%csdbc'
- AND a in
- (SELECT * FROM t1 WHERE x LIKE b)
- UNION
- SELECT * FROM t`,
- End: &store.Position{Line: 13, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestPGDropDatabaseStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "DROP DATABASE test",
- want: []ast.Node{
- &ast.DropDatabaseStmt{
- DatabaseName: "test",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP DATABASE test",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DROP DATABASE IF EXISTS test",
- want: []ast.Node{
- &ast.DropDatabaseStmt{
- DatabaseName: "test",
- IfExists: true,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP DATABASE IF EXISTS test",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestUpdateStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "UPDATE tech_book SET a = 1 FROM (SELECT * FROM t) t WHERE a > 1",
- want: []ast.Node{
- &ast.UpdateStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- WhereClause: &ast.UnconvertedExpressionDef{},
- SubqueryList: []*ast.SubqueryDef{
- {
- Select: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "UPDATE tech_book SET a = 1 FROM (SELECT * FROM t) t WHERE a > 1",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "UPDATE tech_book SET a = 1",
- want: []ast.Node{
- &ast.UpdateStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "UPDATE tech_book SET a = 1",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "UPDATE tech_book SET a = 1 WHERE a > 1",
- want: []ast.Node{
- &ast.UpdateStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- WhereClause: &ast.UnconvertedExpressionDef{},
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "UPDATE tech_book SET a = 1 WHERE a > 1",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-func TestDeleteStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "DELETE FROM tech_book",
- want: []ast.Node{
- &ast.DeleteStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DELETE FROM tech_book",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DELETE FROM tech_book WHERE a > 1",
- want: []ast.Node{
- &ast.DeleteStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- WhereClause: &ast.UnconvertedExpressionDef{},
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DELETE FROM tech_book WHERE a > 1",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestSetSchemaStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book SET SCHEMA new_schema",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.SetSchemaStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- NewSchema: "new_schema",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book SET SCHEMA new_schema",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER VIEW tech_book SET SCHEMA new_schema",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.SetSchemaStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeView,
- Name: "tech_book",
- },
- NewSchema: "new_schema",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER VIEW tech_book SET SCHEMA new_schema",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestExplainStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "EXPLAIN SELECT * FROM tech_book",
- want: []ast.Node{
- &ast.ExplainStmt{
- Statement: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- },
- Analyze: false,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "EXPLAIN SELECT * FROM tech_book",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "EXPLAIN ANALYZE SELECT * FROM tech_book",
- want: []ast.Node{
- &ast.ExplainStmt{
- Statement: &ast.SelectStmt{
- SetOperation: ast.SetOperationTypeNone,
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- },
- Analyze: true,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "EXPLAIN ANALYZE SELECT * FROM tech_book",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestAlterColumnType(t *testing.T) {
- tests := []testData{
- {
- stmt: `ALTER TABLE tech_book ALTER COLUMN a TYPE TEXT COLLATE "en_EN"`,
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AlterColumnTypeStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnName: "a",
- Type: &ast.Text{},
- Collation: &ast.CollationNameDef{
- Name: "en_EN",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `ALTER TABLE tech_book ALTER COLUMN a TYPE TEXT COLLATE "en_EN"`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestInsertStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "INSERT INTO tech_book(a, b) VALUES (1, 'a'), (2, 'b')",
- want: []ast.Node{
- &ast.InsertStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnList: []string{
- "a",
- "b",
- },
- ValueList: [][]ast.ExpressionNode{
- {
- &ast.IntegerDef{
- Value: 1,
- },
- &ast.StringDef{
- Value: "a",
- },
- },
- {
- &ast.IntegerDef{
- Value: 2,
- },
- &ast.StringDef{
- Value: "b",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "INSERT INTO tech_book(a, b) VALUES (1, 'a'), (2, 'b')",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "INSERT INTO tech_book SELECT * FROM book WHERE type='tech'",
- want: []ast.Node{
- &ast.InsertStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Select: &ast.SelectStmt{
- FieldList: []ast.ExpressionNode{
- &ast.ColumnNameDef{
- Table: &ast.TableDef{},
- ColumnName: "*",
- },
- },
- WhereClause: &ast.UnconvertedExpressionDef{},
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "INSERT INTO tech_book SELECT * FROM book WHERE type='tech'",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "INSERT INTO tech_book VALUES(1, 2, 3, 4, 5)",
- want: []ast.Node{
- &ast.InsertStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ValueList: [][]ast.ExpressionNode{
- {
- &ast.IntegerDef{
- Value: 1,
- },
- &ast.IntegerDef{
- Value: 2,
- },
- &ast.IntegerDef{
- Value: 3,
- },
- &ast.IntegerDef{
- Value: 4,
- },
- &ast.IntegerDef{
- Value: 5,
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "INSERT INTO tech_book VALUES(1, 2, 3, 4, 5)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "INSERT INTO tech_book VALUES(TRUE)",
- want: []ast.Node{
- &ast.InsertStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ValueList: [][]ast.ExpressionNode{
- {
- &ast.BoolDef{
- Value: true,
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "INSERT INTO tech_book VALUES(TRUE)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCopyStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "COPY tech_book FROM '/file/path/in/file/system'",
- want: []ast.Node{
- &ast.CopyStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- FilePath: "/file/path/in/file/system",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "COPY tech_book FROM '/file/path/in/file/system'",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestUnconvertStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "UNLISTEN *",
- want: []ast.Node{&ast.UnconvertedStmt{}},
- statementList: []base.SingleSQL{
- {
- Text: "UNLISTEN *",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCommentStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "COMMENT ON TABLE public.tech_book IS 'This is a comment with ''.'",
- want: []ast.Node{&ast.CommentStmt{
- Type: ast.ObjectTypeTable,
- Object: &ast.TableDef{Schema: "public", Name: "tech_book"},
- Comment: "This is a comment with '.",
- }},
- statementList: []base.SingleSQL{
- {
- Text: "COMMENT ON TABLE public.tech_book IS 'This is a comment with ''.'",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "COMMENT ON COLUMN public.tech_book.a IS 'This is a comment.'",
- want: []ast.Node{&ast.CommentStmt{
- Type: ast.ObjectTypeColumn,
- Object: &ast.ColumnNameDef{Table: &ast.TableDef{Schema: "public", Name: "tech_book"}, ColumnName: "a"},
- Comment: "This is a comment.",
- }},
- statementList: []base.SingleSQL{
- {
- Text: "COMMENT ON COLUMN public.tech_book.a IS 'This is a comment.'",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCreateDatabase(t *testing.T) {
- tests := []testData{
- {
- stmt: "CREATE DATABASE db1 ENCODING = 'UTF8'",
- want: []ast.Node{&ast.CreateDatabaseStmt{
- Name: "db1",
- OptionList: []*ast.DatabaseOptionDef{
- {
- Type: ast.DatabaseOptionEncoding,
- Value: "UTF8",
- },
- },
- }},
- statementList: []base.SingleSQL{
- {
- Text: "CREATE DATABASE db1 ENCODING = 'UTF8'",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCreateSchema(t *testing.T) {
- tests := []testData{
- {
- stmt: "CREATE SCHEMA myschema",
- want: []ast.Node{&ast.CreateSchemaStmt{
- Name: "myschema",
- IfNotExists: false,
- }},
- statementList: []base.SingleSQL{
- {
- Text: "CREATE SCHEMA myschema",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "CREATE SCHEMA myschema AUTHORIZATION joe;",
- want: []ast.Node{&ast.CreateSchemaStmt{
- Name: "myschema",
- IfNotExists: false,
- RoleSpec: &ast.RoleSpec{Type: ast.RoleSpecTypeUser, Value: "joe"},
- }},
- statementList: []base.SingleSQL{
- {
- Text: "CREATE SCHEMA myschema AUTHORIZATION joe;",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "CREATE SCHEMA IF NOT EXISTS myschema AUTHORIZATION joe;",
- want: []ast.Node{&ast.CreateSchemaStmt{
- Name: "myschema",
- IfNotExists: true,
- RoleSpec: &ast.RoleSpec{Type: ast.RoleSpecTypeUser, Value: "joe"},
- }},
- statementList: []base.SingleSQL{
- {
- Text: "CREATE SCHEMA IF NOT EXISTS myschema AUTHORIZATION joe;",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "CREATE SCHEMA myschema CREATE TABLE tbl (id INT)",
- want: []ast.Node{&ast.CreateSchemaStmt{
- Name: "myschema",
- IfNotExists: false,
- SchemaElementList: []ast.Node{
- &ast.CreateTableStmt{
- IfNotExists: false,
- Name: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tbl",
- },
- ColumnList: []*ast.ColumnDef{
- {
- ColumnName: "id",
- Type: &ast.Integer{Size: 4},
- },
- },
- },
- },
- }},
- statementList: []base.SingleSQL{
- {
- Text: "CREATE SCHEMA myschema CREATE TABLE tbl (id INT)",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
- runTests(t, tests)
-}
-
-func TestDropSchema(t *testing.T) {
- tests := []testData{
- {
- stmt: "DROP SCHEMA s1",
- want: []ast.Node{
- &ast.DropSchemaStmt{
- IfExists: false,
- SchemaList: []string{"s1"},
- Behavior: ast.DropBehaviorRestrict,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP SCHEMA s1",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DROP SCHEMA s1, s2 CASCADE",
- want: []ast.Node{
- &ast.DropSchemaStmt{
- IfExists: false,
- SchemaList: []string{"s1", "s2"},
- Behavior: ast.DropBehaviorCascade,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP SCHEMA s1, s2 CASCADE",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "DROP SCHEMA IF EXISTS s1, s2 RESTRICT",
- want: []ast.Node{
- &ast.DropSchemaStmt{
- IfExists: true,
- SchemaList: []string{"s1", "s2"},
- Behavior: ast.DropBehaviorRestrict,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "DROP SCHEMA IF EXISTS s1, s2 RESTRICT",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
- runTests(t, tests)
-}
-
-func TestAlterColumnDefault(t *testing.T) {
- tests := []testData{
- {
- stmt: "ALTER TABLE tech_book ALTER COLUMN a DROP DEFAULT",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.DropDefaultStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnName: "a",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ALTER COLUMN a DROP DEFAULT",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: "ALTER TABLE tech_book ALTER COLUMN a SET DEFAULT 1+2+3",
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.SetDefaultStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- ColumnName: "a",
- Expression: expressionWithText(&ast.UnconvertedExpressionDef{}, "(1 + 2) + 3"),
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: "ALTER TABLE tech_book ALTER COLUMN a SET DEFAULT 1+2+3",
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
- runTests(t, tests)
-}
-
-func TestCreateSequence(t *testing.T) {
- var one int64 = 1
- tests := []testData{
- {
- stmt: `CREATE SEQUENCE public.tbl_seq_id_seq
- AS integer
- INCREMENT BY 1
- START WITH 1
- MINVALUE 1
- MAXVALUE 1
- CACHE 1
- CYCLE
- OWNED BY public.tbl.id;`,
- want: []ast.Node{
- &ast.CreateSequenceStmt{
- IfNotExists: false,
- SequenceDef: ast.SequenceDef{
- SequenceName: &ast.SequenceNameDef{
- Schema: "public",
- Name: "tbl_seq_id_seq",
- },
- SequenceDataType: &ast.Integer{
- Size: 4,
- },
- IncrementBy: &one,
- StartWith: &one,
- MinValue: &one,
- MaxValue: &one,
- Cache: &one,
- Cycle: true,
- OwnedBy: &ast.ColumnNameDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeUnknown,
- Name: "tbl",
- Schema: "public",
- },
- ColumnName: "id",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE SEQUENCE public.tbl_seq_id_seq
- AS integer
- INCREMENT BY 1
- START WITH 1
- MINVALUE 1
- MAXVALUE 1
- CACHE 1
- CYCLE
- OWNED BY public.tbl.id;`,
- End: &store.Position{Line: 9, Column: 0},
- },
- },
- },
- {
- stmt: `CREATE SEQUENCE public.tbl_seq_id_seq
- AS bigint
- INCREMENT BY 1
- START WITH 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;`,
- want: []ast.Node{
- &ast.CreateSequenceStmt{
- IfNotExists: false,
- SequenceDef: ast.SequenceDef{
- SequenceName: &ast.SequenceNameDef{
- Schema: "public",
- Name: "tbl_seq_id_seq",
- },
- SequenceDataType: &ast.Integer{
- Size: 8,
- },
- IncrementBy: &one,
- StartWith: &one,
- Cache: &one,
- Cycle: false,
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE SEQUENCE public.tbl_seq_id_seq
- AS bigint
- INCREMENT BY 1
- START WITH 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;`,
- End: &store.Position{Line: 7, Column: 0},
- },
- },
- },
- {
- stmt: `CREATE SEQUENCE IF NOT EXISTS public.tbl_seq_id_seq;`,
- want: []ast.Node{
- &ast.CreateSequenceStmt{
- IfNotExists: true,
- SequenceDef: ast.SequenceDef{
- SequenceName: &ast.SequenceNameDef{
- Schema: "public",
- Name: "tbl_seq_id_seq",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE SEQUENCE IF NOT EXISTS public.tbl_seq_id_seq;`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
- runTests(t, tests)
-}
-
-func TestDropSequence(t *testing.T) {
- tests := []testData{
- {
- stmt: `DROP SEQUENCE public.tbl_seq_id_seq;`,
- want: []ast.Node{
- &ast.DropSequenceStmt{
- IfExists: false,
- Behavior: ast.DropBehaviorRestrict,
- SequenceNameList: []*ast.SequenceNameDef{
- {
- Schema: "public",
- Name: "tbl_seq_id_seq",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `DROP SEQUENCE public.tbl_seq_id_seq;`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: `DROP SEQUENCE IF EXISTS tbl_seq1, public.tbl_seq2 CASCADE;`,
- want: []ast.Node{
- &ast.DropSequenceStmt{
- IfExists: true,
- Behavior: ast.DropBehaviorCascade,
- SequenceNameList: []*ast.SequenceNameDef{
- {
- Name: "tbl_seq1",
- },
- {
- Schema: "public",
- Name: "tbl_seq2",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `DROP SEQUENCE IF EXISTS tbl_seq1, public.tbl_seq2 CASCADE;`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
- runTests(t, tests)
-}
-
-func TestAlterSequence(t *testing.T) {
- one := int64(1)
- boolFalse := false
- boolTrue := true
- tests := []testData{
- {
- stmt: `
- ALTER SEQUENCE IF EXISTS public.tbl_seq_id_seq
- AS bigint
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- START WITH 1
- RESTART WITH 1
- CACHE 1
- NO CYCLE
- OWNED BY NONE;`,
- want: []ast.Node{
- &ast.AlterSequenceStmt{
- IfExists: true,
- Name: &ast.SequenceNameDef{
- Schema: "public",
- Name: "tbl_seq_id_seq",
- },
- Type: &ast.Integer{
- Size: 8,
- },
- IncrementBy: &one,
- NoMinValue: true,
- NoMaxValue: true,
- StartWith: &one,
- RestartWith: &one,
- Cache: &one,
- Cycle: &boolFalse,
- OwnedByNone: true,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `ALTER SEQUENCE IF EXISTS public.tbl_seq_id_seq
- AS bigint
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- START WITH 1
- RESTART WITH 1
- CACHE 1
- NO CYCLE
- OWNED BY NONE;`,
- End: &store.Position{Line: 11, Column: 0},
- },
- },
- },
- {
- stmt: `
- ALTER SEQUENCE IF EXISTS public.tbl_seq_id_seq
- MINVALUE 1
- MAXVALUE 1
- CYCLE
- OWNED BY public.tbl.id;`,
- want: []ast.Node{
- &ast.AlterSequenceStmt{
- IfExists: true,
- Name: &ast.SequenceNameDef{
- Schema: "public",
- Name: "tbl_seq_id_seq",
- },
- MinValue: &one,
- MaxValue: &one,
- Cycle: &boolTrue,
- OwnedBy: &ast.ColumnNameDef{
- Table: &ast.TableDef{
- Type: ast.TableTypeUnknown,
- Name: "tbl",
- Schema: "public",
- },
- ColumnName: "id",
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `ALTER SEQUENCE IF EXISTS public.tbl_seq_id_seq
- MINVALUE 1
- MAXVALUE 1
- CYCLE
- OWNED BY public.tbl.id;`,
- End: &store.Position{Line: 6, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCreateExtension(t *testing.T) {
- tests := []testData{
- {
- stmt: `CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public`,
- want: []ast.Node{
- &ast.CreateExtensionStmt{
- Schema: "public",
- Name: "pg_trgm",
- IfNotExists: true,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestDropExtension(t *testing.T) {
- tests := []testData{
- {
- stmt: `DROP EXTENSION IF EXISTS pg_trgm, hstore`,
- want: []ast.Node{
- &ast.DropExtensionStmt{
- IfExists: true,
- NameList: []string{
- "pg_trgm",
- "hstore",
- },
- Behavior: ast.DropBehaviorRestrict,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `DROP EXTENSION IF EXISTS pg_trgm, hstore`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCreateFunction(t *testing.T) {
- tests := []testData{
- {
- stmt: `Create function get_car_Price("Price_from" int, Price_to int)
- returns int
- language plpgsql
- as
- $$
- Declare
- Car_count integer;
- Begin
- select count(*)
- into Car_count
- from Car
- where Car_price between "Price_from" and Price_to;
- return Car_count;
- End;
- $$;`,
- want: []ast.Node{
- &ast.CreateFunctionStmt{
- Function: &ast.FunctionDef{
- Schema: "",
- Name: "get_car_price",
- ParameterList: []*ast.FunctionParameterDef{
- {
- Name: "Price_from",
- Type: &ast.Integer{Size: 4},
- Mode: ast.FunctionParameterModeDefault,
- },
- {
- Name: "price_to",
- Type: &ast.Integer{Size: 4},
- Mode: ast.FunctionParameterModeDefault,
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `Create function get_car_Price("Price_from" int, Price_to int)
- returns int
- language plpgsql
- as
- $$
- Declare
- Car_count integer;
- Begin
- select count(*)
- into Car_count
- from Car
- where Car_price between "Price_from" and Price_to;
- return Car_count;
- End;
- $$;`,
- End: &store.Position{Line: 15, Column: 0},
- },
- },
- },
- {
- stmt: `CREATE FUNCTION public.trigger_update_updated_ts() RETURNS trigger
- LANGUAGE plpgsql
- AS $$
- BEGIN
- NEW.updated_ts = extract(epoch from now());
- RETURN NEW;
- END;
- $$;`,
- want: []ast.Node{
- &ast.CreateFunctionStmt{
- Function: &ast.FunctionDef{
- Schema: "public",
- Name: "trigger_update_updated_ts",
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE FUNCTION public.trigger_update_updated_ts() RETURNS trigger
- LANGUAGE plpgsql
- AS $$
- BEGIN
- NEW.updated_ts = extract(epoch from now());
- RETURN NEW;
- END;
- $$;`,
- End: &store.Position{Line: 8, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestDropFunction(t *testing.T) {
- tests := []testData{
- {
- // pg_query_go will skip the OUT parameters and only parse the parameter data type.
- stmt: `DROP FUNCTION IF EXISTS public.func1(INOUT "Price_from" int, IN price_to int, OUT out_item int), func2()`,
- want: []ast.Node{
- &ast.DropFunctionStmt{
- IfExists: true,
- FunctionList: []*ast.FunctionDef{
- {
- Schema: "public",
- Name: "func1",
- ParameterList: []*ast.FunctionParameterDef{
- {
- Type: &ast.Integer{Size: 4},
- },
- {
- Type: &ast.Integer{Size: 4},
- },
- },
- },
- {
- Schema: "",
- Name: "func2",
- },
- },
- Behavior: ast.DropBehaviorRestrict,
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `DROP FUNCTION IF EXISTS public.func1(INOUT "Price_from" int, IN price_to int, OUT out_item int), func2()`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCreateTrigger(t *testing.T) {
- tests := []testData{
- {
- stmt: `CREATE TRIGGER update_principal_updated_ts BEFORE UPDATE ON public.principal FOR EACH ROW EXECUTE FUNCTION public.trigger_update_updated_ts();`,
- want: []ast.Node{
- &ast.CreateTriggerStmt{
- Trigger: &ast.TriggerDef{
- Name: "update_principal_updated_ts",
- Table: &ast.TableDef{
- Type: ast.TableTypeUnknown,
- Schema: "public",
- Name: "principal",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE TRIGGER update_principal_updated_ts BEFORE UPDATE ON public.principal FOR EACH ROW EXECUTE FUNCTION public.trigger_update_updated_ts();`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestDropTrigger(t *testing.T) {
- tests := []testData{
- {
- stmt: `DROP TRIGGER update_ts ON public.principal`,
- want: []ast.Node{
- &ast.DropTriggerStmt{
- IfExists: false,
- Behavior: ast.DropBehaviorRestrict,
- Trigger: &ast.TriggerDef{
- Name: "update_ts",
- Table: &ast.TableDef{
- Type: ast.TableTypeUnknown,
- Schema: "public",
- Name: "principal",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `DROP TRIGGER update_ts ON public.principal`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCreateType(t *testing.T) {
- tests := []testData{
- {
- stmt: `CREATE TYPE public.bug_status AS ENUM ('new', 'open', 'closed');`,
- want: []ast.Node{
- &ast.CreateTypeStmt{
- Type: &ast.EnumTypeDef{
- Name: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- LabelList: []string{"new", "open", "closed"},
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `CREATE TYPE public.bug_status AS ENUM ('new', 'open', 'closed');`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestDropType(t *testing.T) {
- tests := []testData{
- {
- stmt: `DROP TYPE public.bug_status, tp1`,
- want: []ast.Node{
- &ast.DropTypeStmt{
- IfExists: false,
- Behavior: ast.DropBehaviorRestrict,
- TypeNameList: []*ast.TypeNameDef{
- {
- Schema: "public",
- Name: "bug_status",
- },
- {
- Schema: "",
- Name: "tp1",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `DROP TYPE public.bug_status, tp1`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestAlterType(t *testing.T) {
- tests := []testData{
- {
- stmt: `ALTER TYPE public.bug_status ADD VALUE 'a' BEFORE 'b'`,
- want: []ast.Node{
- &ast.AlterTypeStmt{
- Type: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- AlterItemList: []ast.Node{
- &ast.AddEnumLabelStmt{
- EnumType: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- NewLabel: "a",
- Position: ast.PositionTypeBefore,
- NeighborLabel: "b",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
-
- Text: `ALTER TYPE public.bug_status ADD VALUE 'a' BEFORE 'b'`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: `ALTER TYPE public.bug_status ADD VALUE 'a' AFTER 'b'`,
- want: []ast.Node{
- &ast.AlterTypeStmt{
- Type: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- AlterItemList: []ast.Node{
- &ast.AddEnumLabelStmt{
- EnumType: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- NewLabel: "a",
- Position: ast.PositionTypeAfter,
- NeighborLabel: "b",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
-
- Text: `ALTER TYPE public.bug_status ADD VALUE 'a' AFTER 'b'`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- {
- stmt: `ALTER TYPE public.bug_status ADD VALUE 'a'`,
- want: []ast.Node{
- &ast.AlterTypeStmt{
- Type: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- AlterItemList: []ast.Node{
- &ast.AddEnumLabelStmt{
- EnumType: &ast.TypeNameDef{
- Schema: "public",
- Name: "bug_status",
- },
- NewLabel: "a",
- Position: ast.PositionTypeEnd,
- NeighborLabel: "",
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
-
- Text: `ALTER TYPE public.bug_status ADD VALUE 'a'`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestAttachPartition(t *testing.T) {
- tests := []testData{
- {
- stmt: `ALTER TABLE tech_book ATTACH PARTITION p1 DEFAULT`,
- want: []ast.Node{
- &ast.AlterTableStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- AlterItemList: []ast.Node{
- &ast.AttachPartitionStmt{
- Table: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "tech_book",
- },
- Partition: &ast.TableDef{
- Type: ast.TableTypeBaseTable,
- Name: "p1",
- },
- },
- },
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `ALTER TABLE tech_book ATTACH PARTITION p1 DEFAULT`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestCommit(t *testing.T) {
- tests := []testData{
- {
- stmt: `COMMIT;`,
- want: []ast.Node{
- &ast.CommitStmt{},
- },
- statementList: []base.SingleSQL{
- {
- Text: `COMMIT;`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-func TestRenameSchema(t *testing.T) {
- tests := []testData{
- {
- stmt: `ALTER SCHEMA s1 RENAME TO s2`,
- want: []ast.Node{
- &ast.RenameSchemaStmt{
- Schema: "s1",
- NewName: "s2",
- },
- },
- statementList: []base.SingleSQL{
- {
- Text: `ALTER SCHEMA s1 RENAME TO s2`,
- End: &store.Position{Line: 1, Column: 0},
- },
- },
- },
- }
-
- runTests(t, tests)
-}
-
-type setLineTestData struct {
- statement string
- columnLineList []int
- constraintLineList []int
-}
-
-// TODO(d): fix this test with setLineForCreateTableStmt().
-func TestPGCreateTableSetLine(t *testing.T) {
- tests := []setLineTestData{
- {
- statement: `
- CREATE TABLE t(
- a int, B int,
- C int,
- "D" int NOT NULL,
- CONSTRAINT unique_a UNIQUE (a),
- UNIQUE (b, c),
- PRIMARY KEY (d),CHECK (a > 0),
-
- -- it's a comment.
- FOREIGN KEY (a, b, c) REFERENCES t1(a, b, c)
-
-
-
-
- )
- `,
- columnLineList: []int{3, 3, 4, 5},
- constraintLineList: []int{6, 7, 8, 8, 11},
- },
- {
- // test for Windows.
- statement: "\r\n" +
- "CREATE TABLE t(" + "\r\n" +
- "a int, B int," + "\r\n" +
- "C int," + "\r\n" +
- `"D" int NOT NULL,` + "\r\n" +
- "CONSTRAINT unique_a UNIQUE (a)," + "\r\n" +
- "UNIQUE (b, c)," + "\r\n" +
- "PRIMARY KEY (d),CHECK (a > 0)," + "\r\n" +
- "\r\n" +
- "FOREIGN KEY (a, b, c) REFERENCES t1(a, b, c)" + "\r\n" +
- ")",
- columnLineList: []int{3, 3, 4, 5},
- constraintLineList: []int{6, 7, 8, 8, 10},
- },
- {
- statement: `
- CREATE TABLE t(
- a int PRIMARY KEY,
- b int CHECK(b>1), c int UNIQUE
- )
- `,
- columnLineList: []int{3, 4, 4},
- constraintLineList: []int{},
- },
- {
- statement: `-- complex example
- CREATE TABLE t(
- a int PRIMARY KEY,
- name varchar(255) DEFAULT 'UNIQUE on (a, b, c)(',
- UNIQUE(a, name),
- UNIQUE(name)
- )
- `,
- columnLineList: []int{3, 4},
- constraintLineList: []int{5, 6},
- },
- }
-
- for _, test := range tests {
- nodeList, err := Parse(ParseContext{}, test.statement)
- require.NoError(t, err)
- require.Len(t, nodeList, 1)
- node, ok := nodeList[0].(*ast.CreateTableStmt)
- require.True(t, ok)
- require.Equal(t, len(test.columnLineList), len(node.ColumnList), test.statement)
- require.Equal(t, len(test.constraintLineList), len(node.ConstraintList), test.statement)
- for i, col := range node.ColumnList {
- require.Equal(t, test.columnLineList[i], col.LastLine(), test.statement)
- for _, inlineCons := range col.ConstraintList {
- require.Equal(t, test.columnLineList[i], inlineCons.LastLine(), test.statement)
- }
- }
- for i, cons := range node.ConstraintList {
- require.Equal(t, test.constraintLineList[i], cons.LastLine(), test.statement)
- }
- }
-}
-
-// TestVariableSetStmt is a helper test to help us to determine the statement whether is a variable set statement.
-func TestVariableSetStmt(t *testing.T) {
- tests := []testData{
- {
- stmt: "SET max_execution_time = 1000;",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "max_execution_time",
- Args: []ast.ExpressionNode{
- &ast.IntegerDef{
- Value: 1000,
- },
- },
- },
- },
- },
- {
- stmt: "SET TIME ZONE 'PST8PDT';",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "timezone",
- Args: []ast.ExpressionNode{
- &ast.StringDef{
- Value: "PST8PDT",
- },
- },
- },
- },
- },
- {
- stmt: "SET search_path TO my_schema, public;",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "search_path",
- Args: []ast.ExpressionNode{
- &ast.StringDef{
- Value: "my_schema",
- },
- &ast.StringDef{
- Value: "public",
- },
- },
- },
- },
- },
- {
- stmt: "SET datestyle TO postgres, dmy;",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "datestyle",
- Args: []ast.ExpressionNode{
- &ast.StringDef{
- Value: "postgres",
- },
- &ast.StringDef{
- Value: "dmy",
- },
- },
- },
- },
- },
- {
- stmt: "SET SESSION ROLE 'joe';",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "role",
- Args: []ast.ExpressionNode{
- &ast.StringDef{
- Value: "joe",
- },
- },
- },
- },
- },
- {
- stmt: "SET SESSION ROLE joe;",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "role",
- Args: []ast.ExpressionNode{
- &ast.StringDef{
- Value: "joe",
- },
- },
- },
- },
- },
- {
- stmt: "SET LOCAL ROLE joe;",
- want: []ast.Node{
- &ast.VariableSetStmt{
- Name: "role",
- Args: []ast.ExpressionNode{
- &ast.StringDef{
- Value: "joe",
- },
- },
- IsLocal: true,
- },
- },
- },
- }
-
- for _, test := range tests {
- nodeList, err := Parse(ParseContext{}, test.stmt)
- require.NoError(t, err)
- require.Len(t, nodeList, 1)
- result, ok := nodeList[0].(*ast.VariableSetStmt)
- require.True(t, ok)
- want, ok := test.want[0].(*ast.VariableSetStmt)
- require.True(t, ok)
- require.Equal(t, want.Name, result.Name)
- require.Equal(t, want.Args, result.Args)
- require.Equal(t, want.IsLocal, result.IsLocal)
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/data_type_test.go b/backend/plugin/parser/pg/legacy/data_type_test.go
deleted file mode 100644
index c87462429f..0000000000
--- a/backend/plugin/parser/pg/legacy/data_type_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package legacy
-
-import (
- "fmt"
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-)
-
-func TestEquivalentType(t *testing.T) {
- type testData struct {
- originType string
- matchType string
- }
- tests := []testData{
- {
- originType: "int",
- matchType: "INTEGER",
- },
- {
- originType: "int",
- matchType: "int4",
- },
- {
- originType: "decimal(10, 2)",
- matchType: "decimal",
- },
- {
- originType: "float4",
- matchType: "real",
- },
- {
- originType: "float",
- matchType: "double precision",
- },
- }
-
- for _, test := range tests {
- stmt := fmt.Sprintf("ALTER TABLE t ADD COLUMN a %s", test.originType)
- nodeList, err := Parse(ParseContext{}, stmt)
- require.NoError(t, err)
- require.Len(t, nodeList, 1)
- node := nodeList[0]
- alterTable, ok := node.(*ast.AlterTableStmt)
- require.True(t, ok)
- require.Len(t, alterTable.AlterItemList, 1)
- addColumn, ok := alterTable.AlterItemList[0].(*ast.AddColumnListStmt)
- require.True(t, ok)
- require.Len(t, addColumn.ColumnList, 1)
- column := addColumn.ColumnList[0]
- require.True(t, column.Type.EquivalentType(test.matchType))
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/deparse.go b/backend/plugin/parser/pg/legacy/deparse.go
deleted file mode 100644
index ea2324d605..0000000000
--- a/backend/plugin/parser/pg/legacy/deparse.go
+++ /dev/null
@@ -1,1905 +0,0 @@
-package legacy
-
-import (
- "fmt"
- "strconv"
- "strings"
-
- "github.com/pkg/errors"
-
- pgquery "github.com/pganalyze/pg_query_go/v6"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-)
-
-func deparseImpl(context DeparseContext, in ast.Node, buf *strings.Builder) error {
- switch node := in.(type) {
- case ast.DataType:
- return deparseDataType(context, node, buf)
- case *ast.CreateTableStmt:
- if err := deparseCreateTable(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropTableStmt:
- if err := deparseDropTable(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.AlterTableStmt:
- if err := deparseAlterTable(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.TableDef:
- return deparseTableDef(context, node, buf)
- case *ast.ColumnDef:
- return deparseColumnDef(context, node, buf)
- case *ast.CreateSchemaStmt:
- if err := deparseCreateSchema(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropSchemaStmt:
- if err := deparseDropSchema(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.ConstraintDef:
- return deparseConstraintDef(context, node, buf)
- case *ast.CreateIndexStmt:
- if err := deparseCreateIndex(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropIndexStmt:
- if err := deparseDropIndex(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.CreateSequenceStmt:
- if err := deparseCreateSequence(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.AlterSequenceStmt:
- if err := deparseAlterSequence(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropSequenceStmt:
- if err := deparseDropSequence(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropExtensionStmt:
- if err := deparseDropExtension(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropFunctionStmt:
- if err := deparseDropFunction(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropTriggerStmt:
- if err := deparseDropTrigger(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.DropTypeStmt:
- if err := deparseDropType(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.AlterTypeStmt:
- if err := deparseAlterType(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.RenameSchemaStmt:
- if err := deparseRenameSchema(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- case *ast.CommentStmt:
- if err := deparseComment(context, node, buf); err != nil {
- return err
- }
- return buf.WriteByte(';')
- }
- return errors.Errorf("failed to deparse %T", in)
-}
-
-func deparseComment(context DeparseContext, in *ast.CommentStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- switch in.Type {
- case ast.ObjectTypeTable, ast.ObjectTypeView:
- typeText := "TABLE"
- if in.Type == ast.ObjectTypeView {
- typeText = "VIEW"
- }
- if _, err := fmt.Fprintf(buf, "COMMENT ON %s \"", typeText); err != nil {
- return err
- }
- tableDef, ok := in.Object.(*ast.TableDef)
- if !ok {
- return errors.Errorf("expect *ast.TableDef, but got %T", in.Object)
- }
- if tableDef.Schema != "" {
- if _, err := buf.WriteString(tableDef.Schema); err != nil {
- return err
- }
- if _, err := buf.WriteString("\".\""); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(tableDef.Name); err != nil {
- return err
- }
- if _, err := buf.WriteString("\" IS '"); err != nil {
- return err
- }
- escapeComment := strings.ReplaceAll(in.Comment, "'", "''")
- if _, err := buf.WriteString(escapeComment); err != nil {
- return err
- }
- _, err := buf.WriteString("'")
- return err
- case ast.ObjectTypeColumn:
- if _, err := buf.WriteString("COMMENT ON COLUMN \""); err != nil {
- return err
- }
- columnNameDef, ok := in.Object.(*ast.ColumnNameDef)
- if !ok {
- return errors.Errorf("expect *ast.ColumnNameDef, but got %T", in.Object)
- }
- if columnNameDef.Table.Schema != "" {
- if _, err := buf.WriteString(columnNameDef.Table.Schema); err != nil {
- return err
- }
- if _, err := buf.WriteString("\".\""); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(columnNameDef.Table.Name); err != nil {
- return err
- }
- if _, err := buf.WriteString("\".\""); err != nil {
- return err
- }
- if _, err := buf.WriteString(columnNameDef.ColumnName); err != nil {
- return err
- }
- if _, err := buf.WriteString("\" IS '"); err != nil {
- return err
- }
- escapeComment := strings.ReplaceAll(in.Comment, "'", "''")
- if _, err := buf.WriteString(escapeComment); err != nil {
- return err
- }
- _, err := buf.WriteString("'")
- return err
- default:
- return errors.Errorf("failed to deparse comment for type %v", in.Type)
- }
-}
-
-func deparseDropIndex(context DeparseContext, in *ast.DropIndexStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("DROP INDEX "); err != nil {
- return err
- }
-
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
-
- for i, index := range in.IndexList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
-
- if index.Table != nil && index.Table.Schema != "" {
- if err := writeSurrounding(buf, index.Table.Schema, `"`); err != nil {
- return err
- }
- if err := buf.WriteByte('.'); err != nil {
- return err
- }
- }
-
- if err := writeSurrounding(buf, index.Name, `"`); err != nil {
- return err
- }
- }
-
- if in.Behavior == ast.DropBehaviorCascade {
- if _, err := buf.WriteString(" CASCADE"); err != nil {
- return err
- }
- }
- return nil
-}
-
-func deparseCreateIndex(context DeparseContext, in *ast.CreateIndexStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("CREATE "); err != nil {
- return err
- }
-
- if in.Index.Unique {
- if _, err := buf.WriteString("UNIQUE "); err != nil {
- return err
- }
- }
-
- if _, err := buf.WriteString("INDEX "); err != nil {
- return err
- }
-
- if in.Concurrently {
- if _, err := buf.WriteString("CONCURRENTLY "); err != nil {
- return err
- }
- }
-
- if in.IfNotExists {
- if _, err := buf.WriteString("IF NOT EXISTS "); err != nil {
- return err
- }
- }
-
- if err := writeSurrounding(buf, in.Index.Name, `"`); err != nil {
- return err
- }
-
- if _, err := buf.WriteString(" ON "); err != nil {
- return err
- }
-
- if err := deparseTableDef(context, in.Index.Table, buf); err != nil {
- return err
- }
-
- if _, err := buf.WriteString(" USING "); err != nil {
- return err
- }
-
- if err := deparseIndexMethod(in.Index.Method, buf); err != nil {
- return err
- }
-
- if _, err := buf.WriteString(" ("); err != nil {
- return err
- }
-
- for i, key := range in.Index.KeyList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := deparseIndexKey(DeparseContext{IndentLevel: 0}, key, buf); err != nil {
- return err
- }
- }
-
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
-
- return nil
-}
-
-func deparseIndexMethod(method ast.IndexMethodType, buf *strings.Builder) (err error) {
- switch method {
- case ast.IndexMethodTypeBTree:
- _, err = buf.WriteString("btree")
- case ast.IndexMethodTypeHash:
- _, err = buf.WriteString("hash")
- case ast.IndexMethodTypeGiST:
- _, err = buf.WriteString("gist")
- case ast.IndexMethodTypeSpGiST:
- _, err = buf.WriteString("spgist")
- case ast.IndexMethodTypeGin:
- _, err = buf.WriteString("gin")
- case ast.IndexMethodTypeBrin:
- _, err = buf.WriteString("brin")
- case ast.IndexMethodTypeIvfflat:
- _, err = buf.WriteString("ivfflat")
- default:
- }
- return err
-}
-
-func deparseIndexKey(context DeparseContext, in *ast.IndexKeyDef, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- switch in.Type {
- case ast.IndexKeyTypeColumn:
- if _, err := buf.WriteString(in.Key); err != nil {
- return err
- }
- case ast.IndexKeyTypeExpression:
- if err := buf.WriteByte('('); err != nil {
- return err
- }
- if _, err := buf.WriteString(in.Key); err != nil {
- return err
- }
- if err := buf.WriteByte(')'); err != nil {
- return err
- }
- default:
- }
-
- if in.SortOrder == ast.SortOrderTypeDescending {
- if _, err := buf.WriteString(" DESC"); err != nil {
- return err
- }
- }
-
- switch in.NullOrder {
- case ast.NullOrderTypeFirst:
- if _, err := buf.WriteString(" NULLS FIRST"); err != nil {
- return err
- }
- case ast.NullOrderTypeLast:
- if _, err := buf.WriteString(" NULLS LAST"); err != nil {
- return err
- }
- default:
- // No explicit null ordering specified
- }
-
- return nil
-}
-
-func deparseDropTable(context DeparseContext, in *ast.DropTableStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("DROP TABLE "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- for i, table := range in.TableList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := deparseTableDef(DeparseContext{IndentLevel: 0}, table, buf); err != nil {
- return err
- }
- }
- return deparseDropBehavior(context, in.Behavior, buf)
-}
-
-func deparseAlterTable(context DeparseContext, in *ast.AlterTableStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("ALTER TABLE "); err != nil {
- return err
- }
- if err := deparseTableDef(context, in.Table, buf); err != nil {
- return err
- }
- itemContext := DeparseContext{
- IndentLevel: context.IndentLevel + 1,
- }
- for i, item := range in.AlterItemList {
- if i != 0 {
- if _, err := buf.WriteString(","); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- switch action := item.(type) {
- case *ast.AddColumnListStmt:
- if err := deparseAddColumnList(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.AlterColumnTypeStmt:
- if err := deparseAlterColumnType(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.DropColumnStmt:
- if err := deparseDropColumn(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.SetNotNullStmt:
- if err := deparseSetNotNull(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.DropNotNullStmt:
- if err := deparseDropNotNull(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.AddConstraintStmt:
- if err := deparseAddConstraint(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.DropConstraintStmt:
- if err := deparseDropConstraint(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.SetDefaultStmt:
- if err := deparseSetDefault(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.DropDefaultStmt:
- if err := deparseDropDefault(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.RenameColumnStmt:
- if len(in.AlterItemList) != 1 {
- return errors.Errorf("deparse failed, RenameColumnStmt needs to be alone in a ALTER TABLE statement")
- }
- if err := deparseRenameColumn(itemContext, action, buf); err != nil {
- return err
- }
- case *ast.RenameTableStmt:
- if len(in.AlterItemList) != 1 {
- return errors.Errorf("deparse failed, RenameTableStmt needs to be alone in a ALTER TABLE statement")
- }
- if err := deparseRenameTable(itemContext, action, buf); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-func deparseRenameColumn(context DeparseContext, in *ast.RenameColumnStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("RENAME COLUMN "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" TO "); err != nil {
- return err
- }
- return writeSurrounding(buf, in.NewName, `"`)
-}
-
-func deparseRenameTable(context DeparseContext, in *ast.RenameTableStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("RENAME TO "); err != nil {
- return err
- }
- return writeSurrounding(buf, in.NewName, `"`)
-}
-
-func deparseSetDefault(context DeparseContext, in *ast.SetDefaultStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("ALTER COLUMN "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" SET DEFAULT "); err != nil {
- return err
- }
- if _, err := buf.WriteString(in.Expression.Text()); err != nil {
- return err
- }
- return nil
-}
-
-func deparseDropDefault(context DeparseContext, in *ast.DropDefaultStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("ALTER COLUMN "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" DROP DEFAULT"); err != nil {
- return err
- }
- return nil
-}
-
-func deparseAddConstraint(context DeparseContext, in *ast.AddConstraintStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("ADD "); err != nil {
- return err
- }
- if in.Constraint.Name != "" {
- if _, err := buf.WriteString("CONSTRAINT "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.Constraint.Name, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- }
- return deparseConstraintDef(context, in.Constraint, buf)
-}
-
-func deparseConstraintDef(_ DeparseContext, in *ast.ConstraintDef, buf *strings.Builder) error {
- switch in.Type {
- case ast.ConstraintTypeUniqueUsingIndex:
- if _, err := buf.WriteString("UNIQUE USING INDEX "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.IndexName, `"`); err != nil {
- return err
- }
-
- if in.Initdeferred {
- if _, err := buf.WriteString(" INITIALLY DEFERRED"); err != nil {
- return err
- }
- } else if in.Deferrable {
- if _, err := buf.WriteString(" DEFERRABLE"); err != nil {
- return err
- }
- }
- case ast.ConstraintTypeUnique:
- if _, err := buf.WriteString("UNIQUE ("); err != nil {
- return err
- }
- if err := deparseKeyList(DeparseContext{}, in.KeyList, buf); err != nil {
- return err
- }
-
- if len(in.Including) > 0 {
- if _, err := buf.WriteString(") INCLUDE ("); err != nil {
- return err
- }
- if err := deparseKeyList(DeparseContext{}, in.Including, buf); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- if in.IndexTableSpace != "" {
- if _, err := buf.WriteString(" USING INDEX TABLESPACE "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.IndexTableSpace, `"`); err != nil {
- return err
- }
- }
- case ast.ConstraintTypePrimary:
- if _, err := buf.WriteString("PRIMARY KEY ("); err != nil {
- return err
- }
- if err := deparseKeyList(DeparseContext{}, in.KeyList, buf); err != nil {
- return err
- }
- if len(in.Including) > 0 {
- if _, err := buf.WriteString(") INCLUDE ("); err != nil {
- return err
- }
- if err := deparseKeyList(DeparseContext{}, in.Including, buf); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- if in.IndexTableSpace != "" {
- if _, err := buf.WriteString(" USING INDEX TABLESPACE "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.IndexTableSpace, `"`); err != nil {
- return err
- }
- }
- case ast.ConstraintTypeCheck:
- if _, err := buf.WriteString("CHECK ("); err != nil {
- return err
- }
- if _, err := buf.WriteString(in.Expression.Text()); err != nil {
- return err
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- case ast.ConstraintTypeExclusion:
- if _, err := buf.WriteString("EXCLUDE USING "); err != nil {
- return err
- }
- if err := deparseIndexMethod(in.AccessMethod, buf); err != nil {
- return err
- }
- if _, err := buf.WriteString(" ("); err != nil {
- return err
- }
- if _, err := buf.WriteString(in.Exclusions); err != nil {
- return err
- }
- if err := buf.WriteByte(')'); err != nil {
- return err
- }
- if in.WhereClause != "" {
- if _, err := buf.WriteString(" WHERE ("); err != nil {
- return err
- }
- if _, err := buf.WriteString(in.WhereClause); err != nil {
- return err
- }
- if err := buf.WriteByte(')'); err != nil {
- return err
- }
- }
- case ast.ConstraintTypeForeign:
- if _, err := buf.WriteString("FOREIGN KEY ("); err != nil {
- return err
- }
- for i, column := range in.KeyList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, column, `"`); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(") REFERENCES "); err != nil {
- return err
- }
- if err := deparseTableDef(DeparseContext{}, in.Foreign.Table, buf); err != nil {
- return err
- }
- if _, err := buf.WriteString(" ("); err != nil {
- return err
- }
- for i, column := range in.Foreign.ColumnList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, column, `"`); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
-
- if err := deparseForeignMatchType(DeparseContext{}, in.Foreign.MatchType, buf); err != nil {
- return err
- }
-
- if err := deparseReferentialAction(DeparseContext{}, "ON DELETE", in.Foreign.OnDelete, buf); err != nil {
- return err
- }
-
- if err := deparseReferentialAction(DeparseContext{}, "ON UPDATE", in.Foreign.OnUpdate, buf); err != nil {
- return err
- }
- default:
- }
- return nil
-}
-
-func deparseReferentialAction(_ DeparseContext, prefix string, in *ast.ReferentialActionDef, buf *strings.Builder) error {
- if in.Type == ast.ReferentialActionTypeNoAction {
- // It's default value, no need to print.
- return nil
- }
- if err := buf.WriteByte(' '); err != nil {
- return err
- }
- if _, err := buf.WriteString(prefix); err != nil {
- return err
- }
- if err := buf.WriteByte(' '); err != nil {
- return err
- }
- switch in.Type {
- case ast.ReferentialActionTypeRestrict:
- if _, err := buf.WriteString("RESTRICT"); err != nil {
- return err
- }
- case ast.ReferentialActionTypeCascade:
- if _, err := buf.WriteString("CASCADE"); err != nil {
- return err
- }
- case ast.ReferentialActionTypeSetNull:
- if _, err := buf.WriteString("SET NULL"); err != nil {
- return err
- }
- case ast.ReferentialActionTypeSetDefault:
- if _, err := buf.WriteString("SET DEFAULT"); err != nil {
- return err
- }
- default:
- }
- return nil
-}
-
-func deparseForeignMatchType(_ DeparseContext, in ast.ForeignMatchType, buf *strings.Builder) error {
- switch in {
- case ast.ForeignMatchTypeSimple:
- // It's default value, no need to print.
- case ast.ForeignMatchTypeFull:
- if _, err := buf.WriteString(" MATCH FULL"); err != nil {
- return err
- }
- case ast.ForeignMatchTypePartial:
- if _, err := buf.WriteString(" MATCH PARTIAL"); err != nil {
- return err
- }
- default:
- }
- return nil
-}
-
-func deparseDropConstraint(context DeparseContext, in *ast.DropConstraintStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("DROP CONSTRAINT "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
-
- return writeSurrounding(buf, in.ConstraintName, `"`)
-}
-
-func deparseDropNotNull(context DeparseContext, in *ast.DropNotNullStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("ALTER COLUMN "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" DROP NOT NULL"); err != nil {
- return err
- }
- return nil
-}
-
-func deparseSetNotNull(context DeparseContext, in *ast.SetNotNullStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("ALTER COLUMN "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" SET NOT NULL"); err != nil {
- return err
- }
- return nil
-}
-
-func deparseDropColumn(context DeparseContext, in *ast.DropColumnStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("DROP COLUMN "); err != nil {
- return err
- }
-
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
-
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
-
- return deparseDropBehavior(context, in.Behavior, buf)
-}
-
-func deparseAlterColumnType(context DeparseContext, in *ast.AlterColumnTypeStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("ALTER COLUMN "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" SET DATA TYPE "); err != nil {
- return err
- }
- return deparseDataType(context, in.Type, buf)
-}
-
-func deparseAddColumnList(context DeparseContext, in *ast.AddColumnListStmt, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("ADD COLUMN "); err != nil {
- return err
- }
-
- if in.IfNotExists {
- if _, err := buf.WriteString("IF NOT EXISTS "); err != nil {
- return err
- }
- }
-
- if len(in.ColumnList) != 1 {
- return errors.Errorf("PostgreSQL doesn't support zero or multi-columns for ALTER TABLE ADD COLUMN statements")
- }
-
- return deparseColumnDef(DeparseContext{IndentLevel: 0}, in.ColumnList[0], buf)
-}
-
-func deparseCreateTable(context DeparseContext, in *ast.CreateTableStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("CREATE TABLE"); err != nil {
- return err
- }
- if in.IfNotExists {
- if _, err := buf.WriteString(" IF NOT EXISTS"); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- if err := deparseTableDef(context, in.Name, buf); err != nil {
- return err
- }
-
- if len(in.ColumnList)+len(in.ConstraintList) != 0 {
- if _, err := buf.WriteString(" ("); err != nil {
- return err
- }
- }
- columnContext := DeparseContext{
- IndentLevel: context.IndentLevel + 1,
- }
- for i, column := range in.ColumnList {
- if i != 0 {
- if _, err := buf.WriteString(","); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := deparseColumnDef(columnContext, column, buf); err != nil {
- return err
- }
- }
- for i, constraint := range in.ConstraintList {
- if i != 0 || len(in.ColumnList) > 0 {
- if _, err := buf.WriteString(","); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := deparseTableConstraint(columnContext, constraint, buf); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if len(in.ColumnList)+len(in.ConstraintList) != 0 {
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- }
- if in.PartitionDef != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := deparsePartitionDef(columnContext, in.PartitionDef, buf); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func deparsePartitionDef(_ DeparseContext, in *ast.PartitionDef, buf *strings.Builder) error {
- if _, err := buf.WriteString("PARTITION BY "); err != nil {
- return err
- }
- strategy := ""
- switch in.Strategy {
- case pgquery.PartitionStrategy_PARTITION_STRATEGY_LIST:
- strategy = "LIST"
- case pgquery.PartitionStrategy_PARTITION_STRATEGY_RANGE:
- strategy = "RANGE"
- case pgquery.PartitionStrategy_PARTITION_STRATEGY_HASH:
- strategy = "HASH"
- default:
- }
- if _, err := buf.WriteString(strategy); err != nil {
- return err
- }
- if _, err := buf.WriteString(" ("); err != nil {
- return err
- }
- for i, key := range in.KeyList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- switch key.Type {
- case ast.PartitionKeyTypeColumn:
- if err := writeSurrounding(buf, key.Key, `"`); err != nil {
- return err
- }
- case ast.PartitionKeyTypeExpression:
- if _, err := buf.WriteString("("); err != nil {
- return err
- }
- if _, err := buf.WriteString(key.Key); err != nil {
- return err
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- default:
- }
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
-
- return nil
-}
-
-func deparseTableConstraint(context DeparseContext, in *ast.ConstraintDef, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if in.Name != "" {
- if _, err := buf.WriteString("CONSTRAINT "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.Name, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- }
- return deparseConstraintDef(context, in, buf)
-}
-
-func deparseColumnDef(context DeparseContext, in *ast.ColumnDef, buf *strings.Builder) error {
- if err := context.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if err := writeSurrounding(buf, in.ColumnName, "\""); err != nil {
- return err
- }
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- if err := deparseDataType(context, in.Type, buf); err != nil {
- return err
- }
- for _, constraint := range in.ConstraintList {
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- if err := deparseColumnConstraint(context, constraint, buf); err != nil {
- return err
- }
- }
- return nil
-}
-
-func deparseColumnConstraint(_ DeparseContext, in *ast.ConstraintDef, buf *strings.Builder) error {
- if in.Name != "" {
- if _, err := buf.WriteString("CONSTRAINT "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.Name, "\""); err != nil {
- return err
- }
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- }
- switch in.Type {
- case ast.ConstraintTypeNull:
- if _, err := buf.WriteString("NULL"); err != nil {
- return err
- }
- case ast.ConstraintTypeNotNull:
- if _, err := buf.WriteString("NOT NULL"); err != nil {
- return err
- }
- case ast.ConstraintTypeUnique:
- if _, err := buf.WriteString("UNIQUE"); err != nil {
- return err
- }
- case ast.ConstraintTypePrimary:
- if _, err := buf.WriteString("PRIMARY KEY"); err != nil {
- return err
- }
- case ast.ConstraintTypeDefault:
- if _, err := buf.WriteString("DEFAULT "); err != nil {
- return err
- }
- if _, err := buf.WriteString(in.Expression.Text()); err != nil {
- return err
- }
- case ast.ConstraintTypeGenerated:
- if _, err := fmt.Fprintf(buf, "GENERATED ALWAYS AS (%s) STORED", in.Expression.Text()); err != nil {
- return err
- }
- default:
- return errors.Errorf("failed to deparse column constraint: not support %d", in.Type)
- }
- return nil
-}
-
-func deparseTableDef(_ DeparseContext, in *ast.TableDef, buf *strings.Builder) error {
- if in.Schema != "" {
- if err := writeSurrounding(buf, in.Schema, "\""); err != nil {
- return err
- }
- if _, err := buf.WriteString("."); err != nil {
- return err
- }
- }
- return writeSurrounding(buf, in.Name, "\"")
-}
-
-func deparseDataType(_ DeparseContext, in ast.DataType, buf *strings.Builder) error {
- switch node := in.(type) {
- case *ast.Integer:
- switch node.Size {
- case 8:
- if _, err := buf.WriteString("bigint"); err != nil {
- return err
- }
- case 4:
- if _, err := buf.WriteString("integer"); err != nil {
- return err
- }
- case 2:
- if _, err := buf.WriteString("smallint"); err != nil {
- return err
- }
- default:
- return errors.Errorf("failed to deparse integer with %d size", node.Size)
- }
- case *ast.Decimal:
- if _, err := buf.WriteString("numeric"); err != nil {
- return err
- }
- if node.Precision != 0 {
- if _, err := buf.WriteString("("); err != nil {
- return err
- }
- if _, err := buf.WriteString(strconv.Itoa(node.Precision)); err != nil {
- return err
- }
- }
- if node.Scale != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- if _, err := buf.WriteString(strconv.Itoa(node.Scale)); err != nil {
- return err
- }
- }
- if node.Precision != 0 {
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- }
- case *ast.Float:
- switch node.Size {
- case 8:
- if _, err := buf.WriteString("double precision"); err != nil {
- return err
- }
- case 4:
- if _, err := buf.WriteString("real"); err != nil {
- return err
- }
- default:
- return errors.Errorf("failed to deparse float with %d size", node.Size)
- }
- case *ast.Serial:
- switch node.Size {
- case 8:
- if _, err := buf.WriteString("bigserial"); err != nil {
- return err
- }
- case 4:
- if _, err := buf.WriteString("serial"); err != nil {
- return err
- }
- case 2:
- if _, err := buf.WriteString("smallserial"); err != nil {
- return err
- }
- default:
- return errors.Errorf("failed to deparse serial with %d size", node.Size)
- }
- case *ast.Character:
- if _, err := buf.WriteString("character("); err != nil {
- return err
- }
- if _, err := buf.WriteString(strconv.Itoa(node.Size)); err != nil {
- return err
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- case *ast.CharacterVarying:
- if _, err := buf.WriteString("character varying("); err != nil {
- return err
- }
- if _, err := buf.WriteString(strconv.Itoa(node.Size)); err != nil {
- return err
- }
- if _, err := buf.WriteString(")"); err != nil {
- return err
- }
- case *ast.Text:
- if _, err := buf.WriteString("text"); err != nil {
- return err
- }
- case *ast.JSON:
- text := "json"
- if node.JSONB {
- text = "jsonb"
- }
- if _, err := buf.WriteString(text); err != nil {
- return err
- }
- case *ast.UnconvertedDataType:
- if _, err := buf.WriteString(node.Text()); err != nil {
- return err
- }
- default:
- return errors.Errorf("failed to deparse data type %T", in)
- }
- return nil
-}
-
-func deparseAlterSequence(ctx DeparseContext, in *ast.AlterSequenceStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("ALTER SEQUENCE "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- if err := deparseSequenceName(ctx, in.Name, buf); err != nil {
- return err
- }
- // Write alter items.
- itemContext := DeparseContext{IndentLevel: ctx.IndentLevel + 1}
- if in.Type != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("AS "); err != nil {
- return err
- }
- if err := deparseDataType(DeparseContext{}, in.Type, buf); err != nil {
- return err
- }
- }
-
- if in.IncrementBy != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := fmt.Fprintf(buf, "INCREMENT BY %d", *in.IncrementBy); err != nil {
- return err
- }
- }
-
- if in.NoMinValue {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("NO MINVALUE"); err != nil {
- return err
- }
- } else if in.MinValue != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := fmt.Fprintf(buf, "MINVALUE %d", *in.MinValue); err != nil {
- return err
- }
- }
-
- if in.NoMaxValue {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("NO MAXVALUE"); err != nil {
- return err
- }
- } else if in.MaxValue != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := fmt.Fprintf(buf, "MAXVALUE %d", *in.MaxValue); err != nil {
- return err
- }
- }
-
- if in.StartWith != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := fmt.Fprintf(buf, "START WITH %d", *in.StartWith); err != nil {
- return err
- }
- }
-
- if in.RestartWith != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := fmt.Fprintf(buf, "RESTART WITH %d", *in.RestartWith); err != nil {
- return err
- }
- }
-
- if in.Cache != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := fmt.Fprintf(buf, "CACHE %d", *in.Cache); err != nil {
- return err
- }
- }
-
- if in.Cycle != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if !*in.Cycle {
- if _, err := buf.WriteString("NO "); err != nil {
- return err
- }
- }
-
- if _, err := buf.WriteString("CYCLE"); err != nil {
- return err
- }
- }
-
- if in.OwnedByNone {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("OWNED BY NONE"); err != nil {
- return err
- }
- } else if in.OwnedBy != nil {
- if err := buf.WriteByte('\n'); err != nil {
- return err
- }
- if err := itemContext.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
-
- if _, err := buf.WriteString("OWNED BY "); err != nil {
- return err
- }
- if err := deparseColumnNameDef(DeparseContext{}, in.OwnedBy, buf); err != nil {
- return err
- }
- }
- return nil
-}
-
-func deparseDropFunction(ctx DeparseContext, in *ast.DropFunctionStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("DROP FUNCTION "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- for i, function := range in.FunctionList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := deparseFunctionSignature(function, buf); err != nil {
- return err
- }
- }
- return deparseDropBehavior(ctx, in.Behavior, buf)
-}
-
-func deparseFunctionSignature(function *ast.FunctionDef, buf *strings.Builder) error {
- if function.Schema != "" {
- if err := writeSurrounding(buf, function.Schema, `"`); err != nil {
- return err
- }
- if err := buf.WriteByte('.'); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, function.Name, `"`); err != nil {
- return err
- }
- if err := buf.WriteByte('('); err != nil {
- return err
- }
- total := 0
- for _, parameter := range function.ParameterList {
- if parameter.Mode == ast.FunctionParameterModeOut {
- continue
- }
- if total != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- total++
- if err := deparseDataType(DeparseContext{}, parameter.Type, buf); err != nil {
- return err
- }
- }
- return buf.WriteByte(')')
-}
-
-func deparseRenameSchema(_ DeparseContext, in *ast.RenameSchemaStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("ALTER SCHEMA "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.Schema, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" RENAME TO "); err != nil {
- return err
- }
- return writeSurrounding(buf, in.NewName, `"`)
-}
-
-func deparseAlterType(ctx DeparseContext, in *ast.AlterTypeStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("ALTER TYPE "); err != nil {
- return err
- }
- if in.Type.Schema != "" {
- if err := writeSurrounding(buf, in.Type.Schema, `"`); err != nil {
- return err
- }
- if err := buf.WriteByte('.'); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, in.Type.Name, `"`); err != nil {
- return err
- }
- if err := buf.WriteByte(' '); err != nil {
- return err
- }
-
- for _, item := range in.AlterItemList {
- if node, ok := item.(*ast.AddEnumLabelStmt); ok {
- // The ADD ENUM VALUE statement use the cannot share the AlterType statement with other alter items.
- return deparseAddEnumValue(ctx, node, buf)
- }
- }
- return nil
-}
-
-func deparseAddEnumValue(_ DeparseContext, in *ast.AddEnumLabelStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("ADD VALUE "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.NewLabel, "'"); err != nil {
- return err
- }
- switch in.Position {
- case ast.PositionTypeEnd:
- return nil
- case ast.PositionTypeBefore:
- if _, err := buf.WriteString(" BEFORE "); err != nil {
- return err
- }
- case ast.PositionTypeAfter:
- if _, err := buf.WriteString(" AFTER "); err != nil {
- return err
- }
- default:
- }
- return writeSurrounding(buf, in.NeighborLabel, "'")
-}
-
-func deparseDropType(ctx DeparseContext, in *ast.DropTypeStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("DROP TYPE "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- for i, tp := range in.TypeNameList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if tp.Schema != "" {
- if err := writeSurrounding(buf, tp.Schema, `"`); err != nil {
- return err
- }
- if err := buf.WriteByte('.'); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, tp.Name, `"`); err != nil {
- return err
- }
- }
- return deparseDropBehavior(ctx, in.Behavior, buf)
-}
-
-func deparseDropTrigger(ctx DeparseContext, in *ast.DropTriggerStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("DROP TRIGGER "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, in.Trigger.Name, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString(" ON "); err != nil {
- return err
- }
- if err := deparseTableDef(DeparseContext{}, in.Trigger.Table, buf); err != nil {
- return err
- }
- return deparseDropBehavior(ctx, in.Behavior, buf)
-}
-
-func deparseDropExtension(ctx DeparseContext, in *ast.DropExtensionStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("DROP EXTENSION "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- for i, name := range in.NameList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, name, `"`); err != nil {
- return err
- }
- }
- return deparseDropBehavior(ctx, in.Behavior, buf)
-}
-
-func deparseDropSequence(ctx DeparseContext, in *ast.DropSequenceStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("DROP SEQUENCE "); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString("IF EXISTS "); err != nil {
- return err
- }
- }
- for i, sequence := range in.SequenceNameList {
- if i != 0 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := deparseSequenceName(ctx, sequence, buf); err != nil {
- return err
- }
- }
- return deparseDropBehavior(ctx, in.Behavior, buf)
-}
-
-func deparseCreateSequence(ctx DeparseContext, in *ast.CreateSequenceStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("CREATE SEQUENCE "); err != nil {
- return err
- }
- if in.IfNotExists {
- if _, err := buf.WriteString("IF NOT EXISTS "); err != nil {
- return err
- }
- }
- if err := deparseSequenceName(ctx, in.SequenceDef.SequenceName, buf); err != nil {
- return err
- }
- return depraseSequenceDef(DeparseContext{IndentLevel: ctx.IndentLevel + 1}, &in.SequenceDef, buf)
-}
-
-func depraseSequenceDef(ctx DeparseContext, in *ast.SequenceDef, buf *strings.Builder) error {
- if in.SequenceDataType != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("AS "); err != nil {
- return err
- }
- if err := deparseDataType(ctx, in.SequenceDataType, buf); err != nil {
- return err
- }
- }
- if in.IncrementBy != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(buf, "INCREMENT BY %d", *in.IncrementBy); err != nil {
- return err
- }
- }
- if in.MinValue != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(buf, "MINVALUE %d", *in.MinValue); err != nil {
- return err
- }
- } else {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("NO MINVALUE"); err != nil {
- return err
- }
- }
- if in.MaxValue != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(buf, "MAXVALUE %d", *in.MaxValue); err != nil {
- return err
- }
- } else {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("NO MAXVALUE"); err != nil {
- return err
- }
- }
- if in.StartWith != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(buf, "START WITH %d", *in.StartWith); err != nil {
- return err
- }
- }
- if in.Cache != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(buf, "CACHE %d", *in.Cache); err != nil {
- return err
- }
- }
- if in.Cycle {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("CYCLE"); err != nil {
- return err
- }
- }
- if in.OwnedBy != nil {
- if _, err := buf.WriteString("\n"); err != nil {
- return err
- }
- if err := ctx.WriteIndent(buf, deparseIndentString); err != nil {
- return err
- }
- if _, err := buf.WriteString("OWNED BY "); err != nil {
- return err
- }
- if err := deparseColumnNameDef(ctx, in.OwnedBy, buf); err != nil {
- return err
- }
- }
- return nil
-}
-
-func deparseColumnNameDef(ctx DeparseContext, in *ast.ColumnNameDef, buf *strings.Builder) error {
- if err := deparseTableDef(ctx, in.Table, buf); err != nil {
- return err
- }
- if in.ColumnName != "" {
- if _, err := buf.WriteString("."); err != nil {
- return err
- }
- if err := writeSurrounding(buf, in.ColumnName, `"`); err != nil {
- return err
- }
- }
- return nil
-}
-
-func deparseSequenceName(_ DeparseContext, in *ast.SequenceNameDef, buf *strings.Builder) error {
- if in.Schema != "" {
- if err := writeSurrounding(buf, in.Schema, `"`); err != nil {
- return err
- }
- if _, err := buf.WriteString("."); err != nil {
- return err
- }
- }
- return writeSurrounding(buf, in.Name, "\"")
-}
-
-func deparseCreateSchema(ctx DeparseContext, in *ast.CreateSchemaStmt, buf *strings.Builder) error {
- if _, err := buf.WriteString("CREATE SCHEMA "); err != nil {
- return err
- }
-
- if in.IfNotExists {
- if _, err := buf.WriteString("IF NOT EXISTS "); err != nil {
- return err
- }
- }
- if in.Name != "" {
- if err := writeSurrounding(buf, in.Name, `"`); err != nil {
- return err
- }
- }
- if in.RoleSpec != nil && in.RoleSpec.Type != ast.RoleSpecTypeNone {
- if in.Name != "" {
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- }
- if err := deparseRoleSpec(ctx, in.RoleSpec, buf); err != nil {
- return err
- }
- }
- for _, ele := range in.SchemaElementList {
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- if createTableStmt, ok := ele.(*ast.CreateTableStmt); ok {
- if err := deparseCreateTable(ctx, createTableStmt, buf); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-func deparseRoleSpec(_ DeparseContext, in *ast.RoleSpec, buf *strings.Builder) error {
- if in != nil && in.Type != ast.RoleSpecTypeNone {
- if _, err := buf.WriteString("AUTHORIZATION "); err != nil {
- return err
- }
- switch in.Type {
- case ast.RoleSpecTypeUser:
- if err := writeSurrounding(buf, in.Value, `"`); err != nil {
- return err
- }
- case ast.RoleSpecTypeCurrentRole:
- if _, err := buf.WriteString("CURRENT_ROLE"); err != nil {
- return err
- }
- case ast.RoleSpecTypeCurrentUser:
- if _, err := buf.WriteString("CURRENT_USER"); err != nil {
- return err
- }
- case ast.RoleSpecTypeSessionUser:
- if _, err := buf.WriteString("SESSION_USER"); err != nil {
- return err
- }
- default:
- }
- }
- return nil
-}
-
-func deparseDropSchema(_ DeparseContext, in *ast.DropSchemaStmt, buf *strings.Builder) error {
- if in == nil {
- return nil
- }
- if _, err := buf.WriteString("DROP SCHEMA"); err != nil {
- return err
- }
- if in.IfExists {
- if _, err := buf.WriteString(" IF EXISTS"); err != nil {
- return err
- }
- }
- for idx, schema := range in.SchemaList {
- if idx >= 1 {
- if _, err := buf.WriteString(","); err != nil {
- return err
- }
- }
- if _, err := buf.WriteString(" "); err != nil {
- return err
- }
- if err := writeSurrounding(buf, schema, `"`); err != nil {
- return err
- }
- }
- return deparseDropBehavior(DeparseContext{}, in.Behavior, buf)
-}
-
-func deparseDropBehavior(_ DeparseContext, behavior ast.DropBehavior, buf *strings.Builder) error {
- if behavior == ast.DropBehaviorCascade {
- if _, err := buf.WriteString(" CASCADE"); err != nil {
- return err
- }
- }
- return nil
-}
-
-func deparseKeyList(_ DeparseContext, in []string, buf *strings.Builder) error {
- if len(in) == 0 {
- return nil
- }
- for idx, key := range in {
- if idx >= 1 {
- if _, err := buf.WriteString(", "); err != nil {
- return err
- }
- }
- if err := writeSurrounding(buf, key, `"`); err != nil {
- return err
- }
- }
- return nil
-}
-
-func writeSurrounding(buf *strings.Builder, s string, enclosure string) error {
- if _, err := buf.WriteString(enclosure); err != nil {
- return err
- }
- if _, err := buf.WriteString(s); err != nil {
- return err
- }
- if _, err := buf.WriteString(enclosure); err != nil {
- return err
- }
- return nil
-}
diff --git a/backend/plugin/parser/pg/legacy/deparse_test.go b/backend/plugin/parser/pg/legacy/deparse_test.go
deleted file mode 100644
index 082b333a72..0000000000
--- a/backend/plugin/parser/pg/legacy/deparse_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package legacy
-
-import (
- "io"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/stretchr/testify/require"
- "gopkg.in/yaml.v3"
-)
-
-// TestDeparseData is the test data struct.
-type TestDeparseData struct {
- Stmt string `yaml:"stmt"`
- Want string `yaml:"want"`
-}
-
-func runDeparseTest(t *testing.T, file string, record bool) {
- var tests []TestDeparseData
- filepath := filepath.Join("test-data", file)
- yamlFile, err := os.Open(filepath)
- require.NoError(t, err)
- defer yamlFile.Close()
-
- byteValue, err := io.ReadAll(yamlFile)
- require.NoError(t, err)
- err = yaml.Unmarshal(byteValue, &tests)
- require.NoError(t, err)
-
- for i, test := range tests {
- nodeList, err := Parse(ParseContext{}, test.Stmt)
- require.NoError(t, err)
- require.Len(t, nodeList, 1)
- res, err := Deparse(DeparseContext{}, nodeList[0])
- require.NoError(t, err)
- if record {
- tests[i].Want = res
- } else {
- require.Equal(t, test.Want, res, test.Stmt)
- }
- }
-
- if record {
- err := yamlFile.Close()
- require.NoError(t, err)
- byteValue, err = yaml.Marshal(tests)
- require.NoError(t, err)
- err = os.WriteFile(filepath, byteValue, 0644)
- require.NoError(t, err)
- }
-}
-
-func TestDeparse(t *testing.T) {
- testFileList := []string{
- // Table
- "test_create_table_data.yaml",
- "test_alter_table_data.yaml",
- "test_drop_table_data.yaml",
- // Schema
- "test_create_schema_data.yaml",
- "test_drop_schema_data.yaml",
- "test_rename_schema_data.yaml",
- // Index
- "test_create_index_data.yaml",
- "test_drop_index_data.yaml",
- // Sequence
- "test_create_sequence_data.yaml",
- "test_alter_sequence_data.yaml",
- "test_drop_sequence_data.yaml",
- // Extension
- "test_extension_data.yaml",
- // Function
- "test_function_data.yaml",
- // Trigger
- "test_trigger_data.yaml",
- // Type
- "test_type_data.yaml",
- // Comment
- "test_comment_data.yaml",
- }
- for _, test := range testFileList {
- runDeparseTest(t, test, false /* record */)
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/error.go b/backend/plugin/parser/pg/legacy/error.go
deleted file mode 100644
index 88b5ddc873..0000000000
--- a/backend/plugin/parser/pg/legacy/error.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package legacy
-
-import "github.com/pkg/errors"
-
-// ConvertError is the conversion error.
-// Because this module is still in its early stages and lacks sufficient testing to ensure compatibility,
-// we add ConvertError to differentiate between syntax errors and conversion errors.
-// We will remove it in the future.
-// TODO(rebelice): remove it.
-type ConvertError struct {
- err error
-}
-
-// Error implements the error interface.
-func (e *ConvertError) Error() string {
- return e.err.Error()
-}
-
-// NewConvertErrorf returns the new conversion error.
-func NewConvertErrorf(format string, a ...any) *ConvertError {
- return &ConvertError{err: errors.Errorf(format, a...)}
-}
diff --git a/backend/plugin/parser/pg/legacy/parser.go b/backend/plugin/parser/pg/legacy/parser.go
deleted file mode 100644
index db5929f469..0000000000
--- a/backend/plugin/parser/pg/legacy/parser.go
+++ /dev/null
@@ -1,160 +0,0 @@
-// Package legacy implements the parser for PostgreSQL.
-package legacy
-
-import (
- "strings"
-
- pgquery "github.com/pganalyze/pg_query_go/v6"
- "github.com/pganalyze/pg_query_go/v6/parser"
- "github.com/pkg/errors"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- "github.com/bytebase/bytebase/backend/plugin/parser/tokenizer"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-)
-
-// Disabled legacy parser registration - now using ANTLR parser
-// func init() {
-// base.RegisterParseFunc(storepb.Engine_POSTGRES, parsePostgresForRegistry)
-// }
-
-// parsePostgresForRegistry is the ParseFunc for PostgreSQL.
-// Returns []ast.Node (github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast) on success.
-func parsePostgresForRegistry(statement string) (any, error) {
- nodes, err := Parse(ParseContext{}, statement)
- if err != nil {
- // If it's already a SyntaxError, return it as-is
- if _, ok := err.(*base.SyntaxError); ok {
- return nil, err
- }
- // Otherwise, wrap it as a SyntaxError with line 1
- return nil, &base.SyntaxError{
- Position: &storepb.Position{Line: 1},
- Message: err.Error(),
- }
- }
- // Filter out nil nodes
- var res []ast.Node
- for _, node := range nodes {
- if node != nil {
- res = append(res, node)
- }
- }
- return res, nil
-}
-
-const (
- operatorLike string = "~~"
- operatorNotLike string = "!~~"
- // DeparseIndentString is the string for each indent level.
- deparseIndentString = " "
-)
-
-// ParseContext is the context for parsing.
-type ParseContext struct {
-}
-
-// DeparseContext is the contxt for restoring.
-type DeparseContext struct {
- // IndentLevel is indent level for current line.
- // The parser deparses statements with the indent level for pretty format.
- IndentLevel int
-}
-
-// WriteIndent is the helper function to write indent string.
-func (ctx DeparseContext) WriteIndent(buf *strings.Builder, indent string) error {
- for i := 0; i < ctx.IndentLevel; i++ {
- if _, err := buf.WriteString(indent); err != nil {
- return err
- }
- }
- return nil
-}
-
-// Parse implements the parser.Parser interface.
-func Parse(_ ParseContext, statement string) ([]ast.Node, error) {
- res, err := pgquery.Parse(statement)
- if err != nil {
- // Extract line number from parser error's cursor position
- return nil, convertParserError(statement, err)
- }
-
- // skip the setting line stage
- if len(res.Stmts) == 0 {
- return nil, nil
- }
-
- // setting line stage
- textList, err := splitSQL(statement)
- if err != nil {
- return nil, err
- }
- if len(res.Stmts) != len(textList) {
- return nil, errors.Errorf("split multi-SQL failed: the length should be %d, but get %d. stmt: \"%s\"", len(res.Stmts), len(textList), statement)
- }
-
- var nodeList []ast.Node
-
- for i, stmt := range res.Stmts {
- node, err := convert(stmt.Stmt, textList[i])
- if err != nil {
- return nil, err
- }
- nodeList = append(nodeList, node)
- }
- return nodeList, nil
-}
-
-// convertParserError converts a pgquery parser error to a base.SyntaxError with the correct line number.
-// It extracts the line number from the parser.Error's Cursorpos field.
-func convertParserError(statement string, err error) error {
- line := int32(1)
-
- // Try to extract cursor position from parser.Error
- if perr, ok := err.(*parser.Error); ok {
- if perr.Cursorpos > 0 {
- // Count newlines up to cursor position to get line number
- // Cursorpos is 1-based byte offset
- lineCount := 1
- for i := 0; i < perr.Cursorpos-1 && i < len(statement); i++ {
- if statement[i] == '\n' {
- lineCount++
- }
- }
- line = int32(lineCount)
- }
- }
-
- return &base.SyntaxError{
- Position: &storepb.Position{Line: line},
- Message: err.Error(),
- }
-}
-
-// splitSQL splits the given SQL statement into multiple SQL statements.
-func splitSQL(statement string) ([]base.SingleSQL, error) {
- t := tokenizer.NewTokenizer(statement)
- list, err := t.SplitPostgreSQLMultiSQL()
- if err != nil {
- return nil, err
- }
- var results []base.SingleSQL
- for _, sql := range list {
- if sql.Empty {
- continue
- }
- results = append(results, sql)
- }
- return results, nil
-}
-
-// Deparse implements the parser.Deparse interface.
-func Deparse(context DeparseContext, node ast.Node) (string, error) {
- buf := &strings.Builder{}
- if err := deparseImpl(context, node, buf); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
diff --git a/backend/plugin/parser/pg/legacy/parser_test.go b/backend/plugin/parser/pg/legacy/parser_test.go
deleted file mode 100644
index 0a53f47b20..0000000000
--- a/backend/plugin/parser/pg/legacy/parser_test.go
+++ /dev/null
@@ -1,151 +0,0 @@
-package legacy
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
-)
-
-func TestParsePostgresForRegistryError(t *testing.T) {
- tests := []struct {
- name string
- statement string
- expectedLine int32 // Expected to be the END line of the statement with error
- }{
- {
- name: "single statement with syntax error",
- statement: "SELECT * FRAM t1;",
- expectedLine: 1,
- },
- {
- name: "multi-line single statement with syntax error",
- statement: `SELECT
- 1,
- 2
-FRAM t1;`,
- expectedLine: 4, // Last line of the statement
- },
- {
- name: "multiple statements - error in first",
- statement: `SELECT * FRAM t1;
-SELECT 1;
-SELECT 2;`,
- expectedLine: 1, // End of first statement
- },
- {
- name: "multiple statements - error in second",
- statement: `SELECT 1;
-SELECT * FRAM t2;
-SELECT 2;`,
- expectedLine: 2, // End of second statement
- },
- {
- name: "multiple statements - error in third",
- statement: `SELECT 1;
-SELECT 2;
-SELECT * FRAM t3;`,
- expectedLine: 3, // End of third statement
- },
- {
- name: "multi-line statements - error in second statement",
- statement: `SELECT
- 1,
- 2
-FROM t1;
-SELECT
- *
-FRAM t2;`,
- expectedLine: 7, // End of second statement
- },
- {
- name: "complex multi-line - error on specific line",
- statement: `-- Comment line 1
-SELECT 1;
--- Comment line 3
-SELECT
- a,
- b,
- c,
- d
-FRAM t1;
-SELECT 2;`,
- expectedLine: 9, // End of the SELECT statement with error
- },
- {
- name: "error with WHERE typo",
- statement: `SELECT 1;
-SELECT 2;
-SELECT * FROM t1 WHER id = 1;`,
- expectedLine: 3, // End of third statement
- },
- {
- name: "error in second statement with indentation",
- statement: `select 1;
- selec 2;
-select 3;`,
- expectedLine: 2, // End of second statement
- },
- }
-
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- _, err := parsePostgresForRegistry(test.statement)
- require.Error(t, err, "expected syntax error for statement: %s", test.statement)
- syntaxErr, ok := err.(*base.SyntaxError)
- require.True(t, ok, "expected error to be *base.SyntaxError, got %T", err)
- require.NotNil(t, syntaxErr.Position, "expected position to be set")
- require.Equal(t, test.expectedLine, syntaxErr.Position.GetLine(),
- "incorrect line number for statement:\n%s\nError: %s", test.statement, syntaxErr.Message)
- })
- }
-}
-
-func TestParsePostgresForRegistrySuccess(t *testing.T) {
- tests := []struct {
- name string
- statement string
- }{
- {
- name: "single statement",
- statement: "SELECT 1;",
- },
- {
- name: "multiple statements",
- statement: `SELECT 1;
-SELECT 2;
-SELECT 3;`,
- },
- {
- name: "multi-line statement",
- statement: `SELECT
- 1,
- 2,
- 3
-FROM t1;`,
- },
- {
- name: "complex multi-line statements",
- statement: `-- Comment
-SELECT 1;
-
-SELECT
- a,
- b,
- c
-FROM t1
-WHERE a > 1;
-
-SELECT * FROM t2;`,
- },
- }
-
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- result, err := parsePostgresForRegistry(test.statement)
- require.NoError(t, err, "unexpected error for statement: %s", test.statement)
- require.NotNil(t, result, "expected non-nil result")
- })
- }
-}
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_alter_sequence_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_alter_sequence_data.yaml
deleted file mode 100644
index 51416eaf33..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_alter_sequence_data.yaml
+++ /dev/null
@@ -1,34 +0,0 @@
-- stmt: |-
- ALTER SEQUENCE IF EXISTS public.tbl_seq_id_seq
- AS bigint
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- START WITH 1
- RESTART WITH 1
- CACHE 1
- NO CYCLE
- OWNED BY NONE;
- want: |-
- ALTER SEQUENCE IF EXISTS "public"."tbl_seq_id_seq"
- AS bigint
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- START WITH 1
- RESTART WITH 1
- CACHE 1
- NO CYCLE
- OWNED BY NONE;
-- stmt: |-
- ALTER SEQUENCE IF EXISTS public.tbl_seq_id_seq
- MINVALUE 1
- MAXVALUE 1
- CYCLE
- OWNED BY public.tbl.id;
- want: |-
- ALTER SEQUENCE IF EXISTS "public"."tbl_seq_id_seq"
- MINVALUE 1
- MAXVALUE 1
- CYCLE
- OWNED BY "public"."tbl"."id";
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_alter_table_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_alter_table_data.yaml
deleted file mode 100644
index 63530a8d8a..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_alter_table_data.yaml
+++ /dev/null
@@ -1,134 +0,0 @@
-- stmt: alter table t add column a int
- want: |-
- ALTER TABLE "t"
- ADD COLUMN "a" integer;
-- stmt: alter table t alter column a type varchar(20)
- want: |-
- ALTER TABLE "t"
- ALTER COLUMN "a" SET DATA TYPE character varying(20);
-- stmt: |-
- alter table t
- add column if not exists a integer,
- add column b char(20)
- want: |-
- ALTER TABLE "t"
- ADD COLUMN IF NOT EXISTS "a" integer,
- ADD COLUMN "b" character(20);
-- stmt: |-
- alter table t
- drop column if exists a cascade,
- drop column b
- want: |-
- ALTER TABLE "t"
- DROP COLUMN IF EXISTS "a" CASCADE,
- DROP COLUMN "b";
-- stmt: |-
- alter table t
- alter column c1 set not null,
- alter column c2 drop not null
- want: |-
- ALTER TABLE "t"
- ALTER COLUMN "c1" SET NOT NULL,
- ALTER COLUMN "c2" DROP NOT NULL;
-- stmt: |-
- alter table t
- add unique using index email_idx;
- want: |-
- ALTER TABLE "t"
- ADD UNIQUE USING INDEX "email_idx";
-- stmt: |-
- alter table t
- add unique using index email_idx deferrable;
- want: |-
- ALTER TABLE "t"
- ADD UNIQUE USING INDEX "email_idx" DEFERRABLE;
-- stmt: |-
- alter table t
- add unique using index email_idx INITIALLY DEFERRED;
- want: |-
- ALTER TABLE "t"
- ADD UNIQUE USING INDEX "email_idx" INITIALLY DEFERRED;
-- stmt: |-
- alter table t
- drop constraint unique_tbl_email_key;
- want: |-
- ALTER TABLE "t"
- DROP CONSTRAINT "unique_tbl_email_key";
-- stmt: |-
- alter table t
- drop constraint if exists unique_tbl_email_key;
- want: |-
- ALTER TABLE "t"
- DROP CONSTRAINT IF EXISTS "unique_tbl_email_key";
-- stmt: |-
- alter table t
- add constraint email_unique_key unique(email);
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "email_unique_key" UNIQUE ("email");
-- stmt: |-
- alter table t
- add constraint email_unique_key unique(email) include (email) using index tablespace demo_tablespace;
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "email_unique_key" UNIQUE ("email") INCLUDE ("email") USING INDEX TABLESPACE "demo_tablespace";
-- stmt: alter table t alter column a set default 1+2+3+4
- want: |-
- ALTER TABLE "t"
- ALTER COLUMN "a" SET DEFAULT ((1 + 2) + 3) + 4;
-- stmt: alter table t alter column a drop default
- want: |-
- ALTER TABLE "t"
- ALTER COLUMN "a" DROP DEFAULT;
-- stmt: alter table t add constraint check_a check (a + b > c)
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "check_a" CHECK ((a + b) > c);
-- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c)
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c");
-- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c) match simple on delete no action on update no action
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c");
-- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c) match full on delete set null on update restrict
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c") MATCH FULL ON DELETE SET NULL ON UPDATE RESTRICT;
-- stmt: alter table t add constraint fk_a foreign key (a, b) references t1 (b, c) match full on delete set default on update cascade
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "fk_a" FOREIGN KEY ("a", "b") REFERENCES "t1" ("b", "c") MATCH FULL ON DELETE SET DEFAULT ON UPDATE CASCADE;
-- stmt: |-
- alter table t
- add constraint email_pkey primary key(email, id);
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "email_pkey" PRIMARY KEY ("email", "id");
-- stmt: |-
- alter table t
- add constraint email_pkey primary key(email) include (email) using index tablespace demo_tablespace;
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "email_pkey" PRIMARY KEY ("email") INCLUDE ("email") USING INDEX TABLESPACE "demo_tablespace";
-- stmt: |-
- alter table t
- add constraint circles_c_excl exclude using gist (c WITH &&);
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "circles_c_excl" EXCLUDE USING gist (c WITH &&);
-- stmt: |-
- alter table t
- add constraint circles_c_excl exclude using gist (c WITH &&, d WITH &&) WHERE (a > 0 AND b < 10);
- want: |-
- ALTER TABLE "t"
- ADD CONSTRAINT "circles_c_excl" EXCLUDE USING gist (c WITH &&, d WITH &&) WHERE (a > 0 AND b < 10);
-- stmt: alter table t rename to t1
- want: |-
- ALTER TABLE "t"
- RENAME TO "t1";
-- stmt: alter table t rename column c1 to c2
- want: |-
- ALTER TABLE "t"
- RENAME COLUMN "c1" TO "c2";
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_comment_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_comment_data.yaml
deleted file mode 100644
index 162b5bbbd6..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_comment_data.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-- stmt: COMMENT ON COLUMN public.t4.c IS 'comment with ''; test escape';
- want: COMMENT ON COLUMN "public"."t4"."c" IS 'comment with ''; test escape';
-- stmt: COMMENT ON TABLE public.t4 IS 'comment with ''; test escape';
- want: COMMENT ON TABLE "public"."t4" IS 'comment with ''; test escape';
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_create_index_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_create_index_data.yaml
deleted file mode 100644
index 52239bad6c..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_create_index_data.yaml
+++ /dev/null
@@ -1,8 +0,0 @@
-- stmt: create index concurrently idx_1 on public.t using btree (a, b, c)
- want: CREATE INDEX CONCURRENTLY "idx_1" ON "public"."t" USING btree (a, b, c);
-- stmt: create unique index if not exists idx_1 on public.t(a nulls first, b desc nulls last, c asc)
- want: CREATE UNIQUE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING btree (a NULLS FIRST, b DESC NULLS LAST, c);
-- stmt: create index if not exists idx_1 on public.t using hash (a, b, c)
- want: CREATE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING hash (a, b, c);
-- stmt: create index if not exists idx_1 on public.t using btree((a+b) desc, c)
- want: CREATE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING btree ((a + b) DESC, c);
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_create_schema_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_create_schema_data.yaml
deleted file mode 100644
index 87f8979b5a..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_create_schema_data.yaml
+++ /dev/null
@@ -1,13 +0,0 @@
-- stmt: create schema myschema authorization bytebase create table tbl(id INT);
- want: |-
- CREATE SCHEMA "myschema" AUTHORIZATION "bytebase" CREATE TABLE "tbl" (
- "id" integer
- );
-- stmt: create schema if not exists myschema authorization bytebase;
- want: CREATE SCHEMA IF NOT EXISTS "myschema" AUTHORIZATION "bytebase";
-- stmt: create schema if not exists myschema
- want: CREATE SCHEMA IF NOT EXISTS "myschema";
-- stmt: create schema if not exists "myschema" authorization bytebase
- want: CREATE SCHEMA IF NOT EXISTS "myschema" AUTHORIZATION "bytebase";
-- stmt: create schema if not exists authorization bytebase
- want: CREATE SCHEMA IF NOT EXISTS AUTHORIZATION "bytebase";
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_create_sequence_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_create_sequence_data.yaml
deleted file mode 100644
index 025e44879c..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_create_sequence_data.yaml
+++ /dev/null
@@ -1,25 +0,0 @@
-- stmt: create sequence public.tbl_seq_id_seq AS integer increment by 1 start with 1 minvalue 1 maxvalue 1 cache 1 cycle owned by public.tbl.id;
- want: |-
- CREATE SEQUENCE "public"."tbl_seq_id_seq"
- AS integer
- INCREMENT BY 1
- MINVALUE 1
- MAXVALUE 1
- START WITH 1
- CACHE 1
- CYCLE
- OWNED BY "public"."tbl"."id";
-- stmt: create sequence public.tbl_seq_id_seq as bigint increment by 1 start with 1 no minvalue no maxvalue cache 1;
- want: |-
- CREATE SEQUENCE "public"."tbl_seq_id_seq"
- AS bigint
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- START WITH 1
- CACHE 1;
-- stmt: create sequence if not exists public.tbl_seq_id_seq;
- want: |-
- CREATE SEQUENCE IF NOT EXISTS "public"."tbl_seq_id_seq"
- NO MINVALUE
- NO MAXVALUE;
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_create_table_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_create_table_data.yaml
deleted file mode 100644
index cf2802b091..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_create_table_data.yaml
+++ /dev/null
@@ -1,111 +0,0 @@
-- stmt: create table "TechBook"(a "user defined data type")
- want: |-
- CREATE TABLE "TechBook" (
- "a" "user defined data type"
- );
-- stmt: |-
- CREATE TABLE tech_book(
- a char(20),
- b character(30) NULL default 'this is default',
- c varchar(330),
- d character varying(400),
- e text
- );
- want: |-
- CREATE TABLE "tech_book" (
- "a" character(20),
- "b" character(30) NULL DEFAULT 'this is default',
- "c" character varying(330),
- "d" character varying(400),
- "e" text
- );
-- stmt: |-
- CREATE TABLE tech_book(
- a smallint,
- b integer,
- c bigint,
- d decimal(10, 2),
- e numeric(4),
- f real,
- g double precision,
- h smallserial,
- i serial,
- j bigserial,
- k int8,
- l serial8,
- m float8,
- n int default 1+23+5,
- o int4,
- p float4,
- q int2,
- r serial2,
- s serial4,
- t decimal)
- want: |-
- CREATE TABLE "tech_book" (
- "a" smallint,
- "b" integer,
- "c" bigint,
- "d" numeric(10, 2),
- "e" numeric(4),
- "f" real,
- "g" double precision,
- "h" smallserial,
- "i" serial,
- "j" bigserial,
- "k" bigint,
- "l" bigserial,
- "m" double precision,
- "n" integer DEFAULT (1 + 23) + 5,
- "o" integer,
- "p" real,
- "q" smallint,
- "r" smallserial,
- "s" serial,
- "t" numeric
- );
-- stmt: |-
- CREATE TABLE t(
- a int,
- b int,
- c int,
- PRIMARY KEY(a, b, c),
- CONSTRAINT uk1 UNIQUE(a, b)
- ) partition by range(a, b, (c+1))
- want: |-
- CREATE TABLE "t" (
- "a" integer,
- "b" integer,
- "c" integer,
- PRIMARY KEY ("a", "b", "c"),
- CONSTRAINT "uk1" UNIQUE ("a", "b")
- )
- PARTITION BY RANGE ("a", "b", (c + 1));
-
-- stmt: |-
- CREATE TABLE t (
- a numeric,
- b numeric,
- c numeric GENERATED ALWAYS AS (a * b) STORED
- );
- want: |-
- CREATE TABLE "t" (
- "a" numeric,
- "b" numeric,
- "c" numeric GENERATED ALWAYS AS (a * b) STORED
- );
-
-- stmt: |-
- CREATE TABLE public.t (
- action text NOT NULL,
- action_date timestamp NOT NULL,
- number smallint GENERATED ALWAYS AS ((date_part('week'::text, ((action_date)::date + '1 day'::interval)))::smallint) STORED,
- year smallint GENERATED ALWAYS AS ((date_part('year'::text, date_trunc('week'::text, action_date)))::smallint) STORED
- );
- want: |-
- CREATE TABLE "public"."t" (
- "action" text NOT NULL,
- "action_date" timestamp NOT NULL,
- "number" smallint GENERATED ALWAYS AS (date_part('week'::text, action_date::date + '1 day'::interval)::smallint) STORED,
- "year" smallint GENERATED ALWAYS AS (date_part('year'::text, date_trunc('week'::text, action_date))::smallint) STORED
- );
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_drop_index_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_drop_index_data.yaml
deleted file mode 100644
index 704468c788..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_drop_index_data.yaml
+++ /dev/null
@@ -1,6 +0,0 @@
-- stmt: drop index if exists idx1, idx2, idx3 cascade
- want: DROP INDEX IF EXISTS "idx1", "idx2", "idx3" CASCADE;
-- stmt: drop index idx1 restrict
- want: DROP INDEX "idx1";
-- stmt: drop index public.idx1 cascade
- want: DROP INDEX "public"."idx1" CASCADE;
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_drop_schema_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_drop_schema_data.yaml
deleted file mode 100644
index 58acd08d3c..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_drop_schema_data.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-- stmt: drop schema myschema
- want: DROP SCHEMA "myschema";
-- stmt: drop schema if exists s1, s2 cascade
- want: DROP SCHEMA IF EXISTS "s1", "s2" CASCADE;
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_drop_sequence_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_drop_sequence_data.yaml
deleted file mode 100644
index 084fb04951..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_drop_sequence_data.yaml
+++ /dev/null
@@ -1,8 +0,0 @@
-- stmt: drop sequence s;
- want: DROP SEQUENCE "s";
-- stmt: drop sequence s1, public.s;
- want: DROP SEQUENCE "s1", "public"."s";
-- stmt: drop sequence if exists s1;
- want: DROP SEQUENCE IF EXISTS "s1";
-- stmt: drop sequence if exists s1 cascade;
- want: DROP SEQUENCE IF EXISTS "s1" CASCADE;
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_drop_table_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_drop_table_data.yaml
deleted file mode 100644
index 92c526d77a..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_drop_table_data.yaml
+++ /dev/null
@@ -1,8 +0,0 @@
-- stmt: drop table t
- want: DROP TABLE "t";
-- stmt: drop table public.t, t1
- want: DROP TABLE "public"."t", "t1";
-- stmt: drop table if exists public.t cascade;
- want: DROP TABLE IF EXISTS "public"."t" CASCADE;
-- stmt: drop table public.t restrict
- want: DROP TABLE "public"."t";
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_extension_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_extension_data.yaml
deleted file mode 100644
index d78e2078cb..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_extension_data.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-- stmt: drop extension hstore, extension_a;
- want: DROP EXTENSION "hstore", "extension_a";
-- stmt: drop extension if exists hstore cascade;
- want: DROP EXTENSION IF EXISTS "hstore" CASCADE;
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_function_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_function_data.yaml
deleted file mode 100644
index bcad4621e2..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_function_data.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-- stmt: drop function func1(a int, b int, c int);
- want: DROP FUNCTION "func1"(integer, integer, integer);
-- stmt: drop function if exists public.func1(a int), func2(OUT int);
- want: DROP FUNCTION IF EXISTS "public"."func1"(integer), "func2"();
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_rename_schema_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_rename_schema_data.yaml
deleted file mode 100644
index 171cab9e56..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_rename_schema_data.yaml
+++ /dev/null
@@ -1,2 +0,0 @@
-- stmt: alter schema s1 rename to s2
- want: ALTER SCHEMA "s1" RENAME TO "s2";
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_trigger_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_trigger_data.yaml
deleted file mode 100644
index 9acfc0505a..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_trigger_data.yaml
+++ /dev/null
@@ -1,2 +0,0 @@
-- stmt: drop trigger if exists trigger1 on public.t1
- want: DROP TRIGGER IF EXISTS "trigger1" ON "public"."t1";
diff --git a/backend/plugin/parser/pg/legacy/test-data/test_type_data.yaml b/backend/plugin/parser/pg/legacy/test-data/test_type_data.yaml
deleted file mode 100644
index 26a5b80fb0..0000000000
--- a/backend/plugin/parser/pg/legacy/test-data/test_type_data.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-- stmt: drop type if exists tp1, public.tp2;
- want: DROP TYPE IF EXISTS "tp1", "public"."tp2";
-- stmt: drop type tp1 cascade;
- want: DROP TYPE "tp1" CASCADE;
-- stmt: alter type public.t1 add value 'a';
- want: ALTER TYPE "public"."t1" ADD VALUE 'a';
-- stmt: alter type public.t1 add value 'a' after 'd';
- want: ALTER TYPE "public"."t1" ADD VALUE 'a' AFTER 'd';
-- stmt: alter type public.t1 add value 'a' before 'x';
- want: ALTER TYPE "public"."t1" ADD VALUE 'a' BEFORE 'x';
diff --git a/backend/plugin/parser/tokenizer/tokenizer.go b/backend/plugin/parser/tokenizer/tokenizer.go
index 06775a0fd3..9a4dff1262 100644
--- a/backend/plugin/parser/tokenizer/tokenizer.go
+++ b/backend/plugin/parser/tokenizer/tokenizer.go
@@ -12,7 +12,6 @@ import (
"github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
)
const (
@@ -202,139 +201,6 @@ func matchMySQLTableConstraint(text string, cons *tidbast.Constraint) bool {
}
}
-// SetLineForPGCreateTableStmt sets the line for columns and table constraints in CREATE TABLE statements.
-func (t *Tokenizer) SetLineForPGCreateTableStmt(node *ast.CreateTableStmt, firstLine int) error {
- // Some statement are recognized as create table statement, but without columns and constraints like:
- // CREATE TABLE t AS SELECT * FROM old_t;
- if len(node.ColumnList) == 0 && len(node.ConstraintList) == 0 {
- return nil
- }
- // We assume that the parser will parse the columns and table constraints according to the order of the raw SQL statements
- // and the identifiers don't equal any keywords in CREATE TABLE statements.
- // If it breaks our assumption, we set the line for columns and table constraints to the first line of the CREATE TABLE statement.
- for _, col := range node.ColumnList {
- col.SetLastLine(node.LastLine())
- for _, inlineCons := range col.ConstraintList {
- inlineCons.SetLastLine(node.LastLine())
- }
- }
- for _, cons := range node.ConstraintList {
- cons.SetLastLine(node.LastLine())
- }
-
- columnPos := 0
- constraintPos := 0
- // find the '(' for CREATE TABLE ... ( ... )
- if err := t.scanTo([]rune{'('}); err != nil {
- return err
- }
-
- // parentheses is the flag for matching parentheses.
- parentheses := 1
- t.skipBlank()
- startPos := t.pos()
- for {
- switch {
- case t.char(0) == '\n':
- t.line++
- t.skip(1)
- case t.char(0) == '/' && t.char(1) == '*':
- if err := t.scanComment(); err != nil {
- return err
- }
- case t.char(0) == '-' && t.char(1) == '-':
- if err := t.scanComment(); err != nil {
- return err
- }
- case t.char(0) == '\'':
- if err := t.scanString('\''); err != nil {
- return err
- }
- case t.char(0) == '$':
- if err := t.scanDoubleDollarQuotedString(); err != nil {
- return err
- }
- case t.char(0) == '"':
- if err := t.scanIdentifier('"'); err != nil {
- return err
- }
- case t.char(0) == '(':
- parentheses++
- t.skip(1)
- case t.char(0) == ')':
- parentheses--
- if parentheses == 0 {
- // This means we find the corresponding ')' for the first '(' in CREATE TABLE statements.
- // We need to check the definition and return.
- def := strings.ToLower(t.getString(startPos, t.pos()-startPos))
- if columnPos < len(node.ColumnList) &&
- strings.Contains(def, strings.ToLower(node.ColumnList[columnPos].ColumnName)) {
- // Consider this text:
- // CREATE TABLE t(
- // a int
- // )
- //
- // Our current location is ')'.
- // The line (t.line + firstLine - 1) is the line of ')',
- // but we want to get the line of 'a int'.
- // So we need minus the aboveNonBlankLineDistance.
- node.ColumnList[columnPos].SetLastLine(t.line + firstLine - 1 - t.aboveNonBlankLineDistance())
- for _, inlineConstraint := range node.ColumnList[columnPos].ConstraintList {
- inlineConstraint.SetLastLine(node.ColumnList[columnPos].LastLine())
- }
- } else if constraintPos < len(node.ConstraintList) &&
- matchTableConstraint(def, node.ConstraintList[constraintPos]) {
- // Consider this text:
- // CREATE TABLE t(
- // a int,
- // UNIQUE (a)
- // )
- //
- // Our current location is ')'.
- // The line (t.line + firstLine - 1) is the line of ')',
- // but we want to get the line of 'UNIQUE (a)'.
- // So we need minus the aboveNonBlankLineDistance.
- node.ConstraintList[constraintPos].SetLastLine(t.line + firstLine - 1 - t.aboveNonBlankLineDistance())
- }
- return nil
- }
- t.skip(1)
- case t.char(0) == ',':
- // e.g. CREATE TABLE t(
- // a int,
- // b int,
- // UNIQUE(a, b),
- // UNIQUE(b)
- // )
- // We don't need to consider the ',' in UNIQUE(a, b)
- if parentheses > 1 {
- t.skip(1)
- continue
- }
- def := strings.ToLower(t.getString(startPos, t.pos()-startPos))
- if columnPos < len(node.ColumnList) &&
- strings.Contains(def, strings.ToLower(node.ColumnList[columnPos].ColumnName)) {
- node.ColumnList[columnPos].SetLastLine(t.line + firstLine - 1)
- for _, inlineConstraint := range node.ColumnList[columnPos].ConstraintList {
- inlineConstraint.SetLastLine(node.ColumnList[columnPos].LastLine())
- }
- columnPos++
- } else if constraintPos < len(node.ConstraintList) &&
- matchTableConstraint(def, node.ConstraintList[constraintPos]) {
- node.ConstraintList[constraintPos].SetLastLine(t.line + firstLine - 1)
- constraintPos++
- }
- t.skip(1)
- t.skipBlank()
- startPos = t.pos()
- case t.char(0) == eofRune:
- return nil
- default:
- t.skip(1)
- }
- }
-}
-
func (t *Tokenizer) aboveNonBlankLineDistance() int {
pos := uint(1)
dis := 0
@@ -349,27 +215,6 @@ func (t *Tokenizer) aboveNonBlankLineDistance() int {
}
}
-// matchTableConstraint matches text as lowercase.
-func matchTableConstraint(text string, cons *ast.ConstraintDef) bool {
- text = strings.ToLower(text)
- if cons.Name != "" {
- return strings.Contains(text, strings.ToLower(cons.Name))
- }
- switch cons.Type {
- case ast.ConstraintTypeCheck:
- return strings.Contains(text, "check")
- case ast.ConstraintTypeUnique:
- return strings.Contains(text, "unique")
- case ast.ConstraintTypePrimary:
- return strings.Contains(text, "primary key")
- case ast.ConstraintTypeForeign:
- return strings.Contains(text, "foreign key")
- default:
- // Unknown constraint type
- return false
- }
-}
-
// SplitTiDBMultiSQL splits the statement to a string slice.
func (t *Tokenizer) SplitTiDBMultiSQL() ([]base.SingleSQL, error) {
var res []base.SingleSQL
diff --git a/backend/plugin/parser/tokenizer/tokenizer_test.go b/backend/plugin/parser/tokenizer/tokenizer_test.go
deleted file mode 100644
index 9a70eff29b..0000000000
--- a/backend/plugin/parser/tokenizer/tokenizer_test.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package tokenizer
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/pg/legacy/ast"
-)
-
-// TestSetLineForPGCreateTableStmt tests that the tokenizer handles various CREATE TABLE statements,
-// including partition tables without columns/constraints and regular tables with columns
-func TestSetLineForPGCreateTableStmt(t *testing.T) {
- testCases := []struct {
- name string
- statement string
- hasColumns bool
- hasConstraints bool
- expectError bool
- }{
- {
- name: "Partition table DEFAULT - no columns or constraints",
- statement: "CREATE TABLE mes.insp_oqc_log_default PARTITION OF mes.insp_oqc_log DEFAULT;",
- hasColumns: false,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "Partition table range - no columns or constraints",
- statement: "CREATE TABLE mes.insp_oqc_log_2025q1 PARTITION OF mes.insp_oqc_log FOR VALUES FROM ('2025-01-01') TO ('2025-04-01');",
- hasColumns: false,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "Partition table list - no columns or constraints",
- statement: "CREATE TABLE cities_ab PARTITION OF cities FOR VALUES IN ('New York', 'Chicago');",
- hasColumns: false,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "Partition table hash - no columns or constraints",
- statement: "CREATE TABLE orders_p0 PARTITION OF orders FOR VALUES WITH (modulus 4, remainder 0);",
- hasColumns: false,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "CREATE TABLE AS SELECT - no columns or constraints",
- statement: "CREATE TABLE new_table AS SELECT * FROM old_table;",
- hasColumns: false,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "Regular table with columns",
- statement: "CREATE TABLE test_table (id INT PRIMARY KEY, name VARCHAR(100));",
- hasColumns: true,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "Regular table with columns - multiline",
- statement: `CREATE TABLE test_table (
- id INT PRIMARY KEY,
- name VARCHAR(100),
- created_at TIMESTAMP
- );`,
- hasColumns: true,
- hasConstraints: false,
- expectError: false,
- },
- {
- name: "Table with columns and table constraints",
- statement: "CREATE TABLE test (id INT, name VARCHAR(100), UNIQUE(name));",
- hasColumns: true,
- hasConstraints: true,
- expectError: false,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Create a mock CreateTableStmt
- createTableStmt := &ast.CreateTableStmt{}
-
- // Add columns if test case has columns
- if tc.hasColumns {
- createTableStmt.ColumnList = []*ast.ColumnDef{
- {ColumnName: "id", ConstraintList: []*ast.ConstraintDef{{Name: "PRIMARY KEY"}}},
- {ColumnName: "name"},
- }
- // Add created_at for multiline case
- if len(tc.statement) > 100 {
- createTableStmt.ColumnList = append(createTableStmt.ColumnList,
- &ast.ColumnDef{ColumnName: "created_at"})
- }
- }
-
- // Add constraints if test case has constraints
- if tc.hasConstraints {
- createTableStmt.ConstraintList = []*ast.ConstraintDef{
- {Name: "unique_name"},
- }
- }
-
- // Create tokenizer
- tokenizer := NewTokenizer(tc.statement)
-
- // Test SetLineForPGCreateTableStmt
- err := tokenizer.SetLineForPGCreateTableStmt(createTableStmt, 1)
-
- if tc.expectError {
- require.Error(t, err)
- } else {
- require.NoError(t, err, "SetLineForPGCreateTableStmt should handle: %s", tc.name)
-
- // For tables with columns, verify that columns have their lines set
- if tc.hasColumns {
- for _, col := range createTableStmt.ColumnList {
- require.NotEqual(t, 0, col.LastLine(), "Column %s should have LastLine set", col.ColumnName)
- }
- }
- }
- })
- }
-}
diff --git a/go.mod b/go.mod
index a24aace761..331632fb79 100644
--- a/go.mod
+++ b/go.mod
@@ -71,7 +71,6 @@ require (
github.com/nyaruka/phonenumbers v1.6.6
github.com/opensearch-project/opensearch-go/v4 v4.5.0
github.com/paulmach/orb v0.12.0
- github.com/pganalyze/pg_query_go/v6 v6.1.0
github.com/pingcap/tidb v1.1.0-beta.0.20241125141335-ec8b81b98edc
github.com/pingcap/tidb/pkg/parser v0.0.0-20241125141335-ec8b81b98edc
github.com/pkg/errors v0.9.1
diff --git a/go.sum b/go.sum
index 99d54113a4..69298ce99d 100644
--- a/go.sum
+++ b/go.sum
@@ -855,8 +855,6 @@ github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0 h1:bJ8NSf2K+
github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0/go.mod h1:BEWMfiZtqshdmulKJcIsWb45MUaEvDO4CROcgi8dfFg=
github.com/bytebase/parser v0.0.0-20251103101721-8b106e9a4f5a h1:a/vntE2CQ559g2L0HceY5Xn3nXztzfzzJJiHkmeFOik=
github.com/bytebase/parser v0.0.0-20251103101721-8b106e9a4f5a/go.mod h1:jeak/EfutSOAuWKvrFIT2IZunhWprM7oTFBRgZ9RCxo=
-github.com/bytebase/pg_query_go2/v6 v6.0.0-20250403034815-22c5b71007ed h1:5DEnBIrnxAxCTbh/tbjmg/9uw9/auyvKu8s0M+ePTOs=
-github.com/bytebase/pg_query_go2/v6 v6.0.0-20250403034815-22c5b71007ed/go.mod h1:nvTHIuoud6e1SfrUaFwHqT0i4b5Nr+1rPWVds3B5+50=
github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767 h1:YuR5G3LcxpO5ScSTA+Kdirxg9RW4TRc/v1t7N2Hfmbw=
github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/bytebase/pkcs8 v0.0.0-20240612095628-fcd0a7484c94 h1:6PNsuNmSqCuR8Z616uQLzDIvujWCFsKzeVc3ECmVubk=
@@ -2644,7 +2642,6 @@ google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.29.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
-google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=