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

Named GET? #888

Open
tamis-laan opened this issue Aug 8, 2023 · 4 comments
Open

Named GET? #888

tamis-laan opened this issue Aug 8, 2023 · 4 comments

Comments

@tamis-laan
Copy link

How would I achieve the following, is there something like a NamedGET?

type RequestReport struct {
	Title       string `db:"title" json:"title"`
	Description string `db:"description" json:"description"`
}

type ResponseReport struct {
	Id          uuid.UUID `db:"id" json:"id"`
	Title       string    `db:"title" json:"title"`
	Description string    `db:"description" json:"description"`
}
// Construct the query
query := `
	INSERT INTO reports 
		(title, description) 
	VALUES 
		(:title, :description) 
	RETURNING *
`
err = db.Get(responseReport, query, requestReport)
@gab-aquino
Copy link

You can use db.NamedQuery to achieve that. Check this issue #83

Let me know if it works for you.

@tamis-laan
Copy link
Author

@gab-aquino
I don't think that works, rows.Scan requires all separate arguments from the struct:

rows.Scan(&report.title, &report.description)

Instead of

rows.Scan(&report) 

This would make it cumbersome for larger structs.

@gab-aquino
Copy link

gab-aquino commented Aug 11, 2023

@tamis-laan

You can use rows.StructScan instead. https://jmoiron.github.io/sqlx/#advancedScanning

@tamis-laan
Copy link
Author

@tamis-laan

You can use rows.StructScan instead. https://jmoiron.github.io/sqlx/#advancedScanning

Thnx for the tip, that would work:

type DB struct {
	*sqlx.DB
}

func (db DB) NamedGet(dest interface{}, query string, arg interface{}) error {

	// Execute the named query
	rows, err := db.NamedQuery(query, arg)

	// Error check
	if err != nil {
		return err
	}

	// Scan into struct
	if rows.Next() {
		err = rows.StructScan(&dest)
	}

	// Error check
	if err != nil {
		return err
	}

	// Success
	return nil
}

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

No branches or pull requests

2 participants