go-jet / jet

Type safe SQL builder with code generation and automatic query result data mapping
Apache License 2.0
2.52k stars 118 forks source link

Count doesn't work #317

Closed Spargwy closed 7 months ago

Spargwy commented 7 months ago

Describe the bug

Environment (please complete the following information):

Code snippet

type Count struct {
    Count int64 `sql:"count"`
}

stmt := SELECT(COUNT(table.TableName.ID).AS("count")).
        FROM(table.TableName)

    response := repomodel.Count{}

    err := stmt.QueryContext(ctx, r.JetDB, &response)
    if err != nil {
        return 0, fmt.Errorf("select count: %w", err)
    }

Sql in result: SELECT COUNT(TableName.id) AS "count" FROM public.TableName;

Expected behavior I expect a result greater than 0 because the table is not empty. Before the count request, all rows are received and the data is ok.

fangorn312 commented 7 months ago

I think you should put the name of the struct in the "AS" method

type CountResponse struct {
    Count int64 `json:"count"`
}

stmt := SELECT(COUNT(table.TableName.ID).AS("count_response.count")).
        FROM(table.TableName)

    response := repomodel.Count{}

    err := stmt.QueryContext(ctx, r.JetDB, &response)
    if err != nil {
        return 0, fmt.Errorf("select count: %w", err)
    }
    log.Println(response.Count)
Spargwy commented 7 months ago

I think you should put the name of the struct in the "AS" method

Yes, this is the solution but I think this is a bit implicit. So examples should be added or logic changed

houten11 commented 7 months ago

More on scanning into custom model types can be found here, also check out this faq as well.

Spargwy commented 7 months ago

Thank you