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

Support a generic run_sql goja command for seeding database. #152

Open
jacobblock opened this issue Aug 20, 2020 · 1 comment
Open

Support a generic run_sql goja command for seeding database. #152

jacobblock opened this issue Aug 20, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@jacobblock
Copy link

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.

@jacobblock jacobblock added the enhancement New feature or request label Aug 20, 2020
@ljluestc
Copy link

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)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants