PostgreSQL访问SequoiaDB时,字段名称的大小写问题

在PG的官网文档里,关于字段名称的大小写有这么一段描述:
https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html

因此,在pg里面针对标识符(identifier)-- 主要是字段名称 -- 的大小写处理逻辑是:
-- 如果不将它用引号括起来,那么pg会以“全部小写字母”的形式保存这些标识符。
   所以说,foo和FOO和Foo都是没有区别的,都等同于foo。
-- 如果对标识符加了引号,那么就保留标识符内的大小写来保存。
   因此,"foo"和"FOO"和"Foo"就是三个不同的字段名称了;但是"foo"和foo还是一样的,因为都是小写。

此外还有一点需要记住:SDB内的所有字段名都是区分大小写的(不会自动转成全小写或者全大写)!在SDB里,foo和FOO和Foo在任何情况下都是三个不同的字段名,不管你是否加引号。

明白了上面两点,就知道在pg连接SDB时如何处理大小写问题了。下面举几个例子:

###  示例一

# sdb
sdb 'db.foo.createCL("bar")'
sdb 'db.foo.bar.insert({"id":1, "name":"wang tao"})'
sdb 'db.foo.bar.insert({"id":2, "name":"tang xun"})'
sdb 'db.foo.bar.find()'

# pg
create foreign table sdb_foo_bar (id int, name text) server sdb_server options ( collectionspace 'foo', collection 'bar') ;
create foreign table sdb_foo_bar1 (ID int, name text) server sdb_server options ( collectionspace 'foo', collection 'bar') ;
create foreign table sdb_foo_bar2 (id int, NAME text) server sdb_server options ( collectionspace 'foo', collection 'bar') ;
上面这三个外表虽然用了不同的大小写形式,但由于没有加引号实际上都是同一个结果,即两个字段id和name。
并且,由于sdb中两个id和name也都是小写,所以这三个外表都可以访问到foo.bar中的所有数据。

create foreign table sdb_foo_bar1_upper ("ID" int, name text) server sdb_server options ( collectionspace 'foo', collection 'bar') ;
create foreign table sdb_foo_bar2_upper (id int, "NAME" text) server sdb_server options ( collectionspace 'foo', collection 'bar') ;
上面这两个外表,将大写字母的字段名都用引号括了起来,因此就有问题了。它们分别对应下面的字段名:
  ID, name
  id, NAME
对于第一张外表,无法获取foo.bar中的ID字段(因为foo.bar中是id),而第二张外表则无法获取foo.bar中的NAME字段(因为foo.bar中是name)。

###  示例二

# sdb
sdb 'db.foo.createCL("bar_new")'
sdb 'db.foo.bar_new.insert({"ID":1, "name":"wang tao"})'
sdb 'db.foo.bar_new.insert({"ID":2, "name":"tang xun"})'
sdb 'db.foo.bar_new.find()'

# pg
create foreign table sdb_foo_bar_new (id int, name text) server sdb_server options ( collectionspace 'foo', collection 'bar_new') ;
create foreign table sdb_foo_bar_new1 (ID int, name text) server sdb_server options ( collectionspace 'foo', collection 'bar_new') ;
create foreign table sdb_foo_bar_new2 (id int, NAME text) server sdb_server options ( collectionspace 'foo', collection 'bar_new') ;
同理,由于字段没有加引号所以上面三个外表实际上都是同一个结果:id和name。
但由于SDB的foo.bar_new中的字段名是大写的ID,所以这三个表都无法获取ID的数据。

create foreign table sdb_foo_bar_new1_upper ("ID" int, name text) server sdb_server options ( collectionspace 'foo', collection 'bar_new') ;
上面这张外表才正确地定义了两个字段:ID和name,因此能正确获取foo.bar_new中的数据。

需要注意的是:如果在SELECT语句里想使用具体的字段名而不是用*,那么必须是"ID"而不能是ID,因为不带引号的ID也会被转换成小写的id,从而成为一个不存在的字段名!

总结:

如果用pg连接sdb,我认为最佳的方法是:
1)在SDB里的字段名称尽量用全小写。
2)在pg里定义外表的时候,字段名不要使用引号;如果使用引号那要保证引号内是全小写。
3)在pg里执行SELECT的时候,字段名不要使用引号;如果使用引号那要保证引号内是全小写。

如果SDB里的字段名不是全小写(全大写,或者大小写混合),那么在pg里使用的时候会比较麻烦:
1)在pg里定义外表的时候,字段名必须使用引号!
2)在pg里执行SELECT的时候,字段名必须使用引号!

猜你喜欢

转载自blog.csdn.net/u014439239/article/details/80513269