deagleshot
deagleshot

Reputation: 215

Go: Funcs and Structs

I have a generated sqlc functions and structs here

const getAccount = `-- name: GetAccount :one
SELECT id, owner, balance, currency, created_at FROM accounts
WHERE id = $1 LIMIT 1
`

func (q *Queries) GetAccount(ctx context.Context, id int64) (Account, error) {
    row := q.queryRow(ctx, q.getAccountStmt, getAccount, id)
    var i Account
    err := row.Scan(
        &i.ID,
        &i.Owner,
        &i.Balance,
        &i.Currency,
        &i.CreatedAt,
    )
    return i, err
}

func (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {
switch {
case stmt != nil && q.tx != nil:
    return q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)
case stmt != nil:
    return stmt.QueryRowContext(ctx, args...)
default:
    return q.db.QueryRowContext(ctx, query, args...)
}
}

I am in process of learning Golang and need some clarification of what is happening in the code.

From my understanding, GetAccount takes 2 parameters ctx and id which returns either a Account Model or error model

In this function, variable row is assigned and automatically inferred to q.queryRow and passes in ctx, q.getAccountStmt, the sql query and id.

So what is q.getAccountStmt?

And What is func (q *Queries) mean here?

Also why is err assigned to row.Scan()?

when it states return i, err; does it mean it will return both i and err?

Upvotes: 0

Views: 65

Answers (1)

Schwern
Schwern

Reputation: 164629

What is func (q *Queries) mean here?

It means the function is a method to be called on a pointer to a Queries type. That pointer is put into the variable q. q is like this in Javascript, but you get to choose the variable name. See Go By Example: Methods and Effective Go: Methods.

What is q.getAccountStmt?

This gets the value stored in the field getAccountStmt from q, which we know from above is a pointer to a Queries struct. See Go By Example: Structs.

Why is err assigned to row.Scan()?

The other way around, the return value of row.Scan() is assigned to err. row.Scan() returns an error code, this is how Go generally handles errors. See Go By Example: Errors and Effective Go: Errors.

row.Scan() only returns an error because it puts the values read from the database row directly into its arguments. That is why they are passed as pointers. See Go By Example: Pointers.

Upvotes: 4

Related Questions