diff --git a/cmd/client-fs.go b/cmd/client-fs.go index e1fb5097..0bf48108 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -97,7 +97,7 @@ func (f *fsClient) GetURL() clientURL { } // Select replies a stream of query results. -func (f *fsClient) Select(expression string, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { +func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) { return nil, probe.NewError(APINotImplemented{}) } diff --git a/cmd/client-s3.go b/cmd/client-s3.go index bc2eed95..2efff331 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -59,6 +59,24 @@ const ( googleHostName = "storage.googleapis.com" serverEncryptionKeyPrefix = "x-amz-server-side-encryption" + + defaultRecordDelimiter = "\n" + defaultFieldDelimiter = "," + defaultCSVQuoteCharacter = "\"" + defaultCSVQuoteEscapeCharacter = "\"" + defaultCommentChar = "#" +) + +const ( + recordDelimiterType = "recorddelimiter" + fieldDelimiterType = "fielddelimiter" + quoteCharacterType = "quotechar" + quoteEscapeCharacterType = "quoteescchar" + quoteFieldType = "quotefield" + fileHeaderType = "fileheader" + commentCharType = "commentchar" + quotedRecordDelimiterType = "quotedrecorddelimiter" + typeJSONType = "type" ) // cseHeaders is list of client side encryption headers @@ -410,7 +428,142 @@ var supportedContentTypes = []string{ "bzip2", } -func (c *s3Client) Select(expression string, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { +// set the SelectObjectOutputSerialization struct using options passed in by client. If unspecified, +// default S3 API specified defaults +func selectObjectOutputOpts(selOpts SelectObjectOpts, i minio.SelectObjectInputSerialization) minio.SelectObjectOutputSerialization { + var isOK bool + var recDelim, fldDelim, quoteChar, quoteEscChar, qf string + + o := minio.SelectObjectOutputSerialization{} + if _, ok := selOpts.OutputSerOpts["json"]; ok { + recDelim, isOK = selOpts.OutputSerOpts["json"][recordDelimiterType] + if !isOK { + recDelim = "\n" + } + o.JSON = &minio.JSONOutputOptions{RecordDelimiter: recDelim} + } + if _, ok := selOpts.OutputSerOpts["csv"]; ok { + o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter} + if recDelim, isOK = selOpts.OutputSerOpts["csv"][recordDelimiterType]; isOK { + o.CSV.RecordDelimiter = recDelim + } + + if fldDelim, isOK = selOpts.OutputSerOpts["csv"][fieldDelimiterType]; isOK { + o.CSV.FieldDelimiter = fldDelim + } + if quoteChar, isOK = selOpts.OutputSerOpts["csv"][quoteCharacterType]; isOK { + o.CSV.QuoteCharacter = quoteChar + } + + if quoteEscChar, isOK = selOpts.OutputSerOpts["csv"][quoteEscapeCharacterType]; isOK { + o.CSV.QuoteEscapeCharacter = quoteEscChar + } + if qf, isOK = selOpts.OutputSerOpts["csv"][quoteFieldType]; isOK { + o.CSV.QuoteFields = minio.CSVQuoteFields(qf) + } + } + // default to CSV output if options left unspecified + if o.CSV == nil && o.JSON == nil { + if i.JSON != nil { + o.JSON = &minio.JSONOutputOptions{RecordDelimiter: "\n"} + } else { + o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter} + } + } + return o +} + +// set the SelectObjectInputSerialization struct using options passed in by client. If unspecified, +// default S3 API specified defaults +func selectObjectInputOpts(selOpts SelectObjectOpts, object string) minio.SelectObjectInputSerialization { + var isOK bool + var recDelim, fldDelim, quoteChar, quoteEscChar, fileHeader, commentChar, typ string + + i := minio.SelectObjectInputSerialization{} + if _, ok := selOpts.InputSerOpts["parquet"]; ok { + i.Parquet = &minio.ParquetInputOptions{} + } + if _, ok := selOpts.InputSerOpts["json"]; ok { + i.JSON = &minio.JSONInputOptions{} + if typ, _ = selOpts.InputSerOpts["json"][typeJSONType]; typ != "" { + i.JSON.Type = minio.JSONType(typ) + } + } + if _, ok := selOpts.InputSerOpts["csv"]; ok { + i.CSV = &minio.CSVInputOptions{RecordDelimiter: defaultRecordDelimiter} + if recDelim, isOK = selOpts.InputSerOpts["csv"][recordDelimiterType]; isOK { + i.CSV.RecordDelimiter = recDelim + } + if fldDelim, isOK = selOpts.InputSerOpts["csv"][fieldDelimiterType]; isOK { + i.CSV.FieldDelimiter = fldDelim + } + if quoteChar, isOK = selOpts.InputSerOpts["csv"][quoteCharacterType]; isOK { + i.CSV.QuoteCharacter = quoteChar + } + + if quoteEscChar, isOK = selOpts.InputSerOpts["csv"][quoteEscapeCharacterType]; isOK { + i.CSV.QuoteEscapeCharacter = quoteEscChar + } + fileHeader, _ = selOpts.InputSerOpts["csv"][fileHeaderType] + i.CSV.FileHeaderInfo = minio.CSVFileHeaderInfo(fileHeader) + if commentChar, isOK = selOpts.InputSerOpts["csv"][commentCharType]; isOK { + i.CSV.Comments = commentChar + } + // needs to be added to minio-go + // if qrd, isOK = selOpts.InputSerOpts["csv"][quotedRecordDelimiterType];isOK { + // i.CSV.QuotedRecordDelimiter = qrd + // } + } + ext := filepath.Ext(object) + if i.CSV == nil && i.JSON == nil && i.Parquet == nil { + if strings.Contains(ext, "csv") { + i.CSV = &minio.CSVInputOptions{ + RecordDelimiter: defaultRecordDelimiter, + FieldDelimiter: defaultFieldDelimiter, + FileHeaderInfo: minio.CSVFileHeaderInfoUse, + } + } + if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") { + i.Parquet = &minio.ParquetInputOptions{} + } + if strings.Contains(ext, "json") { + i.JSON = &minio.JSONInputOptions{Type: minio.JSONLinesType} + } + } + i.CompressionType = selectCompressionType(selOpts, object) + return i +} + +// get client specified compression type or default compression type from file extension +func selectCompressionType(selOpts SelectObjectOpts, object string) minio.SelectCompressionType { + ext := filepath.Ext(object) + origContentType := mimedb.TypeByExtension(filepath.Ext(strings.TrimSuffix(strings.TrimSuffix(object, ".gz"), ".bz2"))) + + contentType := mimedb.TypeByExtension(ext) + + if selOpts.CompressionType != "" { + return selOpts.CompressionType + } + if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") { + return minio.SelectCompressionNONE + } + if origContentType != "" { + if strings.Contains(origContentType, "csv") || + strings.Contains(origContentType, "json") { + return minio.SelectCompressionNONE + } + } + if contentType != "" { + if strings.Contains(contentType, "gzip") { + return minio.SelectCompressionGZIP + } else if strings.Contains(contentType, "bzip") { + return minio.SelectCompressionBZIP + } + } + return minio.SelectCompressionNONE +} + +func (c *s3Client) Select(expression string, sse encrypt.ServerSide, selOpts SelectObjectOpts) (io.ReadCloser, *probe.Error) { opts := minio.SelectObjectOptions{ Expression: expression, ExpressionType: minio.QueryExpressionTypeSQL, @@ -419,54 +572,9 @@ func (c *s3Client) Select(expression string, sse encrypt.ServerSide) (io.ReadClo } bucket, object := c.url2BucketAndObject() - ext := filepath.Ext(object) - if strings.Contains(ext, "parquet") { - opts.InputSerialization = minio.SelectObjectInputSerialization{ - CompressionType: minio.SelectCompressionNONE, - Parquet: &minio.ParquetInputOptions{}, - } - opts.OutputSerialization = minio.SelectObjectOutputSerialization{ - JSON: &minio.JSONOutputOptions{ - RecordDelimiter: "\n", - }, - } - } else { - origContentType := mimedb.TypeByExtension(filepath.Ext(strings.TrimSuffix(strings.TrimSuffix(object, ".gz"), ".bz2"))) - contentType := mimedb.TypeByExtension(ext) - if strings.Contains(origContentType, "csv") { - opts.InputSerialization = minio.SelectObjectInputSerialization{ - CompressionType: minio.SelectCompressionNONE, - CSV: &minio.CSVInputOptions{ - FileHeaderInfo: minio.CSVFileHeaderInfoUse, - RecordDelimiter: "\n", - FieldDelimiter: ",", - }, - } - opts.OutputSerialization = minio.SelectObjectOutputSerialization{ - CSV: &minio.CSVOutputOptions{ - RecordDelimiter: "\n", - FieldDelimiter: ",", - }, - } - } else if strings.Contains(origContentType, "json") { - opts.InputSerialization = minio.SelectObjectInputSerialization{ - CompressionType: minio.SelectCompressionNONE, - JSON: &minio.JSONInputOptions{ - Type: minio.JSONLinesType, - }, - } - opts.OutputSerialization = minio.SelectObjectOutputSerialization{ - JSON: &minio.JSONOutputOptions{ - RecordDelimiter: "\n", - }, - } - } - if strings.Contains(contentType, "gzip") { - opts.InputSerialization.CompressionType = minio.SelectCompressionGZIP - } else if strings.Contains(contentType, "bzip") { - opts.InputSerialization.CompressionType = minio.SelectCompressionBZIP - } - } + + opts.InputSerialization = selectObjectInputOpts(selOpts, object) + opts.OutputSerialization = selectObjectOutputOpts(selOpts, opts.InputSerialization) reader, e := c.api.SelectObjectContent(context.Background(), bucket, object, opts) if e != nil { return nil, probe.NewError(e) diff --git a/cmd/client-s3_test.go b/cmd/client-s3_test.go index f439cedb..ab5afcb8 100644 --- a/cmd/client-s3_test.go +++ b/cmd/client-s3_test.go @@ -25,6 +25,7 @@ import ( "net/http/httptest" "strconv" + minio "github.com/minio/minio-go" . "gopkg.in/check.v1" ) @@ -235,3 +236,28 @@ func (s *TestSuite) TestObjectOperations(c *C) { c.Assert(buffer.Bytes(), DeepEquals, object.data) } } + +var testSelectCompressionTypeCases = []struct { + opts SelectObjectOpts + object string + compressionType minio.SelectCompressionType +}{ + {SelectObjectOpts{CompressionType: minio.SelectCompressionNONE}, "a.gzip", minio.SelectCompressionNONE}, + {SelectObjectOpts{CompressionType: minio.SelectCompressionBZIP}, "a.gz", minio.SelectCompressionBZIP}, + {SelectObjectOpts{}, "t.parquet", minio.SelectCompressionNONE}, + {SelectObjectOpts{}, "x.csv.gz", minio.SelectCompressionNONE}, + {SelectObjectOpts{}, "x.json.bz2", minio.SelectCompressionNONE}, + {SelectObjectOpts{}, "b.gz", minio.SelectCompressionGZIP}, + {SelectObjectOpts{}, "k.bz2", minio.SelectCompressionBZIP}, + {SelectObjectOpts{}, "a.csv", minio.SelectCompressionNONE}, + {SelectObjectOpts{}, "a.json", minio.SelectCompressionNONE}, +} + +// TestSelectCompressionType - tests compression type returned +// by method +func (s *TestSuite) TestSelectCompressionType(c *C) { + for _, test := range testSelectCompressionTypeCases { + cType := selectCompressionType(test.opts, test.object) + c.Assert(cType, DeepEquals, test.compressionType) + } +} diff --git a/cmd/client.go b/cmd/client.go index a7aff615..83a88546 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -60,7 +60,7 @@ type Client interface { Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error // Runs select expression on object storage on specific files. - Select(expression string, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) + Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) // I/O operations with metadata. Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error) @@ -107,3 +107,10 @@ type Config struct { Insecure bool Lookup minio.BucketLookupType } + +// SelectObjectOpts - opts entered for select API +type SelectObjectOpts struct { + InputSerOpts map[string]map[string]string + OutputSerOpts map[string]map[string]string + CompressionType minio.SelectCompressionType +} diff --git a/cmd/sql-main.go b/cmd/sql-main.go index a4dcdcd8..abe59fa3 100644 --- a/cmd/sql-main.go +++ b/cmd/sql-main.go @@ -17,9 +17,16 @@ package cmd import ( + "bufio" + "compress/bzip2" + "compress/gzip" + "errors" + "fmt" "io" + "io/ioutil" "os" "path/filepath" + "regexp" "strings" "github.com/minio/cli" @@ -37,6 +44,30 @@ var ( Name: "recursive, r", Usage: "sql query recursively", }, + cli.StringFlag{ + Name: "csv-input", + Usage: "csv input serialization option", + }, + cli.StringFlag{ + Name: "json-input", + Usage: "json input serialization option", + }, + cli.StringFlag{ + Name: "compression", + Usage: "input compression type", + }, + cli.StringFlag{ + Name: "csv-output", + Usage: "csv output serialization option", + }, + cli.StringFlag{ + Name: "csv-output-header", + Usage: "optional csv output header ", + }, + cli.StringFlag{ + Name: "json-output", + Usage: "json output serialization option", + }, } ) @@ -46,7 +77,7 @@ var sqlCmd = cli.Command{ Usage: "run sql queries on objects", Action: mainSQL, Before: setGlobalsFromContext, - Flags: append(append(sqlFlags, ioFlags...), globalFlags...), + Flags: getSQLFlags(), CustomHelpTemplate: `NAME: {{.HelpName}} - {{.Usage}} @@ -59,6 +90,9 @@ FLAGS: ENVIRONMENT VARIABLES: MC_ENCRYPT_KEY: list of comma delimited prefix=secret values +SERIALIZATION OPTIONS: + For query serialization options, refer to https://docs.minio.io/docs/minio-client-complete-guide#sql + EXAMPLES: 1. Run a query on a set of objects recursively on AWS S3. $ {{.HelpName}} --recursive --query "select * from S3Object" s3/personalbucket/my-large-csvs/ @@ -68,11 +102,294 @@ EXAMPLES: 3. Run a query on an encrypted object with customer provided keys. $ {{.HelpName}} --encrypt-key "myminio/iot-devices=32byteslongsecretkeymustbegiven1" \ - --query "select count(s.power) from S3Object" myminio/iot-devices/power-ratio-encrypted.csv + --query "select count(s.power) from S3Object s" myminio/iot-devices/power-ratio-encrypted.csv + + 4. Run a query on an object on Minio in gzip format using ; as field delimiter, + newline as record delimiter and file header to be used + $ {{.HelpName}} --compression GZIP --csv-input "rd=\n,fh=USE,fd=;" \ + --query "select count(s.power) from S3Object" myminio/iot-devices/power-ratio.csv.gz + + 5. Run a query on an object on Minio in gzip format using ; as field delimiter, + newline as record delimiter and file header to be used + $ {{.HelpName}} --compression GZIP --csv-input "rd=\n,fh=USE,fd=;" \ + --json-output "rd=\n\n" --query "select * from S3Object" myminio/iot-devices/data.csv + + 6. Run same query as in 5., but specify csv output headers. If --csv-output-headers is + specified as "", first row of csv is interpreted as header + $ {{.HelpName}} --compression GZIP --csv-input "rd=\n,fh=USE,fd=;" \ + --csv-output "rd=\n" --csv-output-header "device_id,uptime,lat,lon" \ + --query "select * from S3Object" myminio/iot-devices/data.csv + `, } -func sqlSelect(targetURL, expression string, encKeyDB map[string][]prefixSSEPair) *probe.Error { +// filter json from allowed flags for sql command +func getSQLFlags() []cli.Flag { + flags := append(sqlFlags, ioFlags...) + for _, f := range globalFlags { + if f.GetName() != "json" { + flags = append(flags, f) + } + } + return flags +} + +// valid CSV and JSON keys for input/output serialization +var ( + validCSVCommonKeys = []string{"FieldDelimiter", "QuoteChar", "QuoteEscChar"} + validCSVInputKeys = []string{"Comments", "FileHeader", "QuotedRecordDelimiter", "RecordDelimiter"} + validCSVOutputKeys = []string{"QuoteFields"} + + validJSONInputKeys = []string{"Type"} + validJSONCSVCommonOutputKeys = []string{"RecordDelimiter"} + + // mapping of abbreviation to long form name of CSV and JSON input/output serialization keys + validCSVInputAbbrKeys = map[string]string{"cc": "Comments", "fh": "FileHeader", "qrd": "QuotedRecordDelimiter", "rd": "RecordDelimiter", "fd": "FieldDelimiter", "qc": "QuoteChar", "qec": "QuoteEscChar"} + validCSVOutputAbbrKeys = map[string]string{"qf": "QuoteFields", "rd": "RecordDelimiter", "fd": "FieldDelimiter", "qc": "QuoteChar", "qec": "QuoteEscChar"} + validJSONOutputAbbrKeys = map[string]string{"rd": "RecordDelimiter"} +) + +// parseKVArgs parses string of the form k=v delimited by "," +// into a map of k-v pairs +func parseKVArgs(is string) (map[string]string, *probe.Error) { + kvmap := make(map[string]string) + var key, value string + var s, e int // tracking start and end of value + var index int // current index in string + if is != "" { + for index < len(is) { + i := strings.Index(is[index:], "=") + if i == -1 { + return nil, probe.NewError(errors.New("Arguments should be of the form key=value,... ")) + } + key = is[index : index+i] + s = i + index + 1 + e = strings.Index(is[s:], ",") + delimFound := false + for !delimFound { + if e == -1 || e+s >= len(is) { + delimFound = true + break + } + if string(is[s+e]) != "," { + delimFound = true + if string(is[s+e-1]) == "," { + e-- + } + } else { + e++ + } + } + var vEnd = len(is) + if e != -1 { + vEnd = s + e + } + + value = is[s:vEnd] + index = vEnd + 1 + if _, ok := kvmap[strings.ToLower(key)]; ok { + return nil, probe.NewError(fmt.Errorf("More than one key=value found for %s", strings.TrimSpace(key))) + } + kvmap[strings.ToLower(key)] = strings.NewReplacer(`\n`, "\n", `\t`, "\t", `\r`, "\r").Replace(value) + } + } + return kvmap, nil +} + +// returns a string with list of serialization options and abbreviation(s) if any +func fmtString(validAbbr map[string]string, validKeys []string) string { + var sb strings.Builder + i := 0 + for k, v := range validAbbr { + sb.WriteString(fmt.Sprintf("%s(%s) ", v, k)) + i++ + if i != len(validAbbr) { + sb.WriteString(",") + } + } + if len(sb.String()) == 0 { + for _, k := range validKeys { + sb.WriteString(fmt.Sprintf("%s ", k)) + } + } + return sb.String() +} + +// parses the input string and constructs a k-v map, replacing any abbreviated keys with actual keys +func parseSerializationOpts(inp string, validKeys []string, validAbbrKeys map[string]string) (map[string]string, *probe.Error) { + if validAbbrKeys == nil { + validAbbrKeys = make(map[string]string) + } + validKeyFn := func(key string, validKeys []string) bool { + for _, name := range validKeys { + if strings.ToLower(name) == strings.ToLower(key) { + return true + } + } + return false + } + kv, err := parseKVArgs(inp) + if err != nil { + return nil, err + } + ikv := make(map[string]string) + for k, v := range kv { + fldName, ok := validAbbrKeys[strings.ToLower(k)] + if ok { + ikv[strings.ToLower(fldName)] = v + } else { + ikv[strings.ToLower(k)] = v + } + } + for k := range ikv { + if !validKeyFn(k, validKeys) { + return nil, probe.NewError(errors.New("Options should be key-value pairs in the form key=value,... where valid key(s) are " + fmtString(validAbbrKeys, validKeys))) + } + } + return ikv, nil +} + +// gets the input serialization opts from cli context and constructs a map of csv, json or parquet options +func getInputSerializationOpts(ctx *cli.Context) map[string]map[string]string { + icsv := ctx.String("csv-input") + ijson := ctx.String("json-input") + m := make(map[string]map[string]string) + + csvType := ctx.IsSet("csv-input") + jsonType := ctx.IsSet("json-input") + if csvType && jsonType { + fatalIf(errInvalidArgument(), "Only one of --csv-input or --json-input can be specified as input serialization option") + } + + if icsv != "" { + kv, err := parseSerializationOpts(icsv, append(validCSVCommonKeys, validCSVInputKeys...), validCSVInputAbbrKeys) + fatalIf(err, "Invalid serialization option(s) specified for --csv-input flag") + + m["csv"] = kv + } + if ijson != "" { + kv, err := parseSerializationOpts(ijson, validJSONInputKeys, nil) + + fatalIf(err, "Invalid serialization option(s) specified for --json-input flag") + m["json"] = kv + } + + return m +} + +// gets the output serialization opts from cli context and constructs a map of csv or json options +func getOutputSerializationOpts(ctx *cli.Context, csvHdrs []string) (opts map[string]map[string]string) { + m := make(map[string]map[string]string) + + ocsv := ctx.String("csv-output") + ojson := ctx.String("json-output") + csvType := ctx.IsSet("csv-output") + jsonType := ctx.IsSet("json-output") + + if csvType && jsonType { + fatalIf(errInvalidArgument(), "Only one of --csv-output, or --json-output can be specified as output serialization option") + } + + if jsonType && len(csvHdrs) > 0 { + fatalIf(errInvalidArgument(), "--csv-output-header incompatible with --json-output option") + } + + if csvType { + validKeys := append(validCSVCommonKeys, validJSONCSVCommonOutputKeys...) + kv, err := parseSerializationOpts(ocsv, append(validKeys, validCSVOutputKeys...), validCSVOutputAbbrKeys) + fatalIf(err, "Invalid value(s) specified for --csv-output flag") + m["csv"] = kv + } + + if jsonType { + kv, err := parseSerializationOpts(ojson, validJSONCSVCommonOutputKeys, validJSONOutputAbbrKeys) + fatalIf(err, "Invalid value(s) specified for --json-output flag") + m["json"] = kv + } + return m +} + +// getCSVHeader fetches the first line of csv query object +func getCSVHeader(sourceURL string, encKeyDB map[string][]prefixSSEPair) ([]string, *probe.Error) { + var r io.ReadCloser + switch sourceURL { + case "-": + r = os.Stdin + default: + var err *probe.Error + var metadata map[string]string + if r, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil { + return nil, err.Trace(sourceURL) + } + ctype := metadata["Content-Type"] + if strings.Contains(ctype, "gzip") { + var e error + r, e = gzip.NewReader(r) + if e != nil { + return nil, probe.NewError(e) + } + defer r.Close() + } else if strings.Contains(ctype, "bzip") { + defer r.Close() + r = ioutil.NopCloser(bzip2.NewReader(r)) + } else { + defer r.Close() + } + } + br := bufio.NewReader(r) + line, _, err := br.ReadLine() + if err != nil { + return nil, probe.NewError(err) + } + return strings.Split(string(line), ","), nil +} + +// returns true if query is selectign all columns of the csv object +func isSelectAll(query string) bool { + match, _ := regexp.MatchString("^\\s*?select\\s+?\\*\\s+?.*?$", query) + return match +} + +// if csv-output-header is set to a comma delimited string use it, othjerwise attempt to get the header from +// query object +func getCSVOutputHeaders(ctx *cli.Context, url string, encKeyDB map[string][]prefixSSEPair, query string) (hdrs []string) { + if !ctx.IsSet("csv-output-header") { + return + } + + hdrStr := ctx.String("csv-output-header") + if hdrStr == "" && isSelectAll(query) { + // attempt to get the first line of csv as header + if hdrs, err := getCSVHeader(url, encKeyDB); err == nil { + return hdrs + } + } + hdrs = strings.Split(hdrStr, ",") + return +} + +// get the Select options for sql select API +func getSQLOpts(ctx *cli.Context, csvHdrs []string) (s SelectObjectOpts) { + is := getInputSerializationOpts(ctx) + os := getOutputSerializationOpts(ctx, csvHdrs) + + return SelectObjectOpts{ + InputSerOpts: is, + OutputSerOpts: os, + } +} + +func isCSVOrJSON(inOpts map[string]map[string]string) bool { + if _, ok := inOpts["csv"]; ok { + return true + } + if _, ok := inOpts["json"]; ok { + return true + } + return false +} + +func sqlSelect(targetURL, expression string, encKeyDB map[string][]prefixSSEPair, selOpts SelectObjectOpts, csvHdrs []string, writeHdr bool) *probe.Error { alias, _, _, err := expandAlias(targetURL) if err != nil { return err.Trace(targetURL) @@ -84,16 +401,36 @@ func sqlSelect(targetURL, expression string, encKeyDB map[string][]prefixSSEPair } sseKey := getSSE(targetURL, encKeyDB[alias]) - outputer, err := targetClnt.Select(expression, sseKey) + outputer, err := targetClnt.Select(expression, sseKey, selOpts) if err != nil { return err.Trace(targetURL, expression) } defer outputer.Close() + // write csv header to stdout + if len(csvHdrs) > 0 && writeHdr { + fmt.Println(strings.Join(csvHdrs, ",")) + } _, e := io.Copy(os.Stdout, outputer) return probe.NewError(e) } +func validateOpts(selOpts SelectObjectOpts, url string) { + _, targetURL, _ := mustExpandAlias(url) + if strings.HasSuffix(targetURL, ".parquet") && isCSVOrJSON(selOpts.InputSerOpts) { + fatalIf(errInvalidArgument(), "Input serialization flags --csv-input and --json-input cannot be used for object in .parquet format") + } +} + +// validate args and optionally fetch the csv header of query object +func getAndValidateArgs(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, url string) (query string, csvHdrs []string, selOpts SelectObjectOpts) { + query = ctx.String("query") + csvHdrs = getCSVOutputHeaders(ctx, url, encKeyDB, query) + selOpts = getSQLOpts(ctx, csvHdrs) + validateOpts(selOpts, url) + return +} + // check sql input arguments. func checkSQLSyntax(ctx *cli.Context) { if !ctx.Args().Present() { @@ -103,19 +440,27 @@ func checkSQLSyntax(ctx *cli.Context) { // mainSQL is the main entry point for sql command. func mainSQL(ctx *cli.Context) error { + var ( + csvHdrs []string + selOpts SelectObjectOpts + query string + ) // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // validate sql input arguments. checkSQLSyntax(ctx) - // extract URLs. URLs := ctx.Args() - query := ctx.String("query") + writeHdr := true for _, url := range URLs { if !isAliasURLDir(url, encKeyDB) { - errorIf(sqlSelect(url, query, encKeyDB).Trace(url), "Unable to run sql") + if writeHdr { + query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, url) + } + errorIf(sqlSelect(url, query, encKeyDB, selOpts, csvHdrs, writeHdr).Trace(url), "Unable to run sql") + writeHdr = false continue } targetAlias, targetURL, _ := mustExpandAlias(url) @@ -130,12 +475,16 @@ func mainSQL(ctx *cli.Context) error { errorIf(content.Err.Trace(url), "Unable to list on target `"+url+"`.") continue } + if writeHdr { + query, csvHdrs, selOpts = getAndValidateArgs(ctx, encKeyDB, targetAlias+content.URL.Path) + } contentType := mimedb.TypeByExtension(filepath.Ext(content.URL.Path)) for _, cTypeSuffix := range supportedContentTypes { if strings.Contains(contentType, cTypeSuffix) { errorIf(sqlSelect(targetAlias+content.URL.Path, query, - encKeyDB).Trace(content.URL.String()), "Unable to run sql") + encKeyDB, selOpts, csvHdrs, writeHdr).Trace(content.URL.String()), "Unable to run sql") } + writeHdr = false } } } diff --git a/cmd/sql-main_test.go b/cmd/sql-main_test.go new file mode 100644 index 00000000..910da4a4 --- /dev/null +++ b/cmd/sql-main_test.go @@ -0,0 +1,142 @@ +/* + * Minio Client (C) 2019 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "fmt" + "strings" + "testing" +) + +var testParseKVArgsCases = []struct { + inp string + kvmap map[string]string + errMsg string +}{ + {"fh=use,rd=|,fd=;,qec=\"", map[string]string{"fh": "use", "rd": "|", "fd": ";", "qec": "\""}, ""}, + {"", map[string]string{}, ""}, + {"not the right format", map[string]string{}, "Arguments should be of the form key=value,... "}, + {"k==v", map[string]string{"k": "=v"}, ""}, + {"k=v1,k=v2", map[string]string{}, "More than one key=value found for k"}, + {"k=v1;k=v2", map[string]string{"k": "v1;k=v2"}, ""}, +} + +func TestParseKVArgs(t *testing.T) { + for _, test := range testParseKVArgsCases { + kvmap, err := parseKVArgs(test.inp) + gerr := err.ToGoError() + if gerr != nil && gerr.Error() != test.errMsg { + t.Fatalf("Unexpected result for \"%s\", expected: |%s| got: |%s|\n", test.inp, test.errMsg, gerr) + } + if gerr == nil && test.errMsg != "" { + t.Fatalf("Unexpected result for \"%s\", expected: |%s| got: |%s|\n", test.inp, test.errMsg, gerr) + } + for k, v := range test.kvmap { + actual, ok := kvmap[k] + if !ok { + t.Fatalf("Unexpected result for \"%s,\" expected %s , found %s for key %s\n", test.inp, v, actual, k) + } + } + } +} + +var testParseSerializationCases = []struct { + inp string + validKeys []string + validAbbrKeys map[string]string + parsedOpts map[string]string + errMsg string +}{ + {"rd=\n,fd=;,qc=\"", + append(validCSVCommonKeys, validCSVInputKeys...), + validCSVInputAbbrKeys, + map[string]string{"recorddelimiter": "\n", "fielddelimiter": ";", "quotechar": "\""}, + "", + }, + {"rd=\n,fd=;,qc=\"", + validCSVInputKeys, + validCSVInputAbbrKeys, + map[string]string{}, + "Options should be key-value pairs in the form key=value,... where valid key(s) are ", + }, + {"nokey=\n,fd=;,qc=\"", + validCSVInputKeys, + validCSVInputAbbrKeys, + map[string]string{}, + "Options should be key-value pairs in the form key=value,... where valid key(s) are ", + }, + {"rd=\n\n,fd=|,qc=\",qc='", + validCSVInputKeys, + validCSVInputAbbrKeys, + map[string]string{}, + "More than one key=value found for ", + }, + {"recordDelimiter=\n\n,FieldDelimiter=|,QuoteChAR=\"", + append(validCSVCommonKeys, validCSVInputKeys...), + validCSVInputAbbrKeys, + map[string]string{"recorddelimiter": "\n\n", "fielddelimiter": "|", "quotechar": "\""}, + "", + }, + {"recordDelimiter=\n\n,FieldDelimiter=|,QuoteChAR=\",fh=use,qrd=;", + append(validCSVCommonKeys, validCSVInputKeys...), + validCSVInputAbbrKeys, + map[string]string{"recorddelimiter": "\n\n", "fielddelimiter": "|", "quotechar": "\"", "quotedrecorddelimiter": ";", "fileheader": "use"}, + "", + }, + {"recordDelimiter=\n\n,FieldDelimiter=|,QuoteChar=\",qf=;,qec='", + append(validCSVCommonKeys, validCSVOutputKeys...), + validCSVOutputAbbrKeys, + map[string]string{}, + "Options should be key-value pairs in the form key=value,... where valid key(s) are ", + }, + {"FieldDelimiter=|,QuoteChar=\",qf=;,qec='", + append(validCSVCommonKeys, validCSVOutputKeys...), + validCSVOutputAbbrKeys, + map[string]string{"fielddelimiter": "|", "quotechar": "\"", "quotefields": ";", "quoteescchar": "'"}, + "", + }, + {"type=lines", + validJSONInputKeys, + nil, + map[string]string{"type": "lines"}, + "", + }, +} + +func TestParseSerializationOpts(t *testing.T) { + + for i, test := range testParseSerializationCases { + optsMap, err := parseSerializationOpts(test.inp, test.validKeys, test.validAbbrKeys) + gerr := err.ToGoError() + fmt.Println(i+1, optsMap, gerr) + if gerr != nil && gerr.Error() != test.errMsg { + // match partial error message + if !strings.Contains(gerr.Error(), test.errMsg) { + t.Fatalf("Test %d: Unexpected result for \"%s\", expected: |%s| got: |%s|\n", i+1, test.inp, test.errMsg, gerr) + } + } + if gerr == nil && test.errMsg != "" { + t.Fatalf("Test %d: Unexpected result for \"%s\", expected: |%s| got: |%s|\n", i+1, test.inp, test.errMsg, gerr) + } + for k, v := range test.parsedOpts { + actual, ok := optsMap[strings.ToLower(k)] + if !ok { + t.Fatalf("Test %d:Unexpected result for \"%s,\" expected %s , found %s for key %s\n", i+1, test.inp, v, actual, k) + } + } + } +} diff --git a/docs/minio-client-complete-guide.md b/docs/minio-client-complete-guide.md index 0543a88e..f85b2dd7 100644 --- a/docs/minio-client-complete-guide.md +++ b/docs/minio-client-complete-guide.md @@ -382,11 +382,57 @@ USAGE: FLAGS: --query value, -e value sql query expression --recursive, -r sql query recursively + --csv-input value csv input serialization option + --json-input value json input serialization option + --compression value input compression type + --csv-output value csv output serialization option + --json-output value json output serialization option --encrypt-key value encrypt/decrypt objects (using server-side encryption with customer provided keys) --help, -h show help ENVIRONMENT VARIABLES: MC_ENCRYPT_KEY: list of comma delimited prefix=secret values + +INPUT SERIALIZATION + --csv-input or --json-input can be used to specify input data format. Format is + specified by a string with pattern "key=value,..." for valid key(s). + + DATA FORMAT: + csv: Use --csv-input flag + Valid keys: + RecordDelimiter (rd) + FieldDelimiter (fd) + QuoteChar (qc) + QuoteEscChar (qec) + FileHeader (fh) + Comments (cc) + QuotedRecordDelimiter (qrd) + + json: Use --json-input flag + Valid keys: + Type + parquet: If object name ends in .parquet, this is automatically interpreted. + +OUTPUT SERIALIZATION + --csv-output or --json-output can be used to specify output data format. Format is + specified by a string with pattern "key=value,..." for valid key(s). + DATA FORMAT: + csv: Use --csv-output flag + Valid keys: + RecordDelimiter (rd) + FieldDelimiter (fd) + QuoteChar (qc) + QuoteEscChar (qec) + QuoteFields (qf) + + json: Use --json-output flag + Valid keys: + RecordDelimiter (rd) + +COMPRESSION TYPE + --compression specifies if the queried object is compressed. + Valid values: NONE | GZIP | BZIP2 + ``` *Example: Select all columns on a set of objects recursively on AWS S3* diff --git a/go.mod b/go.mod index b1c8d936..3600e4c0 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/fatih/color v1.7.0 github.com/fatih/structs v0.0.0-20181010231757-878a968ab225 // indirect github.com/ghodss/yaml v1.0.0 // indirect - github.com/go-ini/ini v1.42.0 // indirect github.com/gogo/protobuf v1.2.0 // indirect github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef // indirect github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c // indirect @@ -30,7 +29,7 @@ require ( github.com/mattn/go-runewidth v0.0.4 // indirect github.com/minio/cli v0.0.0-20170227073228-b8ae5507c0ce github.com/minio/minio v0.0.0-20190206103305-fd4e15c11641 - github.com/minio/minio-go v0.0.0-20190227180923-59af836a7e6d + github.com/minio/minio-go v0.0.0-20190308013636-b32976861da0 github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16 github.com/minio/sio v0.0.0-20180327104954-6a41828a60f0 // indirect github.com/mitchellh/go-homedir v1.1.0 diff --git a/go.sum b/go.sum index 60ada70f..6733e472 100644 --- a/go.sum +++ b/go.sum @@ -28,8 +28,6 @@ github.com/fatih/structs v0.0.0-20181010231757-878a968ab225 h1:sX8PG1xNFAxOSefJm github.com/fatih/structs v0.0.0-20181010231757-878a968ab225/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-ini/ini v1.42.0 h1:TWr1wGj35+UiWHlBA8er89seFXxzwFn11spilrrj+38= -github.com/go-ini/ini v1.42.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/gogo/protobuf v1.2.0 h1:xU6/SpYbvkNYiptHJYEDRseDLvYE7wSqhYYNy0QSUzI= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= @@ -85,12 +83,8 @@ github.com/minio/cli v0.0.0-20170227073228-b8ae5507c0ce h1:cMutC6C4ElU0TVblNfXx6 github.com/minio/cli v0.0.0-20170227073228-b8ae5507c0ce/go.mod h1:hLsWNQy2wIf3FKFnMlH69f4RdEyn8nbRA2shaulTjGY= github.com/minio/minio v0.0.0-20190206103305-fd4e15c11641 h1:iW6Ns9yJPCzd1v+AjznM2xY9JwH2tIaHEdM6rsG8YKE= github.com/minio/minio v0.0.0-20190206103305-fd4e15c11641/go.mod h1:lXcp05uxYaW99ebgI6ZKIGYU7tqZkM5xSsG0xRt4VIU= -github.com/minio/minio-go v0.0.0-20190207005939-34f2b94c43ca h1:G/CcAEahhiwwL1A/BW4WIA1D+PJwJov3Q3I9knm15qg= -github.com/minio/minio-go v0.0.0-20190207005939-34f2b94c43ca/go.mod h1:vuvdOZLJuf5HmJAJrKV64MmozrSsk+or0PB5dzdfspg= -github.com/minio/minio-go v0.0.0-20190227180923-59af836a7e6d h1:gptD0/Hnam7h4Iq9D/33fscRpHfzOOUqUbH2nPw9HcU= -github.com/minio/minio-go v0.0.0-20190227180923-59af836a7e6d/go.mod h1:/haSOWG8hQNx2+JOfLJ9GKp61EAmgPwRVw/Sac0NzaM= -github.com/minio/minio-go v6.0.14+incompatible h1:fnV+GD28LeqdN6vT2XdGKW8Qe/IfjJDswNVuni6km9o= -github.com/minio/minio-go v6.0.14+incompatible/go.mod h1:7guKYtitv8dktvNUGrhzmNlA5wrAABTQXCoesZdFQO8= +github.com/minio/minio-go v0.0.0-20190308013636-b32976861da0 h1:yHdN+v8UkkeKXBF7evFjHE9hvdrW6WhyT/S0W07YM48= +github.com/minio/minio-go v0.0.0-20190308013636-b32976861da0/go.mod h1:/haSOWG8hQNx2+JOfLJ9GKp61EAmgPwRVw/Sac0NzaM= github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16 h1:5W7KhL8HVF3XCFOweFD3BNESdnO8ewyYTFT2R+/b8FQ= github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16/go.mod h1:2FMWW+8GMoPweT6+pI63m9YE3Lmw4J71hV56Chs1E/U= github.com/minio/sio v0.0.0-20180327104954-6a41828a60f0 h1:ys4bbOlPvaUBlA0byjm6TqydsXZu614ZIUTfF+4MRY0= @@ -161,10 +155,6 @@ golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613/go.mod h1:6SG95UA2DQfeDnf golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3 h1:ulvT7fqt0yHWzpJwI57MezWnYDVpCAYBVuYst/L+fAY= -golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190206173232-65e2d4e15006 h1:bfLnR+k0tq5Lqt6dflRLcZiz6UaXCMt3vhYJ1l4FQ80= -golang.org/x/net v0.0.0-20190206173232-65e2d4e15006/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -188,7 +178,6 @@ google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0 google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/grpc v1.18.0 h1:IZl7mfBGfbhYx2p2rKRtYgDFw6SBz+kclmxYrCksPPA= google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= -google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/vendor/github.com/minio/minio-go/api-select.go b/vendor/github.com/minio/minio-go/api-select.go index 643abef8..71c5838b 100644 --- a/vendor/github.com/minio/minio-go/api-select.go +++ b/vendor/github.com/minio/minio-go/api-select.go @@ -90,19 +90,19 @@ type ParquetInputOptions struct{} type CSVInputOptions struct { FileHeaderInfo CSVFileHeaderInfo RecordDelimiter string - FieldDelimiter string - QuoteCharacter string - QuoteEscapeCharacter string - Comments string + FieldDelimiter string `xml:",omitempty"` + QuoteCharacter string `xml:",omitempty"` + QuoteEscapeCharacter string `xml:",omitempty"` + Comments string `xml:",omitempty"` } // CSVOutputOptions csv output specific options type CSVOutputOptions struct { - QuoteFields CSVQuoteFields + QuoteFields CSVQuoteFields `xml:",omitempty"` RecordDelimiter string - FieldDelimiter string - QuoteCharacter string - QuoteEscapeCharacter string + FieldDelimiter string `xml:",omitempty"` + QuoteCharacter string `xml:",omitempty"` + QuoteEscapeCharacter string `xml:",omitempty"` } // JSONInputOptions json input specific options diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index f47fac1f..ca18aea7 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -102,7 +102,7 @@ type Options struct { // Global constants. const ( libraryName = "minio-go" - libraryVersion = "v6.0.19" + libraryVersion = "v6.0.20" ) // User Agent should always following the below style. diff --git a/vendor/modules.txt b/vendor/modules.txt index ae654fbf..e8b2a51a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -72,7 +72,7 @@ github.com/minio/minio/pkg/cpu github.com/minio/minio/pkg/disk github.com/minio/minio/pkg/mem github.com/minio/minio/pkg/safe -# github.com/minio/minio-go v0.0.0-20190227180923-59af836a7e6d +# github.com/minio/minio-go v0.0.0-20190308013636-b32976861da0 github.com/minio/minio-go github.com/minio/minio-go/pkg/credentials github.com/minio/minio-go/pkg/encrypt