I want to be able to create a Spanner view only if the source table contains at least one record. If not I want the view creation to fail. For instance, this is my view statement without any non-empty check:
CREATE OR REPLACE VIEW user_view
SQL SECURITY INVOKER
AS SELECT
user.name as name,
user.lastname as lastname
FROM user
Thanks
What you are asking is not directly possible. I can think of a couple of alternatives:
VIEW
definition is generated from code, then you could adjust your generation function in such a way that it automatically generates an invalid syntax if the source table is empty. But it would in that case probably be easier/cleaner to just not generate the view in the first place.create or replace view v_test
sql security invoker as
select case count(1)
when 0 then cast(cast(current_timestamp() as varchar) as bool)
else false
end as empty
from (select 1 from user limit 1) t
The trick in the above query is that the current_timestamp()
function is non-deterministic, but it will never return a value that can actually be cast to a bool
. This means that the query can be parsed and is accepted as a valid query for the VIEW
definition. The cast will only be invoked if the source table is empty.