在PostgreSQL数据库创建表时,如果没有指定schema名称,会采用哪个schema?
在创建PostgreSQL数据库中的表时,如果没有提及schema名称,通常会以什么作为架构名的参考?
解决方案
这取决于你的 search_path。默认情况下是 "$user",它表示一个与当前用户同名的模式。如果该模式不存在,它会在搜索路径中检查下一个条目(通常是 public),以此类推。你可以通过调用 current_schema() 来检查:
current_schema → name
current_schema() → name
返回搜索路径中第一个存在的模式的名称(如果搜索路径为空则返回空值)。这是在未指定目标模式时创建的任何表或其他命名对象将使用的模式。
The "schema that is first in the search path" should say "first existing schema in the search path". You can have 4 entries and it'll return the 4th if the leading 3 can't be found. New objects will be created in the 4th schema: demo at db<>fiddle
drop schema if exists "1st";
drop schema if exists "2nd";
drop schema if exists "3rd";
create schema if not exists "4th";
set search_path to "1st", "2nd", "3rd", "4th";
create table my_table(i int);
select schemaname,tablename
from pg_tables
where tablename='my_table';
| 模式名 | 表名 |
|---|---|
| 4th | my_table |
The "null value if the search path is empty" should actually say "null value if none of the schemas listed in your search_path exists":
set search_path to 'this_schema_does_not_exist';
select current_schema();
| current_schema |
|---|
| null |
And that obviously leads to an error:
create table my_table4(i int);
none ERROR: no schema has been selected to create in LINE 3: create table my_table4(i int); ^
下面是如何在不丢失你此前在搜索路径中其他模式(架构)中的内容的前提下,安全地添加一个新模式
select set_config('search_path',concat_ws(', ','your_additional_schema',current_setting('search_path')), false);
Unlike doing this:
set search_path to your_additional_schema, "$user", public;
It doesn't require you to remember or check and re-list all entries each time you change it, and unlike doing just this:
set search_path to your_additional_schema;
它不会从该列表中移除其他条目,例如 public 和 "$user"。如果你把一些共享的函数、过程、类型等保存在那些地方,且你打算在这个新模式上工作时使用它们,那么这就不太合适。