GORM Playground Link

https://github.com/go-gorm/playground/pull/835

Description

Gorm v1.31.0

Function:

func (r *LayoutRepository) GetLayouts(ctx context.Context, projectId uuid.UUID, userId uuid.NullUUID) ([]models.Layout, error) {
    layouts := []models.Layout{}
    byUser := func(dbScope *gorm.DB) *gorm.DB {
        if userId.Valid {
            return dbScope.Where(dbScope.Where("private_for = ?", userId).Or("private_for IS NULL")) // Problem is here
        }
        return dbScope
    }
    res := r.db.WithContext(ctx).Table("layouts").Scopes(byUser).Find(&layouts, map[string]any{"project_id": projectId})
    return layouts, res.Error
}

It rendered as:

SELECT * FROM "layouts" WHERE "layouts"."project_id" = '0199a4b7-1359-7587-b83d-c044f1949514' AND private_for = '7f23f9cc-835a-4821-b266-c7eae4f6a7fe' OR private_for IS NULL AND ("layouts"."project_id" = '0199a4b7-1359-7587-b83d-c044f1949514' AND private_for = '7f23f9cc-835a-4821-b266-c7eae4f6a7fe' OR private_for IS NULL)

Which is unexpected.

If I replace call to .Or() with string like this:

func (r *LayoutRepository) GetLayouts(ctx context.Context, projectId uuid.UUID, userId uuid.NullUUID) ([]models.Layout, error) {
    layouts := []models.Layout{}
    byUser := func(dbScope *gorm.DB) *gorm.DB {
        if userId.Valid {
            return dbScope.Where("(private_for = ? OR private_for IS NULL)", userId) // Change is here
        }
        return dbScope
    }
    res := r.db.WithContext(ctx).Table("layouts").Scopes(byUser).Find(&layouts, map[string]any{"project_id": projectId})
    return layouts, res.Error
}

It rendered as:

SELECT * FROM "layouts" WHERE "layouts"."project_id" = '0199a4b7-1359-7587-b83d-c044f1949514' AND ((private_for = '7f23f9cc-835a-4821-b266-c7eae4f6a7fe' OR private_for IS NULL))

Which is expected.

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking