Skip to content

Commit

Permalink
Reads query from args if Stdin is not piped.
Browse files Browse the repository at this point in the history
  • Loading branch information
aidin36 committed Aug 23, 2018
1 parent fc43acd commit eba5355
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ cat query.sql | sql test_db
sed 's/2015/2016/g' query_for_2015.sql | sql db1 db2 db3
echo "SELECT * FROM users WHERE name = 'John'" | sql all
sql all "SELECT * FROM users WHERE name = 'John'"
```

## Notes
Expand Down
20 changes: 18 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,28 @@ func main() {
usage("Target database unspecified; where should I run the query?")
}

sql := readInput(os.Stdin)
var sql string
var databasesArgs []string

stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) != 0 {
// Stdin is a terminal. The last argument is the SQL.
if len(os.Args) < 3 {
usage("No SQL to run. Exiting.")
}
sql = os.Args[len(os.Args)-1]
databasesArgs = os.Args[1 : len(os.Args)-1]
} else {
sql = readInput(os.Stdin)
databasesArgs = os.Args[1:]
}

if len(sql) <= 3 {
usage("No SQL to run. Exiting.")
}

targetDatabases := []string{}
for _, k := range os.Args[1:] {
for _, k := range databasesArgs {
if _, ok := databases[k]; k != "all" && !ok {
usage("Target database unknown: [%v]", k)
}
Expand Down Expand Up @@ -171,6 +186,7 @@ func readInput(r io.Reader) string {
for {
var s string
s, err = rd.ReadString('\n')

if err == io.EOF {
return strings.Join(ls, " ")
}
Expand Down
2 changes: 1 addition & 1 deletion usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ e.g.
sed 's/2015/2016/g' query_for_2015.sql | sql db1 db2 db3
echo "SELECT * FROM users WHERE name = 'John'" | sql all
sql all "SELECT * FROM users WHERE name = 'John'"
For more detailed help, please go to: https://github.com/marianogappa/sql
`)
Expand Down

0 comments on commit eba5355

Please sign in to comment.