github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/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/doltcore/env" 25 "github.com/dolthub/dolt/go/libraries/doltcore/sqle/dsess" 26 ) 27 28 // These functions cannot be in the sqlfmt package as the reliance on the sqle package creates a circular reference. 29 30 func PrepareCreateTableStmt(ctx context.Context, sqlDb dsess.SqlDatabase) (*sql.Context, *sqle.Engine, *dsess.DoltSession) { 31 pro, err := NewDoltDatabaseProviderWithDatabase(env.DefaultInitBranch, nil, sqlDb, nil) 32 if err != nil { 33 return nil, nil, nil 34 } 35 engine := sqle.NewDefault(pro) 36 37 sess := dsess.DefaultSession(pro) 38 sqlCtx := sql.NewContext(ctx, sql.WithSession(sess)) 39 sqlCtx.SetCurrentDatabase(sqlDb.Name()) 40 return sqlCtx, engine, sess 41 } 42 43 func GetCreateTableStmt(ctx *sql.Context, engine *sqle.Engine, tableName string) (string, error) { 44 _, rowIter, err := engine.Query(ctx, fmt.Sprintf("SHOW CREATE TABLE `%s`;", tableName)) 45 if err != nil { 46 return "", err 47 } 48 rows, err := sql.RowIterToRows(ctx, rowIter) 49 if err != nil { 50 return "", err 51 } 52 if len(rows) != 1 || len(rows[0]) != 2 { 53 return "", fmt.Errorf("unexpected result from SHOW CREATE TABLE") 54 } 55 stmt, ok := rows[0][1].(string) 56 if !ok { 57 return "", fmt.Errorf("expected string statement from SHOW CREATE TABLE") 58 } 59 return stmt + ";", nil 60 }