// Testcase from ThePendulum

// Building must contain any of the specified people
select("buildings", [
	define("tenants", has("tenants.building_id")),
	where({ tenants: { name: anyOf([ "james", "luke", "stanley" ]) } })
])


// Building must contain *all* of the specified people, and optionally others
select("buildings", [
	define("tenants", has("tenants.building_id")),
	where({ tenants: { name: allOf([ "james", "luke", "stanley" ]) } })
])

// Additional testcase: Building must contain *only* the specified people


// Related code:
	/* GraphQL/Postgraphile 'every' applies to the data, will only include scenes for which every assigned tag is selected,
		instead of what we want; scenes with every selected tag, but possibly also some others */
		CREATE FUNCTION actors_scenes(actor actors, selected_tags text[], mode text DEFAULT 'all') RETURNS SETOF releases AS $$
		SELECT releases.*
		FROM releases
		LEFT JOIN
			releases_actors ON releases_actors.release_id = releases.id
		LEFT JOIN
			releases_tags ON releases_tags.release_id = releases.id
		LEFT JOIN
			tags ON tags.id = releases_tags.tag_id
		WHERE releases_actors.actor_id = actor.id
		AND CASE
			/* match at least one of the selected tags */
			WHEN mode = 'any' AND array_length(selected_tags, 1) > 0
			THEN tags.slug = ANY(selected_tags)
			ELSE true
			END
		GROUP BY releases.id
		HAVING CASE
			/* match all of the selected tags */
			WHEN mode = 'all' AND array_length(selected_tags, 1) > 0
				THEN COUNT(
					CASE WHEN tags.slug = ANY(selected_tags)
					THEN true
					END
				) = array_length(selected_tags, 1)
			ELSE true
		END;
	$$ LANGUAGE SQL STABLE;
