#126·script

Question: Prepend a string to a file within a pipeline?

Author: Michael-F-EllisCreated Jul 3, 2022Updated Sep 8, 2024

First, thanks for creating and maintaining this package! It's something I've wished for repeatedly since discovering Go a few years ago AND the implementation is really clean.

Upon discovering script yesterday, I put it to work in query handler for sqlite.

go
// Query executes a SQL query contained in a file at qrypath against the sqlite3
// db file located at dbpath.  The result is returned as a string and err will
// be non-nil if an error is encountered.
// You may pass zero or more sqlite3 special commands in dotcmd. These are
// typically used to change the output format, e.g. ".mode json" but other
// special commands may be useful.  Sqlite3 currently recognizes more than 60
// dot commands. See https://www.sqlite.org/cli.html for more info.
func Query(qrypath string, dbpath string, dotcmd ...string) (result string, err error) {
	qrybytes, err := ioutil.ReadFile(qrypath)
	if err != nil {
		return
	}
	qry := strings.Join(dotcmd, "\n") + "\n" + string(qrybytes)
	cmd := fmt.Sprintf("sqlite3 %s", dbpath)
	result, err = script.Echo(qry).Exec(cmd).String()
	return
}

So is there any way to construct a pipeline that would catenate the joined dotcmd lines and the content of the sql file (qrypath) before passing it to Exec?