AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-64463

dw8547's questions

Martin Hope
dw8547
Asked: 2019-06-05 04:18:51 +0800 CST

我们如何绕过 PostgreSQL autovacuum 在副本上使用表级锁 ACCESS EXCLUSIVE?

  • 3

我们正在运行:

user@primary/client-n:~$ psql -d database -c "SELECT version();"                                                                   
version
---------------------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 10.7 (Ubuntu 10.7-1.pgdg16.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609, 64-bit
(1 row)

上:

user@primary/client-n:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:        16.04
Codename:       xenial

并设置一个主客户端和两个流复制客户端,配置如下:

user@client-n:~$ psql -d postgres -c "SELECT name, setting FROM pg_settings WHERE name IN ( 'hot_standby', 'hot_standby_feedback', 'max_standby_streaming_delay' );"
           name             | setting 
----------------------------+---------
hot_standby                 | on
hot_standby_feedback        | on
max_standby_streaming_delay | 150000
(3 rows)

我们只有一个数据库(标准数据库除外)和数据库中的一个表。每天大约 3 到 4 次,我们会遇到一种特殊情况下的 autovacuum 情况,文档中将其描述为:

[...]它(autovacuum)不会将空间返回给操作系统,除非在特殊情况下,表末尾的一个或多个页面完全空闲并且可以轻松获得独占表锁

我们正在监视pg_locks并且已经能够观察到 autovacuum 守护进程获取表级锁定ACCESS EXCLUSIVE,这反过来会导致客户端上的大量进程被阻塞,如下面的日志条目所示:

基本的:

...
2019-06-04 05:59:29.154 BST [8998-1] LOG:  automatic vacuum of table "database.schema.table": index scans: 1
...

客户 1:

...
2019-06-04 05:59:03.660 BST [21167-858] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 21167 still waiting for AccessShareLock on relation 16390 of database 16388 after 1000.222 ms
2019-06-04 05:59:03.660 BST [21167-859] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  Process holding the lock: 2741. Wait queue: 21167, 1215, 26415.
2019-06-04 05:59:03.660 BST [21167-860] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT ...
2019-06-04 05:59:03.730 BST [1215-51] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 1215 still waiting for AccessShareLock on relation 16390 of database 16388 after 1000.188 ms at character 15
2019-06-04 05:59:03.730 BST [1215-52] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  Process holding the lock: 2741. Wait queue: 21167, 1215, 26415.
2019-06-04 05:59:03.730 BST [1215-53] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT ...
...
2019-06-04 05:59:19.975 BST [22242-4569] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 22242 still waiting for AccessShareLock on relation 16390 of database 16388 after 1000.281 ms at character 15
2019-06-04 05:59:19.975 BST [22242-4570] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  Process holding the lock: 2741. Wait queue: 21167, 1215, 26415, 2423, 1289, 24009, 22441, 2640, 1843, 1056, 23336, 28060, 1860, 1134, 19419, 14649, 2721, 29540, 20138, 22242.
2019-06-04 05:59:19.975 BST [22242-4571] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT...
...

以及持有锁的过程:

postgres=# SELECT pid, backend_type, wait_event_type, wait_event FROM pg_stat_activity WHERE pid = 2741;
 pid  | backend_type | wait_event_type |   wait_event
------+--------------+-----------------+----------------
 2741 | startup      | Activity        | RecoveryWalAll
(1 row)

在此处输入图像描述

客户 2:

...
2019-06-04 06:00:08.964 BST [16153-1] [PostgreSQL JDBC Driver@ip_address(port):role@database] | FATAL:  terminating connection due to conflict with recovery
2019-06-04 06:00:08.964 BST [16153-2] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  User was holding a relation lock for too long.
2019-06-04 06:00:08.964 BST [16153-3] [PostgreSQL JDBC Driver@ip_address(port):role@database] | HINT:  In a moment you should be able to reconnect to the database and repeat your command.
2019-06-04 06:00:09.964 BST [5747-537] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 5747 still waiting for AccessShareLock on relation 16390 of database 16388 after 1000.248 ms
2019-06-04 06:00:09.964 BST [5747-538] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  Process holding the lock: 12709. Wait queue: 5747, 19765, 16036, 14617, 12280, 14513, 14728, 15398, 27611, 14542, 15948, 23398, 5853, 5098, 4324, 10760, 23480, 30192, 15300, 16228.
2019-06-04 06:00:09.964 BST [5747-539] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT ...
2019-06-04 06:00:09.975 BST [19765-6847] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 19765 still waiting for AccessShareLock on relation 16390 of database 16388 after 1000.180 ms
2019-06-04 06:00:09.975 BST [19765-6848] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  Process holding the lock: 12709. Wait queue: 5747, 19765, 16036, 14617, 12280, 14513, 14728, 15398, 27611, 14542, 15948, 23398, 5853, 5098, 4324, 10760, 23480, 30192, 15300, 16228.
2019-06-04 06:00:09.975 BST [19765-6849] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT ...
...
2019-06-04 06:01:25.487 BST [15873-1] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 15873 still waiting for AccessShareLock on relation 16390 of database 16388 after 1000.218 ms at character 15
2019-06-04 06:01:25.487 BST [15873-2] [PostgreSQL JDBC Driver@ip_address(port):role@database] | DETAIL:  Process holding the lock: 12709. Wait queue: 5747, 19765, 16036, 14617, 12280, 14513, 14728, 15398, 27611, 14542, 15948, 23398, 5853, 5098, 4324, 10760, 23480, 30192, 15300, 16228, 16127, 16285, 15873.
2019-06-04 06:01:25.487 BST [15873-3] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT ...
...
2019-06-04 06:01:29.160 BST [16127-6] [PostgreSQL JDBC Driver@ip_address(port):role@database] | LOG:  process 16127 acquired AccessShareLock on relation 16390 of database 16388 after 8560.748 ms at character 15
2019-06-04 06:01:29.160 BST [16127-7] [PostgreSQL JDBC Driver@ip_address(port):role@database] | STATEMENT:  SELECT ...
...

再次持有锁的进程:

postgres=# SELECT pid, backend_type, wait_event_type, wait_event FROM pg_stat_activity WHERE pid = 2741;
 pid  | backend_type | wait_event_type |   wait_event
------+--------------+-----------------+----------------
12709 | startup      | Activity        | RecoveryWalAll
(1 row)

在此处输入图像描述

客户端上被阻止的查询导致 API 延迟在 10 到 20 秒之间,有时还会出现大量 5xx 响应。Out SRE 团队的任务是降低这些事件期间的 API 延迟,我们正在寻找解决这个问题的方法,我们认为这是一个非常小众的情况。我们目前正在recovery_min_apply_delay = 120s客户端 1 上进行试验(因此后面的日志条目),以便两个客户端不会同时锁定。这在一定程度上减少了错误响应的数量并稍微降低了延迟峰值。我们不确定如何完全解决这个问题,事实上,是否有可能这样做。我们将不胜感激您的建议。我们找到了这个相关的帖子,但遗憾的是,它也没有得到解决。

postgresql locking
  • 1 个回答
  • 1703 Views
Martin Hope
dw8547
Asked: 2019-05-11 07:01:55 +0800 CST

添加 JSONB 索引是否会使数据库膨胀?

  • 4

我们正在运行:

user@host:~$ psql -d database -c "SELECT version();"                                                                   
version
---------------------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 10.7 (Ubuntu 10.7-1.pgdg16.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609, 64-bit
(1 row)

上:

user@host:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial

并具有以下设置:

database=# \d+ schema.table
                                                                  Table "schema.table"
           Column            |            Type             | Collation | Nullable |                     Default                     | Storage  | Stats target | Description
-----------------------------+-----------------------------+-----------+----------+-------------------------------------------------+----------+--------------+-------------
 column_1                    | bigint                      |           | not null | nextval('table_id_seq'::regclass)               | plain    |              |
 column_2                    | character varying           |           | not null |                                                 | extended |              |
 column_3                    | character varying           |           | not null |                                                 | extended |              |
 column_4                    | character varying           |           | not null |                                                 | extended |              |
 column_5                    | timestamp without time zone |           | not null |                                                 | plain    |              |
 column_6                    | timestamp without time zone |           |          |                                                 | plain    |              |
 column_7                    | character varying           |           | not null |                                                 | extended |              |
 column_8                    | jsonb                       |           | not null |                                                 | extended |              |
 column_9                    | jsonb                       |           |          |                                                 | extended |              |
 column_10                   | character varying           |           | not null |                                                 | extended |              |
 column_11                   | character varying           |           | not null |                                                 | extended |              |
 column_12                   | character varying           |           |          |                                                 | extended |              |
 column_13                   | character varying           |           |          |                                                 | extended |              |
 column_14                   | timestamp with time zone    |           | not null |                                                 | plain    |              |
 column_15                   | timestamp with time zone    |           | not null |                                                 | plain    |              |
Indexes:
    "table_pkey" PRIMARY KEY, btree ( column_1 )
    "table_idx_1" btree ( column_11)
    "table_idx_2" btree ( column_4, column_2, column_7, column_5, column_6 )
    "table_idx_3" btree ( column_7, column_11, column_15 )
    "table_idx_4" btree ( column_7, column_11, column_14 )
    "table_idx_5" btree ( column_7, column_11, column_5 )
    "table_idx_6" btree ( column_7, ( ( column_8 ->> 'string_1'::TEXT )::INTEGER ), column_5 )
    "table_idx_7" btree ( column_15 )
    "table_idx_8" btree ( column_4, column_2, column_7, column_5, ( ( column_8 ->> 'string_1'::TEXT )::INTEGER ) )
    "table_idx_9" btree ( column_4, column_2, column_7, ( ( column_8 ->> 'string_1'::TEXT )::INTEGER) )
    "table_idx_a" btree ( column_7, column_4, column_2, ( ( column_8 ->> 'string_1'::TEXT )::INTEGER), ( ( column_8 ->> 'string_2'::TEXT )::INTEGER ) ) WHERE column_7::TEXT = 'string_3'::TEXT
Check constraints:
    "table_check_constraints" CHECK ( lower( column_10::TEXT ) <> 'string_4'::TEXT OR column_9 IS NOT NULL AND column_6 IS NOT NULL )

Autovacuum 已打开并配置为:

user@host:~$ psql -d database -c "SELECT name, setting, pending_restart FROM pg_settings WHERE NAME ILIKE '%autovacuum%' ORDER BY name;"
                name                 |  setting              | pending_restart
-------------------------------------+-----------------------+-----------------
 autovacuum                          | on                    | f
 autovacuum_analyze_scale_factor     | 0.002                 | f
 autovacuum_analyze_threshold        | 10                    | f
 autovacuum_freeze_max_age           | 200000000             | f
 autovacuum_max_workers              | 5                     | f
 autovacuum_multixact_freeze_max_age | 400000000             | f
 autovacuum_naptime                  | 30                    | f
 autovacuum_vacuum_cost_delay        | 10                    | f
 autovacuum_vacuum_cost_limit        | 1000                  | f
 autovacuum_vacuum_scale_factor      | 0.001                 | f
 autovacuum_vacuum_threshold         | 25                    | f
 autovacuum_work_mem                 | -1                    | f
 log_autovacuum_min_duration         | 0 (env 1) /-1 (env 2) | f
(13 rows)

以下事件序列发生在环境 1中,在此期间autovacuum已按上述方式开启和配置:

  1. 每晚VACUUM (VERBOSE, ANALYZE)添加数据库。
  2. 一段时间过去,膨胀处于正常运行水平。
  3. NightlyVACUUM (VERBOSE, ANALYZE)的数据库被删除。
  4. table_idx_8添加了包含 JSONB 数据类型列的索引。
  5. table_idx_9添加了包含 JSONB 数据类型列的索引。
  6. 膨胀的生长突增开始并持续 2 天,直到达到顶峰。
  7. VACUUM (VERBOSE, FULL)的表。
  8. 膨胀恢复到正常的操作水平并保持在那里。

在这一系列事件中,环境 1中的数据库大小 (GB) 如下所示:

环境 1 数据库大小 (GB)

这就是环境 1中膨胀 (GB) 的样子:

环境 1 数据库膨胀 (GB)

环境 1中的活动行数:

环境 1 活动行数

环境 1中的死行数:

环境 1 死行数

以下事件序列发生在环境 2中,在所有这些事件中都autovacuum按上述方式打开和配置:

  1. 每晚VACUUM (VERBOSE, ANALYZE)添加数据库。
  2. 一段时间过去,膨胀处于正常运行水平。
  3. NightlyVACUUM (VERBOSE, ANALYZE)的数据库被删除。
  4. table_idx_8添加了包含 JSONB 数据类型列的索引。
  5. table_idx_9添加了包含 JSONB 数据类型列的索引。
  6. 膨胀的增长突增开始并持续 2 天,直到达到峰值并使 DB 下降(磁盘已满)。
  7. TRUNCATE TABLE schema.table.
  8. 再次填充 schema.table 表。
  9. 膨胀并没有稳定下来并增长,直到它再次达到顶峰。
  10. TRUNCATE TABLE schema.table在磁盘再次填满之前。
  11. 数据库的 VACUUM (VERBOSE, FULL)。
  12. 再次填充 schema.table 表。
  13. 膨胀继续增长!

在这一系列事件中,环境 2中的数据库大小 (GB)如下所示:

在此处输入图像描述

这就是环境 2中膨胀 (GB) 的样子:

在此处输入图像描述

这两种环境之间的唯一区别是它们的规格略有不同(2 的功能较弱)。在这些事件序列中,每个环境的写入/读取量都没有变化。我们正在使用此查询来衡量膨胀(以字节为单位)。

我已经交叉检查了 PostgreSQL 日志、监控日志和提交日志 (Git),并确定添加两个索引作为膨胀的触发器,但是:

  1. 那正确吗?增加一个指数会引发如此膨胀的增长吗?
  2. 如果确实如此,为什么添加索引会触发膨胀?
  3. 为什么环境 1 稳定而环境 2 不稳定?
  4. 我们如何稳定环境 2?

任何回答这些问题的帮助将不胜感激,不用说,我很乐意提供我错过的任何其他可能有用的信息。

postgresql index
  • 1 个回答
  • 355 Views
Martin Hope
dw8547
Asked: 2018-10-04 02:25:42 +0800 CST

PostgreSQL 中函数的所有权限包括什么?

  • 3

我正在尝试查找EXECUTE和之间的区别的参考ALL:

GRANT { EXECUTE | ALL [ PRIVILEGES ] } ON { FUNCTION | ALL FUNCTIONS IN SCHEMA }...

但我能找到的只是文档所说的:

EXECUTE 允许使用指定的函数以及在函数之上实现的任何运算符。这是唯一适用于函数的特权类型。(此语法也适用于聚合函数。)

例如,我知道对于模式,ALL = CREATE + USAGE但我想在参考函数时仔细检查:

这是唯一适用于函数的特权类型。

在上面的文档片段中暗示了函数ALL = EXECUTE和:

GRANT ALL ON ALL FUNCTIONS...

相当于:

GRANT EXECUTE ON ALL FUNCTIONS...
postgresql permissions
  • 1 个回答
  • 9484 Views
Martin Hope
dw8547
Asked: 2018-07-25 05:18:02 +0800 CST

在 PostgreSQL 中将密码到期日期重置为 NULL

  • 2

我们正在清理/标准化系统上的数据库用户/应用程序帐户,这些帐户混合了由不同个人在不同时间使用不同命令创建的帐户。

我们有一种情况,对于某些帐户,密码过期日期属性已明确设置为无穷大,而对于某些帐户,则没有:

postgres=# \du+                                                                                    List of roles
    Role name     |                         Attributes                         | Member of |                                       Description
------------------+------------------------------------------------------------+-----------+-----------------------------------------------------------------------------------------
 user_1           |                                                            | {}        |
 user_2           |                                                            | {}        |
 user_3           | Password valid until infinity                              | {}        |
 user_4           | Password valid until infinity                              | {}        |

以便:

postgres=# SELECT * FROM pg_shadow;
     usename    | usesysid | usecreatedb | usesuper | userepl | usebypassrls |               passwd                | valuntil | useconfig
 ---------------+----------+-------------+----------+---------+--------------+-------------------------------------+----------+-----------
  user_1        |    12345 | f           | f        | f       | f            | md5_foo                             |          |
  user_2        |    12346 | f           | f        | f       | f            | md5_foo                             |          |
  user_3        |    12347 | f           | f        | f       | f            | md5_bar                             | infinity |
  user_4        |    12348 | f           | f        | f       | f            | md5_bar                             | infinity |
 (4 rows)

和:

postgres=# SELECT * FROM pg_roles;
     rolname    | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcanlogin | rolreplication | rolconnlimit | rolpassword | rolvaliduntil | rolbypassrls | rolconfig |  oid
 ---------------+----------+------------+---------------+-------------+-------------+----------------+--------------+-------------+---------------+--------------+-----------+-------
  user_1        | f        | f          | f             | f           | t           | f              |           -1 | ********    |               | f            |           | 12345
  user_1        | f        | f          | f             | f           | t           | f              |           -1 | ********    |               | f            |           | 12346
  user_1        | f        | f          | f             | f           | t           | f              |           -1 | ********    | infinity      | f            |           | 12347
  user_1        | f        | f          | f             | f           | t           | f              |           -1 | ********    | infinity      | f            |           | 12348
 (4 rows)

例如:user_1并且user_2创建于:

CREATE USER user_1/2 WITH ENCRYPTED PASSWORD 'foo';

而user_3anduser_4是用以下方式创建的:

CREATE USER user_3/4 WITH ENCRYPTED PASSWORD 'bar' VALID UNTIL 'infinity';

我们要重置VALID UNTIL属性,以便:

postgres=# \du+                                                                                    List of roles
     Role name     |                         Attributes                         | Member of |                                       Description
 ------------------+------------------------------------------------------------+-----------+-----------------------------------------------------------------------------------------
  user_1           |                                                            | {}        |
  user_2           |                                                            | {}        |
  user_3           |                                                            | {}        |
  user_4           |                                                            | {}        |

我们尝试过,但没有成功:

  1. ALTER ROLE user_1/2 WITH VALID UNTIL NULL;
  2. ALTER ROLE user_1/2 WITH VALID UNTIL '';
  3. ALTER ROLE user_1/2 WITH VALID UNTIL DEFAULT;

所以问题是,是否可以将密码过期日期角色属性重置为NULL/ DEFAULT,最好不必重新创建角色?

postgresql-9.5 role
  • 1 个回答
  • 4470 Views
Martin Hope
dw8547
Asked: 2017-05-11 03:06:50 +0800 CST

无法在 pgAdmin III 中打开“pg_hba.conf”

  • 2

我在跑步:

version
-----------------------------------------------------------------------------------------------------
PostgreSQL 9.4.11 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit
(1 row)

和:

pgAdmin III 1.22.2

一样的:

Description: Ubuntu 14.04.5 LTS
Release: 14.04

我可以用配置文件打开postgresql.conf配置文件,pgAdmin但不能用pg_hba.conf配置文件打开。

pgAdmin III pg_hba.conf 错误信息

两个文件都在同一个目录 ( /etc/postgresql/9.4/main) 中:

-rw-r----- 1 postgres postgres  4641 Jun 10  2016 pg_hba.conf
-rw-r--r-- 1 postgres postgres 21501 Jun 10  2016 postgresql.conf

但我注意到这两个配置文件具有不同的权限。我没有修改 的权限pg_hba.conf以使其与postgresql.conf.

默认情况下这些文件的权限不同吗?pg_hba.conf有更多限制读取权限的原因吗?我可以继续修改 的权限pg_hba.conf吗?

postgresql pgadmin
  • 1 个回答
  • 1697 Views
Martin Hope
dw8547
Asked: 2016-12-15 11:51:46 +0800 CST

使用 2+ 列旋转(使用 CROSSTAB?)

  • 3

我有一个deflator定义为的表:

               Table "deflator"
    Column   |       Type        | Modifiers
-------------+-------------------+-----------
country_code | smallint          | not null
country_name | character varying | not null
year         | smallint          | not null
deflator     | numeric           |
source       | character varying |

此表的示例输出如下所示:

country_code | country_name  | year | deflator | source
-------------+---------------+------+----------+----------
           1 | country_1     | 2016 |       12 | source_1
           1 | country_1     | 2015 |       11 | source_2
           1 | country_1     | 2014 |       10 | source_2
           2 | country_2     | 2016 |       15 | source_1
           2 | country_2     | 2015 |       14 | source_1
           2 | country_2     | 2014 |       13 | source_2
           3 | country_3     | 2016 |       18 | source_1
           3 | country_3     | 2015 |       17 | source_2
           3 | country_3     | 2014 |       16 | source_3
(9 rows)

如果我排除列source,我使用以下查询来透视表:

SELECT
    *
FROM CROSSTAB (
    'SELECT
        country_code
        , country_name
        , year
        , deflator
     FROM dimension.master_oecd_deflator
     ORDER BY 1;'
     , $$ VALUES ('2014'::TEXT), ('2015'::TEXT), ('2016'::TEXT) $$
) AS "ct" (
    "country_code" SMALLINT
    , "country_name" TEXT
    , "2014" NUMERIC
    , "2015" NUMERIC
    , "2016" NUMERIC
);

上面的查询给了我:

country_code |   country_name    | 2016 | 2015 | 2014 |
-------------+-------------------+------+--- --+------+
           1 | country_1         | 12   | 11   | 10   |
           2 | country_2         | 15   | 14   | 13   |
           3 | country_3         | 18   | 17   | 16   |

但是由于每个国家的平减指数的来源每年都不同,我想source在枢轴中包含该列,以使我想要的输出看起来像:

country_code |   country_name    | 2016 | 2016_source | 2015 | 2015_source | 2014 | 2014_source
-------------+-------------------+------+-------------+------+-------------+------+------------
           1 | country_1         | 12   | source_1    | 11   | source_2    | 10   | source_2
           2 | country_2         | 15   | source_1    | 14   | source_1    | 13   | source_2
           3 | country_3         | 18   | source_1    | 17   | source_2    | 16   | source_3

如何修改此查询以提供所需的输出?(每年的来源都列在年份旁边)。这甚至可能吗?

postgresql postgresql-9.4
  • 2 个回答
  • 3151 Views
Martin Hope
dw8547
Asked: 2016-07-15 01:30:43 +0800 CST

如何将较长的 PL/pgSQL 代码行拆分为多行?

  • 21

有没有办法将一长串 PL/pgSQL 代码拆分为多行?我的上下文是一个触发函数,我按照以下方式将插入记录到表中:

INSERT INTO insert_log (log_time, description)
VALUES (
    now()
    , 'A description. Made up of 3 semi long sentences. That I want to split, in the code, not in the log table, over 3 lines for readability.'
);
postgresql-9.4
  • 1 个回答
  • 16473 Views
Martin Hope
dw8547
Asked: 2016-04-02 05:01:20 +0800 CST

循环字符串文字作为函数 PostgreSQL 9.4 的输入

  • 1

我有一个update_total看起来像这样的函数:

CREATE OR REPLACE FUNCTION update_total (table_name CHARACTER VARYING, year CHARACTER(4), donor_type CHARACTER VARYING, donor_code CHARACTER(5)) RETURNS VOID AS $$

DECLARE

table_name ALIAS FOR $1;
year ALIAS FOR $2;
donor_type ALIAS FOR $3;
donor_code ALIAS FOR $4;
query_statement TEXT;

BEGIN

    query_statement :=
    '
    UPDATE gha.' || table_name  || '
    SET "' || year || '" = "' || year ||'_total"
    FROM gha.' || table_name || ' "' || year || '",
    (
        SELECT
        donor_type
        , COALESCE(SUM("' || year || '"), 0) AS "' || year ||'_total"
        FROM gha.' || table_name || '
        WHERE donor_type = ''' || donor_type || '''
        GROUP BY donor_type
    ) "new_data"
    WHERE
    gha.' || table_name || '.donor_code = ' || CAST(donor_code AS INT) || ';'
    ;

    EXECUTE query_statement;

END;
$$ LANGUAGE plpgsql;

它更新表中包含聚合值的行,我称它为,例如,如下所示:

SELECT update_total ('bilateral_oda_dac_1', '1990', 'Multilateral', '20002');

它更新的表设置为每年都有一个范围内的列,即:

   Column   |       Type        
------------+-------------------
 donor_code | smallint           
 donor_name | character varying 
 donor_type | character varying  
 1990       | numeric            
 1991       | numeric      
 1992       | numeric  
...

使用此功能,我一次只能更新一列中的聚合值,但我希望能够一次更新一系列列,大致如下:

CREATE FUNCTION update_all_total ()
    RETURNS void LANGUAGE plpgsql AS

$BODY$
BEGIN

FOR i IN 1990 .. 1995
LOOP
   PERFORM update_total ('bilateral_oda_dac_1', i, 'DAC', '20001');
END LOOP;

END;
$BODY$;

(我用这篇文章让我开始:https ://stackoverflow.com/questions/11164409/sql-call-function-multiple-times-in-a-loop-postgres-8-3 )。上面截断的代码不起作用,因为我正在使用的函数将字符串作为输入,并且我向它传递了一个整数。我如何设置循环以便将字符串传递给我在其中调用的函数?

postgresql-9.4 functions
  • 1 个回答
  • 1344 Views
Martin Hope
dw8547
Asked: 2015-10-15 02:44:17 +0800 CST

使用名称以数字开头的 PostgreSQL information_schema 和表(具有相同的名称,在不同的模式中)

  • 0

我需要使用名称以数字开头的表。例如,在crs_1973模式中有一个名为 的表2015_04_21。我知道当表名由数字组成时,我必须双引号才能使用它,例如,SELECT * FROM crs_1973."2015_04_21";(这对我有用)。但是,我想从 PostgreSQL 中提取有关此表的信息information_schema。具体来说,我需要表中列的数据类型2015_04_21,

我用一个名称以字母开头的表尝试了这个查询,它产生了期望的结果:

SELECT column_name, data_type
FROM   information_schema.columns
WHERE  table_name = 'some_table_name_that_starts_with_a_letter'
ORDER  BY ordinal_position;

但是,当我使用名称以数字开头的表运行此查询时,它不会。例如:

WHERE  table_name = 'crs_1973.2015_04_21'

不起作用。也没有:

WHERE  table_name = 'crs_1973'.'2015_04_21'
WHERE  table_name = 'crs_1973'."2015_04_21"
WHERE  table_name = 'crs_1973'.'"2015_04_21"'
...

等。如何使此查询适用于以数字开头的表名?这可能吗?

在几个不同的模式中有名为“2015_04_21”的表,因此我需要将限定的表名传递给查询。

datatypes postgresql-9.3
  • 1 个回答
  • 137 Views
Martin Hope
dw8547
Asked: 2015-08-11 02:29:14 +0800 CST

为什么我在 psql 中使用 \dt(+) 时看不到我的表 (PostgreSQL)?

  • 16

我按照以下方式donor在模式reference中创建了表:

CREATE TABLE reference.donor (
    donor_code smallint PRIMARY KEY,
    donor_name character varying NOT NULL,
    donor_type smallint REFERENCES reference.donor_type (type_id),
    alpha_2_code char(2) REFERENCES reference.iso_3166_1 (alpha_2_code)
);

我已经按照以下方式填充了表格:

INSERT INTO reference.donor (donor_code, donor_name, donor_type, alpha_2_code)
SELECT donor_code, donor_name, donor_type, alpha_2_code
FROM reference.donor_template;

当我运行时:

\dt+ reference.*

在 psql 里面我看到了reference.donor表格:

                          List of relations
  Schema   |      Name      | Type  |  Owner   | Size  | Description 
-----------+----------------+-------+----------+-------+-------------
 reference | donor          | table | postgres | 16 kB | 
 reference | donor_template | table | postgres | 16 kB | 
 reference | donor_type     | table | postgres | 16 kB | 
 reference | iso_3166_1     | table | postgres | 48 kB | 
(4 rows)

但是当我运行\dt+ donor*(或\dt(+))时,我看不到reference.donor表格:

                          List of relations
  Schema   |      Name      | Type  |  Owner   | Size  | Description 
-----------+----------------+-------+----------+-------+-------------
 oecd_cl   | donor          | table | postgres | 16 kB | 
 reference | donor_template | table | postgres | 16 kB | 
 reference | donor_type     | table | postgres | 16 kB | 
(3 rows)

为什么我只有在运行or时才能看到reference.donor表格? 我期待(或)显示它,但它没有。\dt+ reference.*\dt+ *.donor
\dt\dt+

我的search_path包括架构reference和用户对架构和架构中的所有表postgres具有所有权限,如下所示:reference

GRANT ALL ON ALL TABLES IN SCHEMA reference TO postgres;

澄清一下,我有两个donor表,但它们位于两个不同的模式中,即oecd.donor& reference.donor。(当我在 psql 中使用时,我可以看到oecd.donor没有任何问题)。\dt(+)

postgresql schema
  • 2 个回答
  • 38996 Views
Martin Hope
dw8547
Asked: 2015-05-15 01:10:48 +0800 CST

使用源代码或使用 apt-get 安装 PostgreSQL?

  • 3

我想在运行 Ubuntu 14.04.2 LTS 的服务器上安装 PostgreSQL。

我知道我有两个选择:

  1. 使用源代码分发安装 PostgreSQL
  2. apt-get install postgresql postgresql-contrib使用这些说明安装 PostgreSQL 。

我应该使用哪个选项?

  • 结果会有不同吗?
  • 这两个选项是否会导致相同的设置和配置(假设我选择选项 #1 的默认安装)?
  • 是否存在我更喜欢选项 #1 而不是选项 #2 的情况,反之亦然?
postgresql installation
  • 2 个回答
  • 1218 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    连接到 PostgreSQL 服务器:致命:主机没有 pg_hba.conf 条目

    • 12 个回答
  • Marko Smith

    如何让sqlplus的输出出现在一行中?

    • 3 个回答
  • Marko Smith

    选择具有最大日期或最晚日期的日期

    • 3 个回答
  • Marko Smith

    如何列出 PostgreSQL 中的所有模式?

    • 4 个回答
  • Marko Smith

    列出指定表的所有列

    • 5 个回答
  • Marko Smith

    如何在不修改我自己的 tnsnames.ora 的情况下使用 sqlplus 连接到位于另一台主机上的 Oracle 数据库

    • 4 个回答
  • Marko Smith

    你如何mysqldump特定的表?

    • 4 个回答
  • Marko Smith

    使用 psql 列出数据库权限

    • 10 个回答
  • Marko Smith

    如何从 PostgreSQL 中的选择查询中将值插入表中?

    • 4 个回答
  • Marko Smith

    如何使用 psql 列出所有数据库和表?

    • 7 个回答
  • Martin Hope
    Jin 连接到 PostgreSQL 服务器:致命:主机没有 pg_hba.conf 条目 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane 如何列出 PostgreSQL 中的所有模式? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh 为什么事务日志不断增长或空间不足? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland 列出指定表的所有列 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney MySQL 能否合理地对数十亿行执行查询? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx 如何监控大型 .sql 文件的导入进度? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison 你如何mysqldump特定的表? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas 如何使用 psql 对 SQL 查询进行计时? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas 如何从 PostgreSQL 中的选择查询中将值插入表中? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas 如何使用 psql 列出所有数据库和表? 2011-02-18 00:45:49 +0800 CST

热门标签

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve