sq/cli/cmd_scratch.go

86 lines
2.3 KiB
Go
Raw Normal View History

2020-08-06 20:58:47 +03:00
package cli
import (
"github.com/spf13/cobra"
"github.com/neilotoole/sq/cli/run"
2020-08-06 20:58:47 +03:00
"github.com/neilotoole/sq/libsq/source"
"github.com/neilotoole/sq/libsq/source/drivertype"
2020-08-06 20:58:47 +03:00
)
// TODO: dump all this "internal" stuff: make the options as follows: @HANDLE, file, memory
func newScratchCmd() *cobra.Command {
2020-08-06 20:58:47 +03:00
cmd := &cobra.Command{
Use: "scratch [@HANDLE|internal|internal:file|internal:mem|@scratch]",
// This command is likely to be ditched in favor of a generalized "config" cmd
// such as "sq config scratchdb=@my1"
Hidden: true,
Args: cobra.ExactArgs(1),
RunE: execScratch,
2020-08-06 20:58:47 +03:00
Example: ` # get scratch data source
$ sq scratch
2020-08-06 20:58:47 +03:00
# set @my1 as scratch data source
$ sq scratch @my1
2020-08-06 20:58:47 +03:00
# use the default embedded db
$ sq scratch internal
2020-08-06 20:58:47 +03:00
# explicitly specify use of embedded file db
$ sq scratch internal:file
2020-08-06 20:58:47 +03:00
# explicitly specify use of embedded memory db
$ sq scratch internal:mem
2020-08-06 20:58:47 +03:00
# restore default scratch db (equivalent to "internal")
$ sq scratch @scratch`,
2020-08-06 20:58:47 +03:00
Short: "Get or set scratch data source",
Long: `Get or set scratch data source. The scratch db is used internally by sq for multiple purposes such as
importing non-SQL data, or cross-database joins. If no argument provided, get the current scratch data
source. Otherwise, set @HANDLE or an internal db as the scratch data source. The reserved handle "@scratch" resets the
`,
}
cmdMarkRequiresConfigLock(cmd)
2020-08-06 20:58:47 +03:00
return cmd
2020-08-06 20:58:47 +03:00
}
func execScratch(cmd *cobra.Command, args []string) error {
ru := run.FromContext(cmd.Context())
cfg := ru.Config
2020-08-06 20:58:47 +03:00
var src *source.Source
var err error
defaultScratch := &source.Source{
Handle: source.ScratchHandle,
Location: "internal:file",
Type: drivertype.SQLite,
2020-08-06 20:58:47 +03:00
}
if len(args) == 0 {
// Print the scratch src
src = cfg.Collection.Scratch()
2020-08-06 20:58:47 +03:00
if src == nil {
src = defaultScratch
}
return ru.Writers.Source.Source(cfg.Collection, src)
2020-08-06 20:58:47 +03:00
}
// Set the scratch src
2020-08-06 20:58:47 +03:00
switch args[0] {
case "internal", "internal:file", "internal:mem":
// TODO: currently only supports file sqlite3 db, fairly trivial to do mem as well
_, _ = cfg.Collection.SetScratch("")
2020-08-06 20:58:47 +03:00
src = defaultScratch
default:
src, err = cfg.Collection.SetScratch(args[0])
2020-08-06 20:58:47 +03:00
if err != nil {
return err
}
}
err = ru.ConfigStore.Save(cmd.Context(), ru.Config)
2020-08-06 20:58:47 +03:00
if err != nil {
return err
}
return ru.Writers.Source.Source(cfg.Collection, src)
2020-08-06 20:58:47 +03:00
}