volatiletech / sqlboiler

Generate a Go ORM tailored to your database schema.
BSD 3-Clause "New" or "Revised" License
6.66k stars 539 forks source link

After Eager, empty lists result in null "R" field #51

Closed jseriff closed 7 years ago

jseriff commented 7 years ago

When doing an eager, the R field is left as null if no eager objects are loaded. I think a non-null R, with an empty array in the loaded relationship would be more appropriate.

To reproduce, here is the schema I used:

CREATE SCHEMA test_schema;

CREATE TABLE test_schema.parents (
    id BIGSERIAL PRIMARY KEY,
    name TEXT
);

CREATE TABLE test_schema.children (
    id BIGSERIAL PRIMARY KEY,
    parent_id BIGINT REFERENCES test_schema.parents(id),
    name TEXT
);

INSERT INTO test_schema.parents (name) values ('P1');
INSERT INTO test_schema.parents (name) values ('P2');
INSERT INTO test_schema.children (parent_id, name) values ((select id from test_schema.parents where name = 'P2'), 'C21');
INSERT INTO test_schema.children (parent_id, name) values ((select id from test_schema.parents where name = 'P2'), 'C22');

So, P1 has no children, and P2 has two children. Create the models for this schema, then run the following:

package main

import (
    "database/sql"
    "fmt"

    "github.com/jseriff/sqltest/models"
    _ "github.com/lib/pq"
    "github.com/vattle/sqlboiler/queries/qm"
)

func main() {
    db, _ := sql.Open("postgres", "postgres://evsr_development:evsr_development@localhost:5432/evsr_development?options=+-c+search_path%%3Dtest_schema")

    parents, _ := models.Parents(db,
        qm.Load("Children"),
    ).All()

    for i := range parents {
        fmt.Printf("Parent %d.R: %v\n", i, parents[i].R)
    }
}

The output is:

Parent 0.R: <nil>
Parent 1.R: &{[0xc4200118c0 0xc420011900]}

You can see in the output that Parent 0.R is nil. This forces me to check R for nil before looking at the relationship, adding quite a bit of verbosity.

aarondl commented 7 years ago

@jseriff Thought about this a lot. I'm okay with it. If LoadX gets called on it, it will not be nil. Will implement soon. Solving your other bug right now, making good progress.

aarondl commented 7 years ago

@jseriff Have you tried this or the other bug fix yet? Things should be working well on dev.

jseriff commented 7 years ago

This is working now in dev. Please let me know when it gets released as a new version.

Thanks!