rel icon indicating copy to clipboard operation
rel copied to clipboard

Docs: Use a raw query?

Open IngwiePhoenix opened this issue 10 months ago • 3 comments

I made my SurrealDB driver work and am currently testing it - and while testing the more "not so standart" parts of SurrealDB, I realized that... I had no idea how to run raw queries.

func main() {
	adapter, err := srel.Open("ws://root:[email protected]:8000/rpc?method=root")
	if err != nil {
		log.Fatal(err.Error())
	}
	defer adapter.Close()

	repo := rel.New(adapter)
	sql := rel.SQL("INFO FOR ROOT;")
	cursor, err := adapter.Query(context.TODO(), rel.Query{
		SQLQuery: sql,
	})
	if err != nil {
		log.Fatal(err.Error())
	}
	fields, err := cursor.Fields()
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Print(fields)
}

Is there an easier way to construct raw queries? I can't imagine it's this convoluted... x)

Kind regards, Ingwie

IngwiePhoenix avatar Feb 11 '25 21:02 IngwiePhoenix

Hi Ingwie,

you can run raw query just like this:

sql := rel.SQL("SELECT id, title, price, orders = (SELECT COUNT(t.id) FROM [transactions] t WHERE t.book_id = b.id) FROM books b where b.id=?", 1)
err := repo.Find(ctx, &book, sql)

https://go-rel.github.io/queries/#native-sql-query

Fs02 avatar Feb 11 '25 23:02 Fs02

Great, thank you! Must've not seen the forest for all it's trees...

Last thing: Is there a better way to stringify generated queries? In my tests, I'd like to verify if my SQL generates correctly. Currently, I just cast the adapter to the initial instance returned by New(...); basically, in my case, adapter.(*SurrealDB). From there, I use it's QueryBuilder and pass it whatever query I had built (i.e. rel.From("books").Select("author")) to see what it generated.

inst := adapter.(*SurrealDB)
q := rel.From("books").Select("author")
sql, _ := inst.QueryBuilder.Build(q)
fmt.Println(sql)

Is there a more elegant solution rather than casting directly to the adapter type? I couldn't find a direct function for that in the interface.

By the way, the driver is here: https://github.com/IngwiePhoenix/surrealdb-driver/blob/master/pkg/rel/ - I have a lot of test cases to write yet, but this was implemented in but a day, which was quite easy to do actually.

Thanks and kind regards!

IngwiePhoenix avatar Feb 12 '25 05:02 IngwiePhoenix

the query builder is an internal adapter implementation right now, so there's no direct way to access it from rel as of now

Fs02 avatar Feb 18 '25 14:02 Fs02