Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSONEachRow / NDJSON support #38

Merged
merged 6 commits into from
Oct 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions utils/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"encoding/json"
"fmt"
"bytes"
"quackpipe/model"
"regexp"
"strings"
Expand All @@ -30,6 +31,12 @@ func ConversationOfRows(rows *sql.Rows, default_format string, duration time.Dur
return "", err
}
return result, nil
case "JSONEachRow", "NDJSON":
result, err := rowsToNDJSON(rows)
if err != nil {
return "", err
}
return result, nil
case "CSVWithNames":
result, err := rowsToCSV(rows, true)
if err != nil {
Expand Down Expand Up @@ -122,6 +129,55 @@ func rowsToJSON(rows *sql.Rows, elapsedTime time.Duration) (string, error) {
return string(jsonData), nil
}

// rowsToNDJSON converts the rows to NDJSON strings
func rowsToNDJSON(rows *sql.Rows) (string, error) {
defer rows.Close()

columns, err := rows.Columns()
if err != nil {
return "", err
}

var buffer bytes.Buffer
values := make([]interface{}, len(columns))
scanArgs := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}

for rows.Next() {
err := rows.Scan(scanArgs...)
if err != nil {
return "", err
}

rowMap := make(map[string]interface{})
for i, col := range columns {
val := values[i]
b, ok := val.([]byte)
if ok {
rowMap[col] = string(b)
} else {
rowMap[col] = val
}
}

jsonData, err := json.Marshal(rowMap)
if err != nil {
return "", err
}

buffer.Write(jsonData)
buffer.WriteByte('\n')
}

if err = rows.Err(); err != nil {
return "", err
}

return buffer.String(), nil
}

// rowsToTSV converts the rows to TSV string
func rowsToTSV(rows *sql.Rows, cols bool) (string, error) {
var result []string
Expand Down
Loading