github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/cli/examples.go (about) 1 // Copyright 2016 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package cli 12 13 import ( 14 "fmt" 15 "os" 16 "strings" 17 18 "github.com/cockroachdb/cockroach/pkg/workload" 19 // Register the relevant examples 20 _ "github.com/cockroachdb/cockroach/pkg/workload/examples" 21 "github.com/cockroachdb/cockroach/pkg/workload/workloadsql" 22 "github.com/spf13/cobra" 23 ) 24 25 var genExamplesCmd = &cobra.Command{ 26 Use: "example-data", 27 Short: "generate example SQL code suitable for use with CockroachDB", 28 Long: `This command generates example SQL code that shows various CockroachDB features and 29 is suitable to populate an example database for demonstration and education purposes. 30 `, 31 } 32 33 func init() { 34 for _, meta := range workload.Registered() { 35 gen := meta.New() 36 genExampleCmd := &cobra.Command{ 37 Use: meta.Name, 38 Short: meta.Description, 39 Args: cobra.NoArgs, 40 RunE: func(cmd *cobra.Command, args []string) error { 41 runGenExamplesCmd(gen) 42 return nil 43 }, 44 } 45 if f, ok := gen.(workload.Flagser); ok { 46 genExampleCmd.Flags().AddFlagSet(f.Flags().FlagSet) 47 } 48 genExamplesCmd.AddCommand(genExampleCmd) 49 } 50 } 51 52 func runGenExamplesCmd(gen workload.Generator) { 53 w := os.Stdout 54 55 meta := gen.Meta() 56 fmt.Fprintf(w, "CREATE DATABASE IF NOT EXISTS %s;\n", meta.Name) 57 fmt.Fprintf(w, "SET DATABASE=%s;\n", meta.Name) 58 for _, table := range gen.Tables() { 59 fmt.Fprintf(w, "DROP TABLE IF EXISTS \"%s\";\n", table.Name) 60 fmt.Fprintf(w, "CREATE TABLE \"%s\" %s;\n", table.Name, table.Schema) 61 for rowIdx := 0; rowIdx < table.InitialRows.NumBatches; rowIdx++ { 62 for _, row := range table.InitialRows.BatchRows(rowIdx) { 63 rowTuple := strings.Join(workloadsql.StringTuple(row), `,`) 64 fmt.Fprintf(w, "INSERT INTO \"%s\" VALUES (%s);\n", table.Name, rowTuple) 65 } 66 } 67 } 68 69 fmt.Fprint(w, footerComment) 70 } 71 72 const footerComment = `-- 73 -- 74 -- If you can see this message, you probably want to redirect the output of 75 -- 'cockroach gen example-data' to a file, or pipe it as input to 'cockroach sql'. 76 `