graphjin
graphjin copied to clipboard
Support a generic `run_sql` goja command for seeding database.
What would you like to be added:
It looks like cmd_seed has a couple of functions manually added, graphql
and import_csv
. It would also be nice to have something generic like run_sql
so we can populate the database directly and not write out 10+ csv files for initializing tables.
Why is this needed: Convenience and allow for more flexibility in the seed runner.
package main
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/dop251/goja"
_ "github.com/mattn/go-sqlite3"
)
func main() {
// Create an SQLite database and open a connection
db, err := sql.Open("sqlite3", "mydatabase.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Initialize Goja runtime
vm := goja.New()
// Define a run_sql function in JavaScript
runSQL := func(call goja.FunctionCall) goja.Value {
// Get the SQL query from the JavaScript argument
query := call.Argument(0).String()
// Execute the SQL query
_, err := db.Exec(query)
if err != nil {
fmt.Println("Error executing SQL query:", err)
return goja.Null()
}
return goja.Null()
}
// Register the run_sql function in the Goja runtime
vm.Set("run_sql", runSQL)
// Your JavaScript code for seeding the database
seedCode := `
run_sql("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
run_sql("INSERT INTO users (name) VALUES ('Alice')")
run_sql("INSERT INTO users (name) VALUES ('Bob')")
`
// Execute the JavaScript code
_, err = vm.RunString(seedCode)
if err != nil {
fmt.Println("Error executing JavaScript code:", err)
}
}