github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/doltcore/sqle/show_create_table.go (about)

     1  // Copyright 2020 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package sqle
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  
    21  	sqle "github.com/dolthub/go-mysql-server"
    22  	"github.com/dolthub/go-mysql-server/sql"
    23  
    24  	"github.com/dolthub/dolt/go/libraries/utils/tracing"
    25  )
    26  
    27  // These functions cannot be in the sqlfmt package as the reliance on the sqle package creates a circular reference.
    28  
    29  func PrepareCreateTableStmt(ctx context.Context, sqlDb sql.Database) (*sql.Context, *sqle.Engine, *DoltSession) {
    30  	dsess := DefaultDoltSession()
    31  	sqlCtx := sql.NewContext(ctx,
    32  		sql.WithSession(dsess),
    33  		sql.WithIndexRegistry(sql.NewIndexRegistry()),
    34  		sql.WithViewRegistry(sql.NewViewRegistry()),
    35  		sql.WithTracer(tracing.Tracer(ctx)))
    36  	engine := sqle.NewDefault()
    37  	engine.AddDatabase(sqlDb)
    38  	dsess.SetCurrentDatabase(sqlDb.Name())
    39  	return sqlCtx, engine, dsess
    40  }
    41  
    42  func GetCreateTableStmt(ctx *sql.Context, engine *sqle.Engine, tableName string) (string, error) {
    43  	_, rowIter, err := engine.Query(ctx, fmt.Sprintf("SHOW CREATE TABLE `%s`;", tableName))
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	rows, err := sql.RowIterToRows(ctx, rowIter)
    48  	if err != nil {
    49  		return "", err
    50  	}
    51  	if len(rows) != 1 || len(rows[0]) != 2 {
    52  		return "", fmt.Errorf("unexpected result from SHOW CREATE TABLE")
    53  	}
    54  	stmt, ok := rows[0][1].(string)
    55  	if !ok {
    56  		return "", fmt.Errorf("expected string statement from SHOW CREATE TABLE")
    57  	}
    58  	return stmt + ";", nil
    59  }