Golang SQLC not generating structs

2.4k Views Asked by At

I am using sqlc and mysql, for some reason the generated code that is meant to execute the queries doesn't have the structs or fields in the functions for the objects am supposed to insert or query the db with.

My create table query looks similar to this

CREATE TABLE users (
    user_id int PRIMARY KEY,
    f_name varchar(255) NOT NULL,
    m_name varchar(255),
    l_name varchar(255) NOT NULL
);

The queries look like this

-- name: CreateUser :exec
INSERT INTO users (f_name,
                   m_name,
                   l_name)
VALUES ($1, $2, $3);

-- name: GetUserByUserId :one
SELECT * FROM users
WHERE user_id = $1;

This is what is generated

const createUser = `-- name: CreateUser :exec
INSERT INTO users (
                   f_name,
                   m_name,
                   l_name)
VALUES ($1, $2, $3)
`

func (q *Queries) CreateUser(ctx context.Context) error {
    _, err := q.db.ExecContext(ctx, createUser)
    return err
}

const getUserByUserId = `-- name: GetUserByUserId :one
SELECT f_name, m_name, l_name FROM users
WHERE user_id = $1
`

func (q *Queries) GetUserByUserId(ctx context.Context) (User, error) {
    row := q.db.QueryRowContext(ctx, getUserByUserId)
    var i User
    err := row.Scan(
        &i.UserID,
        &i.FName,
        &i.MName,
        &i.LName
    )
    return i, err
}

As you can see from in the code generated for createUser there is no struct generated that can in turn be passed a function parameter to CreateUser, the same for getUserByUserId there is no userId parameter being passed in the GetUserByUserId function.

Not certain what am doing wrong, here is how my sqlc.yaml file looks like

version: "1"
packages:
  - name: "db"
    path: "./db/sqlc"
    queries: "./db/query/"
    schema: "./db/migration/"
    engine: "mysql"
    emit_json_tags: true
    emit_prepared_queries: false
    emit_interface: false
    emit_exact_table_names: false
1

There are 1 best solutions below

0
On

So I did a little digging in the issues on the sqlc GitHub repo and found the solution here

My mistake was I was using $ when stating query parameters which mysql doesn't recognize. I used ? instead and it worked

My queries now looks something like this

-- name: CreateUser :exec
INSERT INTO users (f_name,
                   m_name,
                   l_name)
VALUES (?, ?, ?);

-- name: GetUserByUserId :one
SELECT * FROM users
WHERE user_id = ?;