When / how are default value expression functions bound with regard to search_path?

后端 未结 3 1483
盖世英雄少女心
盖世英雄少女心 2021-01-25 16:06

For testing purposes, I provide my own implementation of the now() function which is public.now(). Using search_path to override the defau

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-25 16:20

    The default function is "bound" at the time the default constraint is created. The view showing the unqualified name is simply abbreviating it.

    This can be demonstrated by inserting rows before and after shadowing the function:

    Set search_path to public,pg_catalog;
    
    Create Temp Table foo (
        test date not null default now()
    );
    
    Insert Into foo default values;
    
    Create Function public.now() Returns timestamp with time zone Language SQL As $$ 
         -- No idea why I chose this date.
         Select '1942-05-09'::timestamp with time zone;
    $$;
    
    Insert Into foo default values;
    
    Select * from foo;
    

    Note that both rows (inserted before and after function creation) contain today's date, not the fake date.

    Furthermore, creating a table with the above function already in scope, then trying to delete the function, results in a dependency error:

    Set search_path to public,pg_catalog;
    
    Create Function public.now() Returns timestamp with time zone Language SQL As $$ 
        Select '1942-05-09'::timestamp with time zone;
    $$;
    
    Create Temp Table bar (
        test date not null default now()
    );
    
    Insert Into bar default values;
    
    Select * from bar;
    -- Single row containing the dummy date rather than today
    
    Drop Function public.now();
    -- ERROR:  cannot drop function now() because other objects depend on it
    

    If the binding happened only on insert, there would be no such dependency.

提交回复
热议问题