stephenafamo/bob

No way of adding a column alias for "select" column

RangelReale opened this issue · 2 comments

I want to generate this fictional query (the real one is much more complex):

select p.post_id, p.title,  
 	(select pt.tag_id from posts_tags pt where p.post_id = pt.post_id limit 1) AS first_tag
from posts p 

I can't add the "first_tag" alias to the subselect in the query builder, psql.Select don't have an "As" method.

	query := psql.Select(
		sm.Columns("d.post_id"),
		sm.Columns(
			psql.Select(
				sm.Columns(`pt.tag_id`),
				sm.From("posts_tags pt"),
				sm.Where(psql.Raw(`p.post_id = pt.post_id`)),
				sm.Limit(1),
			),
		),
		sm.From("posts").As("p"),
	)

I've added an As() starter function in d5872f4 . You should now be able to do this:

	query := psql.Select(
		sm.Columns("d.post_id"),
		sm.Columns(
			psql.As(psql.Select(
				sm.Columns(`pt.tag_id`),
				sm.From("posts_tags pt"),
				sm.Where(psql.Raw(`p.post_id = pt.post_id`)),
				sm.Limit(1),
			), "first_tag"),
		),
		sm.From("posts").As("p"),
	)

Side note: You can pass multiple columns to a single sm.Columns().

Great, didn't know that!