pgadmin4树节点增删查

一,服务器组

二,服务器

三,数据库

(一)查询

(二)创建数据库

1,general标签

在这里插入图片描述

(1)查询“所有者”

在这里插入代码片

4,参数标签

pgadmin4树节点增删查_第1张图片

(1)查询“名称”与“类型”

SELECT name, vartype, min_val, max_val, enumvals	
FROM pg_catalog.pg_settings WHERE context in ('user', 'superuser')

(2)查询“角色”

SELECT
	r.oid, r.rolname, r.rolcanlogin, r.rolsuper
FROM
	pg_catalog.pg_roles r
ORDER BY r.rolcanlogin, r.rolname

(三)属性

(四)删除

(五)备份与恢复

查看这里:pgadmin4中的备份与恢复

(六)刷新

四,事件触发器 Event Trigger

创建与使用见附录。

(一)查询事件触发器

pgadmin4树节点增删查_第2张图片
pg模板:

SELECT e.oid, e.evtname AS name
FROM pg_catalog.pg_event_trigger e
{% if etid %}
WHERE e.oid={{etid}}::oid
{% endif %}
{% if schema_diff %}
WHERE CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
    WHERE objid = e.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY e.evtname

实际执行:

SELECT e.oid, e.evtname AS name
FROM pg_catalog.pg_event_trigger e
ORDER BY e.evtname

(二)创建

1,general标签

(1)查询“所有者”

pgadmin4树节点增删查_第3张图片

同上

2,定义标签

pgadmin4树节点增删查_第4张图片

(1)获取“触发器函数”

pg模板:

SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfname
FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_language l
WHERE p.pronamespace = n.oid AND p.prolang = l.oid AND p.pronargs = 0 AND l.lanname != 'sql' AND prorettype::regtype::text = 'event_trigger'
ORDER BY nspname ASC, proname ASC

实际执行:

SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfname
FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_language l
WHERE p.pronamespace = n.oid AND p.prolang = l.oid AND p.pronargs = 0 AND l.lanname != 'sql' AND prorettype::regtype::text = 'event_trigger'
ORDER BY nspname ASC, proname ASC
  • 但pgadmin4会查出来一条空数据,不知道为什么:
    pgadmin4树节点增删查_第5张图片

3,点击保存

pg模板:

{% if data %}
CREATE EVENT TRIGGER {{ conn|qtIdent(data.name) }} ON {{data.eventname}}
{% if data.when %}
    WHEN TAG IN ({{data.when}})
{% endif %}
    EXECUTE PROCEDURE {{data.eventfunname}}();
{% endif %}

ALTER EVENT TRIGGER {{ conn|qtIdent(data.name) }}
    OWNER TO {{ conn|qtIdent(data.eventowner) }};

请求参数:

gid=1
sid=1
did=13799

data = {'name': 'log_ddl_info', 'eventowner': 'postgres', 'enabled': 'O', 'eventfunname': 'public.log_ddl', 'eventname': 'DDL_COMMAND_END'}

填充SQL:

sql = render_template(
    "/".join([self.template_path, self._CREATE_SQL]),
    data=data, conn=self.conn
)

实际执行:

CREATE EVENT TRIGGER log_ddl_info ON DDL_COMMAND_END
    EXECUTE PROCEDURE public.log_ddl();

ALTER EVENT TRIGGER log_ddl_info
    OWNER TO postgres;

(三)属性

请求参数:

etid=24599
  • 获取 etid :SELECT e.oid from pg_catalog.pg_event_trigger e WHERE e.evtname = '事件触发器名称'

pg模板:

SELECT e.oid, e.xmin, e.evtname AS name, upper(e.evtevent) AS eventname,
pg_catalog.pg_get_userbyid(e.evtowner) AS eventowner,
e.evtenabled AS enabled,
e.evtfoid AS eventfuncoid,
CASE
  WHEN n.nspname = 'public'
  THEN pg_catalog.quote_ident(n.nspname) || '.' || cast(e.evtfoid::regproc as text)
  ELSE cast(e.evtfoid::regproc as text)
END AS  eventfunname,
pg_catalog.array_to_string(array(select pg_catalog.quote_literal(x) from pg_catalog.unnest(evttags) as t(x)), ', ') AS when,
 pg_catalog.obj_description(e.oid, 'pg_event_trigger') AS comment,
 (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabel sl1 WHERE sl1.objoid=e.oid) AS seclabels,
 p.prosrc AS source, p.pronamespace AS schemaoid, l.lanname AS language
 FROM pg_catalog.pg_event_trigger e
 LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=e.evtfoid
 LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang,
 pg_catalog.pg_namespace n
 WHERE p.pronamespace = n.oid
{% if etid %}
 AND e.oid={{etid}}::oid
{% endif %}
  ORDER BY e.evtname

实际执行 :

SELECT e.oid, e.xmin, e.evtname AS name, upper(e.evtevent) AS eventname,
pg_catalog.pg_get_userbyid(e.evtowner) AS eventowner,
e.evtenabled AS enabled,
e.evtfoid AS eventfuncoid,
CASE
  WHEN n.nspname = 'public'
  THEN pg_catalog.quote_ident(n.nspname) || '.' || cast(e.evtfoid::regproc as text)
  ELSE cast(e.evtfoid::regproc as text)
END AS  eventfunname,
pg_catalog.array_to_string(array(select pg_catalog.quote_literal(x) from pg_catalog.unnest(evttags) as t(x)), ', ') AS when,
 pg_catalog.obj_description(e.oid, 'pg_event_trigger') AS comment,
 (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabel sl1 WHERE sl1.objoid=e.oid) AS seclabels,
 p.prosrc AS source, p.pronamespace AS schemaoid, l.lanname AS language
 FROM pg_catalog.pg_event_trigger e
 LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=e.evtfoid
 LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang,
 pg_catalog.pg_namespace n
 WHERE p.pronamespace = n.oid
 AND e.oid=24599::oid
  ORDER BY e.evtname

(四)删除

pg模板:

{% if etid %}
SELECT e.evtname AS name FROM pg_catalog.pg_event_trigger e
WHERE e.oid={{etid}}::oid;
{% endif %}

{% if name %}
DROP EVENT TRIGGER IF EXISTS {{ conn|qtIdent(name) }}{% if cascade%} CASCADE{% endif %};
{% endif %}

实际执行:

DROP EVENT TRIGGER IF EXISTS log_ddl_drop_info;

五,触发器函数 Trigger Functions

(一)查询

在这里插入图片描述
pg模板:

SELECT
    pr.oid, pr.proname || '()' as name,
    lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
WHERE
    proisagg = FALSE
{% if fnid %}
    AND pr.oid = {{ fnid|qtLiteral(conn) }}
{% endif %}
{% if scid %}
    AND pronamespace = {{scid}}::oid
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
    AND typname IN ('trigger', 'event_trigger')
    AND lanname NOT IN ('edbspl', 'sql', 'internal')
ORDER BY
    proname;

实际执行:

SELECT
    pr.oid, pr.proname || '()' as name,
    lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
WHERE
    pr.prokind IN ('f', 'w')
    AND pronamespace = 2200::oid
    AND typname IN ('trigger', 'event_trigger')
    AND lanname NOT IN ('edbspl', 'sql', 'internal')
ORDER BY
    proname;

(二)创建

1,General标签

pgadmin4树节点增删查_第6张图片

2,定义标签

pgadmin4树节点增删查_第7张图片

3,代码标签

pgadmin4树节点增删查_第8张图片
实际只需要填:

DECLARE
  audit_query TEXT;
  r RECORD;
BEGIN
  IF tg_tag = 'DROP TABLE'
  THEN
    FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() 
    LOOP
      INSERT INTO ddl_history (ddl_date, ddl_tag, object_name) 
      	     VALUES (statement_timestamp(), tg_tag, r.object_identity);
    END LOOP;
  END IF;
END;

以上等价于直接执行SQL:

CREATE OR REPLACE FUNCTION log_ddl_drop()
  RETURNS event_trigger AS $$
DECLARE
  audit_query TEXT;
  r RECORD;
BEGIN
  IF tg_tag = 'DROP TABLE'
  THEN
    FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() 
    LOOP
      INSERT INTO ddl_history (ddl_date, ddl_tag, object_name) 
      	     VALUES (statement_timestamp(), tg_tag, r.object_identity);
    END LOOP;
  END IF;
END;
$$ LANGUAGE plpgsql;

4,选项标签

pgadmin4树节点增删查_第9张图片

5,点击保存

pg模板:

{% set is_columns = [] %}
{% set exclude_quoting = ['search_path'] %}
{% if data %}
CREATE{% if add_replace_clause %} OR REPLACE{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.proargnames %}{{data.proargnames}}{% endif %})
    RETURNS{% if data.proretset and data.prorettypename.startswith('SETOF ') %} {{ data.prorettypename }}{% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}

    LANGUAGE {{ data.lanname|qtLiteral(conn) }}
{% if data.procost %}
    COST {{data.procost}}
{% endif %}
    {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %}{% endif %}{% if data.proleakproof %} LEAKPROOF{% else %} NOT LEAKPROOF{% endif %}
{% if data.proisstrict %} STRICT{% endif %}
{% if data.prosecdef %} SECURITY DEFINER{% endif %}
{% if data.proiswindow %} WINDOW{% endif %}
{% if data.prorows and (data.prorows | int) > 0 %}

    ROWS {{data.prorows}}{% endif -%}{% if data.variables %}{% for v in data.variables %}

    SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
{% endif %}

AS {% if data.lanname == 'c' %}
{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
{% else %}
$BODY${{ data.prosrc }}$BODY${% endif -%};
{% if data.funcowner %}

ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
    OWNER TO {{ conn|qtIdent(data.funcowner) }};
{% endif -%}
{% if data.acl %}
{% for p in data.acl %}

{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args)}}
{% endfor %}{% endif %}
{% if data.revoke_all %}

{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
{% endif %}
{% if data.description %}

COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
    IS {{ data.description|qtLiteral(conn)  }};
{% endif -%}
{% if data.seclabels %}
{% for r in data.seclabels %}
{% if r.label and r.provider %}

{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args) }}
{% endif %}
{% endfor %}
{% endif -%}

{% endif %}

以上实际执行:

CREATE FUNCTION public.log_ddl_drop()
    RETURNS trigger
    LANGUAGE 'plpgsql'
     NOT LEAKPROOF
AS $BODY$DECLARE
  audit_query TEXT;
  r RECORD;
BEGIN
  IF tg_tag = 'DROP TABLE'
  THEN
    FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() 
    LOOP
      INSERT INTO ddl_history (ddl_date, ddl_tag, object_name) 
      	     VALUES (statement_timestamp(), tg_tag, r.object_identity);
    END LOOP;
  END IF;
END;
$BODY$;

ALTER FUNCTION public.log_ddl_drop()
    OWNER TO postgres;

(三)属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
fnid=24600

pg模板:

SELECT
    pr.oid, pr.xmin, pr.proiswindow, pr.prosrc, pr.prosrc AS prosrc_c,
    pr.pronamespace, pr.prolang, pr.procost, pr.prorows,
    pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile,
    pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
    pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
    typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
    pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
    pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
    FROM
        pg_catalog.pg_seclabel sl1
    WHERE
        sl1.objoid=pr.oid) AS seclabels
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
WHERE
    proisagg = FALSE
    AND typname IN ('trigger', 'event_trigger')
    AND lanname NOT IN ('edbspl', 'sql', 'internal')
{% if fnid %}
    AND pr.oid = {{fnid}}::oid
{% else %}
    AND pronamespace = {{scid}}::oid
{% endif %}
ORDER BY
    proname;

实际执行:

SELECT
    pr.oid, pr.xmin,
    CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
    pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
    pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
    pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
    pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
    typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
    pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
    pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
    FROM
        pg_catalog.pg_seclabel sl1
    WHERE
        sl1.objoid=pr.oid) AS seclabels
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
WHERE
    pr.prokind IN ('f', 'w')
    AND typname IN ('trigger', 'event_trigger')
    AND lanname NOT IN ('edbspl', 'sql', 'internal')
    AND pr.oid = 24600::oid
ORDER BY
    proname;

(四)删除

请求参数:

gid=1
sid=1
did=13799
scid=2200
fnid=24601

pg模板:

{% if scid and fnid %}
SELECT
    pr.proname as name, '(' || COALESCE(pg_catalog
    .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
    nspname
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
WHERE
    proisagg = FALSE
    AND pronamespace = {{scid}}::oid
    AND typname IN ('trigger', 'event_trigger')
    AND pr.oid = {{fnid}};
{% endif %}

{% if name %}
DROP FUNCTION {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
{% endif %}

实际执行:

SELECT
    pr.proname as name, '(' || COALESCE(pg_catalog
    .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
    nspname
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
WHERE
    pr.prokind IN ('f', 'w')
    AND pronamespace = 2200::oid
    AND typname IN ('trigger', 'event_trigger')
    AND pr.oid = 24601;

DROP FUNCTION public.log_ddl_drop();

六,扩展 Extension

(一)查询

在这里插入图片描述
实际执行:

SELECT
    x.oid, pg_catalog.pg_get_userbyid(extowner) AS owner,
    x.extname AS name, n.nspname AS schema,
    x.extrelocatable AS relocatable, x.extversion AS version,
    e.comment
FROM
    pg_catalog.pg_extension x
    LEFT JOIN pg_catalog.pg_namespace n ON x.extnamespace=n.oid
    JOIN pg_catalog.pg_available_extensions() e(name, default_version, comment) ON x.extname=e.name ORDER BY x.extname

(二)创建

1,general标签

pgadmin4树节点增删查_第10张图片

(1)查询“名称”

SELECT
    a.name, a.installed_version,
    pg_catalog.array_agg(av.version) as version,
    pg_catalog.array_agg(av.schema) as schema,
    pg_catalog.array_agg(av.superuser) as superuser,
    pg_catalog.array_agg(av.relocatable) as relocatable
FROM
    pg_catalog.pg_available_extensions a
    LEFT JOIN pg_catalog.pg_available_extension_versions av ON (a.name = av.name)
GROUP BY a.name, a.installed_version
ORDER BY a.name

2,定义标签

(1)查询“版本”

版本与名称对应。
pgadmin4树节点增删查_第11张图片

3,点击保存

请求参数:

gid=1
sid=1
did=13799
data={'name': 'postgres_fdw', 'version': '1.1', 'schema': 'public', 'relocatable': False, 'is_sys_obj': False, 'comment': None}

pg模板:

{#=========================Create new extension======================#}
{#===Generates comments and code for SQL tab===#}
{% if display_comments %}
-- Extension: {{ conn|qtIdent(data.name) }}

-- DROP EXTENSION {{ conn|qtIdent(data.name) }};

{% endif %}
{% if data.name %}
CREATE EXTENSION{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.name) }}{% if data.schema == '' and data.version == '' %};{% endif %}
{% if data.schema %}

    SCHEMA {{ conn|qtIdent(data.schema) }}{% if data.version == '' %};{% endif %}
{% endif %}
{% if data.version %}

    VERSION {{ conn|qtIdent(data.version) }};
{% endif %}
{% endif %}

实际执行:

CREATE EXTENSION amcheck
    SCHEMA public
    VERSION "1.3";

(三)属性

请求参数:

data={'name': 'postgres_fdw', 'version': '1.1', 'schema': 'public', 'relocatable': False, 'is_sys_obj': False, 'comment': None}
或
gid=1
sid=1
eid=42606

pg模板:

{#===================Fetch properties of each extension by name or oid===================#}
SELECT
    x.oid, pg_catalog.pg_get_userbyid(extowner) AS owner,
    x.extname AS name, n.nspname AS schema,
    x.extrelocatable AS relocatable, x.extversion AS version,
    e.comment
FROM
    pg_catalog.pg_extension x
    LEFT JOIN pg_catalog.pg_namespace n ON x.extnamespace=n.oid
    JOIN pg_catalog.pg_available_extensions() e(name, default_version, comment) ON x.extname=e.name
{%- if eid %}
 WHERE x.oid = {{eid}}::oid
{% elif ename %}
 WHERE x.extname = {{ename|qtLiteral(conn)}}::text
{% else %}
 ORDER BY x.extname
{% endif %}

实际执行:

SELECT
    x.oid, pg_catalog.pg_get_userbyid(extowner) AS owner,
    x.extname AS name, n.nspname AS schema,
    x.extrelocatable AS relocatable, x.extversion AS version,
    e.comment
FROM
    pg_catalog.pg_extension x
    LEFT JOIN pg_catalog.pg_namespace n ON x.extnamespace=n.oid
    JOIN pg_catalog.pg_available_extensions() e(name, default_version, comment) ON x.extname=e.name WHERE x.oid = 24606::oid

(四)删除

请求参数:

gid=1
sid=1
did=13799
eid=24606

pg模板:

{#============================Drop/Cascade Extension by name=========================#}
{% if eid %}
SELECT x.extname from pg_catalog.pg_extension x
    WHERE x.oid = {{ eid }}::oid
{% endif %}
{% if name %}
DROP EXTENSION IF EXISTS {{ conn|qtIdent(name) }}{% if cascade %} CASCADE{% endif %};
{% endif %}

实际执行:

SELECT x.extname from pg_catalog.pg_extension x
    WHERE x.oid = 24606::oid

DROP EXTENSION IF EXISTS postgres_fdw;

七,外部表 Foreign Table

(一)查询

请求参数:

gid=1
sid=1
did=13799
scid=2200

pg模板:

SELECT
    c.oid, c.relname AS name, pg_catalog.pg_get_userbyid(relowner) AS owner,
    ftoptions, nspname as basensp, description
FROM
    pg_catalog.pg_class c
JOIN
    pg_catalog.pg_foreign_table ft ON c.oid=ft.ftrelid
LEFT OUTER JOIN
    pg_catalog.pg_namespace nsp ON (nsp.oid=c.relnamespace)
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_class'::regclass)
WHERE
{% if scid %}
    c.relnamespace = {{scid}}::oid
{% elif foid %}
    c.oid = {{foid}}::oid
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY c.relname;

实际执行:

SELECT
    c.oid, c.relname AS name, pg_catalog.pg_get_userbyid(relowner) AS owner,
    ftoptions, nspname as basensp, description
FROM
    pg_catalog.pg_class c
JOIN
    pg_catalog.pg_foreign_table ft ON c.oid=ft.ftrelid
LEFT OUTER JOIN
    pg_catalog.pg_namespace nsp ON (nsp.oid=c.relnamespace)
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_class'::regclass)
WHERE
    c.relnamespace = 2200::oid
ORDER BY c.relname;

(二)创建

1,常规标签

pgadmin4树节点增删查_第12张图片

2,定义标签

pgadmin4树节点增删查_第13张图片查询“外部服务器”:

在这里插入代码片

3,列标签

pgadmin4树节点增删查_第14张图片

4,约束标签

pgadmin4树节点增删查_第15张图片

5,选项标签

pgadmin4树节点增删查_第16张图片

6,安全标签

pgadmin4树节点增删查_第17张图片

7,点击保存

pgadmin4树节点增删查_第18张图片
请求参数:

gid=1
sid=1
did=13799
scid=2200
name="ft1"

pg模板:

在这里插入代码片

实际执行:

CREATE FOREIGN TABLE public.ft1(
    port integer NULL
)
    SERVER server1;

ALTER FOREIGN TABLE public.ft1
    OWNER TO postgres;

SELECT
    c.oid, bn.oid as scid
FROM
    pg_catalog.pg_class c
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=c.relnamespace
WHERE
    bn.nspname = 'public'
    AND c.relname='ft1';

(三)属性

(四)删除

八,外部数据封装器 Foreign Data Wrappers

准备

(一)查询

在这里插入图片描述
实际执行:

SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
ORDER BY fdwname

(二)创建

pgadmin4树节点增删查_第19张图片

1,general标签

pgadmin4树节点增删查_第20张图片

2,定义标签

pgadmin4树节点增删查_第21张图片

3,选项标签

pgadmin4树节点增删查_第22张图片

4,点击保存

请求参数:

gid=1
sid=1
did=13799
data={'name': 'test1', 'fdwowner': 'postgres', 'fdwvalue': 'public.postgres_fdw_validator', 'fdwhan': 'public.postgres_fdw_handler', 'fdwacl': []}

pg模板:

{# ============= Create foreign data wrapper ============= #}
{% if data.name %}
CREATE FOREIGN DATA WRAPPER {{ conn|qtIdent(data.name) }}{% if data.fdwvalue %}

    VALIDATOR {{ data.fdwvalue }}{%endif%}{% if data.fdwhan %}

    HANDLER {{ data.fdwhan }}{% endif %}{% if data.fdwoptions %}

{% if is_valid_options %}
    OPTIONS ({% for variable in data.fdwoptions %}{% if loop.index != 1 %}, {% endif %}
{{ conn|qtIdent(variable.fdwoption) }} {{ variable.fdwvalue|qtLiteral(conn) }}{% endfor %}){% endif %}{% endif %};

{# ============= Set the owner for foreign data wrapper ============= #}
{% if data.fdwowner %}
ALTER FOREIGN DATA WRAPPER {{ conn|qtIdent(data.name) }}
    OWNER TO {{ conn|qtIdent(data.fdwowner) }};

{% endif %}
{# ============= Comment on of foreign data wrapper object ============= #}
{% if data.description %}
COMMENT ON FOREIGN DATA WRAPPER {{ conn|qtIdent(data.name) }}
    IS {{ data.description|qtLiteral(conn) }};

{% endif %}
{# ============= Create ACL for foreign data wrapper ============= #}
{% if data.fdwacl %}
{% for priv in data.fdwacl %}
GRANT {{ privs|join(', ') }} ON 'FOREIGN DATA WRAPPER' data.name TO priv.grantee;
{% endfor %}
{% endif %}
{% endif %}

实际执行:

CREATE FOREIGN DATA WRAPPER test1
    VALIDATOR public.postgres_fdw_validator
    HANDLER public.postgres_fdw_handler;

ALTER FOREIGN DATA WRAPPER test1
    OWNER TO postgres;

(三)属性

请求参数:

data={'name': 'test1', 'fdwowner': 'postgres', 'fdwvalue': 'public.postgres_fdw_validator', 'fdwhan': 'public.postgres_fdw_handler', 'fdwacl': []}
或
gid=1
sid=1

pg模板:

{# ============= Get all the properties of foreign data wrapper ============= #}
SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
{% if fid %}
WHERE fdw.oid={{fid}}::oid
{% endif %}
{% if fname %}
WHERE fdw.fdwname={{ fname|qtLiteral(conn) }}::text
{% endif %}
{% if schema_diff %}
WHERE CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
    WHERE objid = fdw.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY fdwname

实际执行:

SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
WHERE fdw.fdwname='test1'::text
ORDER BY fdwname

(四)删除

请求参数:

gid=1
sid=1
did=13799
fid=24613
data={'fid':24613,'name':'test1','cascade':False}

pg模板:

{# ============= Get foreign data wrapper from fid ============= #}
{% if fid %}
SELECT fdwname as name from pg_catalog.pg_foreign_data_wrapper WHERE oid={{fid}}::oid;
{% endif %}
{# ============= Delete/Drop cascade foreign data wrapper ============= #}
{% if name %}
DROP FOREIGN DATA WRAPPER IF EXISTS {{ conn|qtIdent(name) }} {% if cascade %} CASCADE {% endif %};
{% endif %}

实际执行:

SELECT fdwname as name from pg_catalog.pg_foreign_data_wrapper WHERE oid=24613::oid;

DROP FOREIGN DATA WRAPPER IF EXISTS test1 ;

九,外部服务器

(一)查询

pgadmin4树节点增删查_第23张图片

请求参数:

gid=1
sid=1
did=13799

pg模板:

{# ============= Get all the properties of foreign data wrapper ============= #}
SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
{% if fid %}
WHERE fdw.oid={{fid}}::oid
{% endif %}
{% if fname %}
WHERE fdw.fdwname={{ fname|qtLiteral }}::text
{% endif %}
{% if schema_diff %}
WHERE CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
    WHERE objid = fdw.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY fdwname

实际执行:

SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
ORDER BY fdwname

(二)创建

1,general标签

pgadmin4树节点增删查_第24张图片

2,定义标签

pgadmin4树节点增删查_第25张图片
查询处理程序:

SELECT nspname, proname as fdwhan,
       pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(proname) AS schema_prefix_fdw_hand
FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace nsp ON nsp.oid=pronamespace
WHERE pronargs=0 AND prorettype=3115;

查询验证其:

SELECT nspname, proname as fdwvalue,
       pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(proname) AS schema_prefix_fdw_val
FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace nsp ON nsp.oid=pronamespace
WHERE proargtypes[0]=1009 AND proargtypes[1]=26;

3,选项标签

pgadmin4树节点增删查_第26张图片

4,安全标签

pgadmin4树节点增删查_第27张图片

5,点击保存

请求参数:

gid=1
sid=1
did=13799
data={'name': 'test1', 'fdwowner': 'postgres', 'fdwvalue': 'public.postgres_fdw_validator', 'fdwhan': 'public.postgres_fdw_handler', 'fdwacl': [], 'fdwoptions': [{'fdwoption': 'host', 'fdwvalue': '172.28.79.200'}, {'fdwoption': 'port', 'fdwvalue': '5432'}, {'fdwoption': 'dbname', 'fdwvalue': 'test'}]}

pg模板:

{% if data.name %}
CREATE
FOREIGN DATA WRAPPER {{ conn|qtIdent(data.name) }}{% if data.fdwvalue %}

    VALIDATOR {{ data.fdwvalue }}{%endif%}{% if data.fdwhan %}

    HANDLER {{ data.fdwhan }}{% endif %}{% if data.fdwoptions %}

{% if is_valid_options %}
    OPTIONS ({% for variable in data.fdwoptions %}{% if loop.index != 1 %}, {% endif %}
{{ conn|qtIdent(variable.fdwoption) }} {{ variable.fdwvalue|qtLiteral }}{% endfor %}){% endif %}{% endif %};

{# ============= Set the owner for foreign data wrapper ============= #}
{% if data.fdwowner %}
ALTER
FOREIGN DATA WRAPPER {{ conn|qtIdent(data.name) }}
    OWNER TO {{ conn|qtIdent(data.fdwowner) }};

{% endif %}
{# ============= Comment on of foreign data wrapper object ============= #}
{% if data.description %}
COMMENT ON FOREIGN DATA WRAPPER {{ conn|qtIdent(data.name) }}
    IS {{ data.description|qtLiteral }};

{% endif %}
{# ============= Create
ACL for foreign data wrapper ============= #}
{% if data.fdwacl %}
{% for priv in data.fdwacl %}
{% if priv.without_grant %}
GRANT {{ privs|join(', ') }} ON 'FOREIGN DATA WRAPPER' data.name TO priv.grantee;
{% endif %}
{% if priv.with_grant %}
GRANT {{ with_grant_privs|join(', ') }} ON 'FOREIGN DATA WRAPPER' data.name TO priv.grantee WITH GRANT OPTION;
{% endif %}
{% endif %}
{% endif %}

实际执行:

CREATE FOREIGN DATA WRAPPER test1
    VALIDATOR public.postgres_fdw_validator
    HANDLER public.postgres_fdw_handler
    OPTIONS (host '172.28.79.200', port '5432', dbname 'test');

ALTER FOREIGN DATA WRAPPER test1
    OWNER TO postgres;

(三)属性

请求参数:

gid=1
sid=1
did=13799
fid=16379

pg模板:

{# ============= Get all the properties of foreign data wrapper ============= #}
SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
{% if fid %}
WHERE fdw.oid={{fid}}::oid
{% endif %}
{% if fname %}
WHERE fdw.fdwname={{ fname|qtLiteral }}::text
{% endif %}
{% if schema_diff %}
WHERE CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
    WHERE objid = fdw.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY fdwname

实际执行:

SELECT fdw.oid, fdwname as name, fdwhandler, fdwvalidator, description,
    fdwoptions AS fdwoptions, pg_catalog.pg_get_userbyid(fdwowner) as fdwowner, pg_catalog.array_to_string(fdwacl::text[], ', ') as acl,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vp.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vp_nsp.nspname)||'.'||pg_catalog.quote_ident(vp.proname)
    END fdwvalue,
    CASE
    -- EPAS in redwood mode, concatenation of a string with NULL results as the original string
    WHEN vh.proname IS NULL THEN NULL
    ELSE pg_catalog.quote_ident(vh_nsp.nspname)||'.'||pg_catalog.quote_ident(vh.proname)
    END fdwhan
FROM pg_catalog.pg_foreign_data_wrapper fdw
    LEFT OUTER JOIN pg_catalog.pg_proc vh on vh.oid=fdwhandler
    LEFT OUTER JOIN pg_catalog.pg_proc vp on vp.oid=fdwvalidator
    LEFT OUTER JOIN pg_catalog.pg_namespace vh_nsp ON vh_nsp.oid=vh.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_namespace vp_nsp ON vp_nsp.oid=vp.pronamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=fdw.oid AND des.objsubid=0 AND des.classoid='pg_foreign_data_wrapper'::regclass)
WHERE fdw.oid=16397::oid
ORDER BY fdwname

(四)删除

请求参数:

gid=1
sid=1
did=13799
fid=16403
name="test1"

pg模板:

{# ============= Get foreign data wrapper from fid ============= #}
{% if fid %}
SELECT fdwname as name from pg_catalog.pg_foreign_data_wrapper WHERE oid={{fid}}::oid;
{% endif %}
{# ============= Delete/Drop cascade foreign data wrapper ============= #}
{% if name %}
DROP FOREIGN DATA WRAPPER IF EXISTS {{ conn|qtIdent(name) }} {% if cascade %} CASCADE {% endif %};
{% endif %}

实际执行:

DROP FOREIGN DATA WRAPPER IF EXISTS test1 ;

十,用户映射

(一)查询

pgadmin4树节点增删查_第28张图片

请求参数:

gid=1
sid=1
did=13799
fid=16397
fsid=16401

实际执行:

SELECT u.umid AS oid, u.usename AS name, fs.srvname, u.srvid AS fsid, umoptions AS umoptions, fs.srvfdw AS fdwid
FROM pg_catalog.pg_user_mappings u
LEFT JOIN pg_catalog.pg_foreign_server fs ON fs.oid = u.srvid
 WHERE u.srvid = 16401::oid  ORDER BY 2;

(二)创建

1,常规标签

pgadmin4树节点增删查_第29张图片

2,选项标签

pgadmin4树节点增删查_第30张图片

3,点击保存

请求参数:

gid=1
sid=1
did=13799
data={"name":"postgres",}

pg模板:

{# ============= Create of user mapping for server ============= #}
{% if data and fdwdata %}
CREATE USER MAPPING FOR {% if data.name == "CURRENT_USER" or data.name == "PUBLIC" %}{{ data.name }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} SERVER {{ conn|qtIdent(fdwdata.name) }}{%endif%}{% if data.umoptions %}{% if is_valid_options %}

    OPTIONS ({% for variable in data.umoptions %}{% if loop.index != 1 %}, {% endif %}
{{ conn|qtIdent(variable.umoption) }} {{ variable.umvalue|qtLiteral }}{% endfor %}){% endif %}{% endif %};

实际执行:

CREATE USER MAPPING FOR postgres SERVER server1
    OPTIONS ("user" 'postgres', password 'postgres');

(三)属性

请求参数:

gid=1
sid=1
did=13799
fid=16397
fsid=16401

pg模板:

{# ============= Get the properties of user mapping ============= #}
{% if fserid %}
SELECT srv.oid as fsrvid, srvname as name
FROM pg_catalog.pg_foreign_server srv
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=srv.oid AND des.objsubid=0 AND des.classoid='pg_foreign_server'::regclass)
WHERE srv.oid = {{fserid}}::oid
{% elif fsid or umid %}
SELECT u.umid AS oid, u.usename AS name, fs.srvname, u.srvid AS fsid, umoptions AS umoptions, fs.srvfdw AS fdwid
FROM pg_catalog.pg_user_mappings u
LEFT JOIN pg_catalog.pg_foreign_server fs ON fs.oid = u.srvid
{% if fsid %} WHERE u.srvid = {{fsid}}::oid {% endif %} {% if umid %} WHERE u.umid= {{umid}}::oid {% endif %}
ORDER BY 2;
{% else %}
SELECT u.umid AS oid, u.usename AS name, u.srvid AS fsid, pg_catalog.array_to_string(u.umoptions, ',') AS umoptions, fs.srvfdw AS fdwid
FROM pg_catalog.pg_user_mappings u
LEFT JOIN pg_catalog.pg_foreign_server fs ON fs.oid = u.srvid
{% if schema_diff %}
WHERE CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
    WHERE objid = u.umid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY 2;
{% endif %}

实际执行:

SELECT u.umid AS oid, u.usename AS name, fs.srvname, u.srvid AS fsid, umoptions AS umoptions, fs.srvfdw AS fdwid
FROM pg_catalog.pg_user_mappings u
LEFT JOIN pg_catalog.pg_foreign_server fs ON fs.oid = u.srvid
  WHERE u.umid= 16404::oid ORDER BY 2;

(四)删除

请求参数:

gid=1
sid=1
did=13799
fid=16397
fsid=16401
umid=16404

pg模板:

{# ============= Get the foreing server name from id ============= #}
{% if fsid %}
SELECT srvname as name FROM pg_catalog.pg_foreign_server srv LEFT OUTER JOIN pg_catalog.pg_foreign_data_wrapper fdw on fdw.oid=srvfdw
    WHERE srv.oid={{fsid}}::oid;
{% endif %}
{# ============= Drop/Delete cascade user mapping ============= #}
{% if name and data %}
DROP USER MAPPING FOR {% if data.name == "CURRENT_USER" or data.name == "PUBLIC" %}{{ data.name }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} SERVER {{ conn|qtIdent(name) }};
{% endif %}

实际执行:

SELECT srvname as name FROM pg_catalog.pg_foreign_server srv LEFT OUTER JOIN pg_catalog.pg_foreign_data_wrapper fdw on fdw.oid=srvfdw
    WHERE srv.oid=16401::oid;

DROP USER MAPPING FOR postgres SERVER server1;

十一,语言 Language

(一)查询

在这里插入图片描述
请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(二)创建

1,general标签

pgadmin4树节点增删查_第31张图片

2,定义标签

pgadmin4树节点增删查_第32张图片

3,安全标签

pgadmin4树节点增删查_第33张图片

4,点击保存

pgadmin4树节点增删查_第34张图片

请求参数:

gid=1
sid=1
did=13799
data={'name': 'test', 'lanowner': 'postgres', 'lanacl': [], 'seclabels': [], 'trusted': True, 'lanproc': 'plpgsql_call_handler', 'laninl': 'btint2sortsupport', 'lanval': 'pg_stat_reset_single_function_counters'}

pg模板:

{# ============= CREATE LANGUAGE Query ============= #}
{% if data.is_template %}
CREATE{% if add_replace_clause %} OR REPLACE{% endif %} LANGUAGE {{ conn|qtIdent(data.name) }};
{% else %}
CREATE{% if add_replace_clause %} OR REPLACE{% endif %}{% if data.trusted %} TRUSTED{% endif %} PROCEDURAL LANGUAGE {{ conn|qtIdent(data.name) }}
{% if data.lanproc %}
    HANDLER {{ conn|qtIdent(data.lanproc) }}
{% endif %}
{% if data.laninl %}
    INLINE {{ conn|qtIdent(data.laninl) }}
{% endif %}
{% if data.lanval %}
    VALIDATOR {{ conn|qtIdent(data.lanval) }}
{% endif %};
{% endif %}
{# ============= Set the owner for language ============= #}
{% if data.lanowner %}
ALTER LANGUAGE {{ conn|qtIdent(data.name) }}
    OWNER TO {{ conn|qtIdent(data.lanowner) }};
{% endif %}
{# ============= Comment on of language object ============= #}
{% if data.description %}
COMMENT ON LANGUAGE {{ conn|qtIdent(data.name) }}
    IS {{ data.description|qtLiteral(conn) }};
{% endif %}

实际执行:

'CREATE TRUSTED PROCEDURAL LANGUAGE test
    HANDLER plpgsql_call_handler
    INLINE btint2sortsupport
    VALIDATOR pg_stat_reset_single_function_counters
;
ALTER LANGUAGE test
    OWNER TO postgres;

(三)属性

请求参数:

gid=1
sid=1
did=13799
lid=13789data={'name': 'test', 'lanowner': 'postgres', 'lanacl': [], 'seclabels': [], 'trusted': True, 'lanproc': 'plpgsql_call_handler', 'laninl': 'btint2sortsupport', 'lanval': 'pg_stat_reset_single_function_counters'}

pg模板:

SELECT
    lan.oid as oid, lanname as name, lanpltrusted as trusted,
    pg_catalog.array_to_string(lanacl::text[], ', ') as acl, hp.proname as lanproc,
    vp.proname as lanval, description,
    pg_catalog.pg_get_userbyid(lan.lanowner) as lanowner, ip.proname as laninl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabel sl1 WHERE sl1.objoid=lan.oid) AS seclabels
FROM
    pg_catalog.pg_language lan JOIN pg_catalog.pg_proc hp ON hp.oid=lanplcallfoid
    LEFT OUTER JOIN pg_catalog.pg_proc ip ON ip.oid=laninline
    LEFT OUTER JOIN pg_catalog.pg_proc vp ON vp.oid=lanvalidator
    LEFT OUTER JOIN pg_catalog.pg_description des
        ON (
            des.objoid=lan.oid AND des.objsubid=0 AND
            des.classoid='pg_language'::regclass
        )
WHERE lanispl IS TRUE
{% if lid %} AND
    lan.oid={{lid}}::oid
{% endif %}
{% if lanname %} AND
    lanname={{ lanname|qtLiteral(conn) }}::text
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = lan.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY lanname

实际执行:

SELECT
    lan.oid as oid, lanname as name, lanpltrusted as trusted,
    pg_catalog.array_to_string(lanacl::text[], ', ') as acl, hp.proname as lanproc,
    vp.proname as lanval, description,
    pg_catalog.pg_get_userbyid(lan.lanowner) as lanowner, ip.proname as laninl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabel sl1 WHERE sl1.objoid=lan.oid) AS seclabels
FROM
    pg_catalog.pg_language lan JOIN pg_catalog.pg_proc hp ON hp.oid=lanplcallfoid
    LEFT OUTER JOIN pg_catalog.pg_proc ip ON ip.oid=laninline
    LEFT OUTER JOIN pg_catalog.pg_proc vp ON vp.oid=lanvalidator
    LEFT OUTER JOIN pg_catalog.pg_description des
        ON (
            des.objoid=lan.oid AND des.objsubid=0 AND
            des.classoid='pg_language'::regclass
        )
WHERE lanispl IS TRUE
 AND
    lan.oid=13789::oid
ORDER BY lanname

(四)删除

请求参数:

gid=1
sid=1
did=13799
lid=24615

pg模板:

{# ============= Get the language name using oid ============= #}
{% if lid %}
    SELECT lanname FROM pg_catalog.pg_language WHERE oid = {{lid}}::oid;
{% endif %}
{# ============= Drop the language ============= #}
{% if lname %}
DROP LANGUAGE IF EXISTS {{ conn|qtIdent(lname) }}{% if cascade %} CASCADE{% endif%};
{% endif %}

实际执行:

SELECT lanname FROM pg_catalog.pg_language WHERE oid = 24615::oid;

DROP LANGUAGE IF EXISTS test;

十一,函数

(一)查询

请求参数:

gid=1
sid=1
did=13799
scid=2200

实际执行:

SELECT
    pr.oid, pr.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
    lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
WHERE
   pr.prokind IN ('f', 'w')
    AND pronamespace = 2200::oid
    AND typname NOT IN ('trigger', 'event_trigger')
ORDER BY
    proname;

(二)创建

1,常规标签

pgadmin4树节点增删查_第35张图片

2,定义标签

在这里插入图片描述

3,代码标签

pgadmin4树节点增删查_第36张图片

4,选项标签

pgadmin4树节点增删查_第37张图片

5,参数标签

pgadmin4树节点增删查_第38张图片

6,安全标签

pgadmin4树节点增删查_第39张图片

7,点击保存

请求参数:


pg模板:

{% import 'macros/functions/variable.macros' as VARIABLE %}
{% set is_columns = [] %}
{% set exclude_quoting = ['search_path'] %}
{% if data %}
{% if query_for == 'sql_panel' and func_def is defined %}
CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
{% else %}
CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
{% if not loop.last %}, {% endif %}
{% endfor %}
{% endif -%}
)
{% endif %}
    RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}

    LANGUAGE {{ data.lanname|qtLiteral(conn) }}
{% if data.procost %}
    COST {{data.procost}}
{% endif %}
    {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
{% if data.proisstrict %}STRICT {% endif %}
{% if data.prosecdef %}SECURITY DEFINER {% endif %}
{% if data.proiswindow %}WINDOW {% endif %}
{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
{% if data.prorows and (data.prorows | int) > 0 %}

    ROWS {{data.prorows}}
{% endif %}
{% if data.prosupportfunc %}
    SUPPORT {{ data.prosupportfunc }}
{% endif -%}
{% if data.variables %}{% for v in data.variables %}

    SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
{% endif %}

{% if data.is_pure_sql %}{{ data.prosrc }}
{% else %}
AS {% if data.lanname == 'c' %}
{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
{% else %}
$BODY${{ data.prosrc }}$BODY${% endif -%};
{% endif -%}
{% if data.funcowner %}

ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
    OWNER TO {{ conn|qtIdent(data.funcowner) }};
{% endif -%}
{% if data.acl %}
{% for p in data.acl %}

{% if p.without_grant %}
GRANT {{ p.without_grant|join(', ') }} ON "FUNCTION" {{ conn|qtIdent(data.pronamespace, data.name) }}(data.func_args_without) TO p.grantee;
{% endif %}
{% if p.with_grant %}
GRANT {{ p.with_grant|join(', ') }} ON "FUNCTION" {{ conn|qtIdent(data.pronamespace, data.name) }}(data.func_args_without) TO p.grantee WITH GRANT OPTION;
{% endif %}
{% endfor %}{% endif %}
{% if data.revoke_all %}

REVOKE ALL ON "FUNCTION" {{ conn|qtIdent(data.pronamespace, data.name) }}(data.func_args_without) FROM "PUBLIC";
{% endif %}
{% if data.description %}

COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
    IS {{ data.description|qtLiteral(conn)  }};
{% endif -%}
{% if data.seclabels %}
{% for r in data.seclabels %}
{% if r.label and r.provider %}
SECURITY LABEL{% if r.provider and r.provider != '' %} FOR {{ conn|qtIdent(r.provider) }}{% endif %} ON 'FUNCTION' {{ conn|qtIdent(data.pronamespace, data.name) }}(data.func_args_without) IS {{ r.label|qtLiteral(conn) }};
{% endif %}
{% endfor %}
{% endif -%}

{% endif %}

实际执行:

CREATE FUNCTION public.get_user_age(birthdate integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    
AS $BODY$
DECLARE
  age integer;
BEGIN
  age := EXTRACT(YEAR FROM age(birthdate));
  RETURN age;
END;
$BODY$;

ALTER FUNCTION public.get_user_age(integer)
    OWNER TO postgres;

(三)属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
fnid=24626

pg模板:

SELECT
    pr.oid, pr.xmin,
    CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
    pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
    pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
    pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
    pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
    typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
    pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
    pg_catalog.pg_get_function_sqlbody(pr.oid) AS prosrc_sql,
    CASE WHEN pr.prosqlbody IS NOT NULL THEN true ELSE false END as is_pure_sql,
    pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
    CASE WHEN prosupport = 0::oid THEN ''
    ELSE (
        SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfunctions
          FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
              WHERE p.pronamespace = n.oid
              AND p.oid = pr.prosupport::OID
    ) END AS prosupportfunc,
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
    FROM
        pg_catalog.pg_seclabel sl1
    WHERE
        sl1.objoid=pr.oid) AS seclabels
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
WHERE
    pr.prokind IN ('f', 'w')
    AND typname NOT IN ('trigger', 'event_trigger')
{% if fnid %}
    AND pr.oid = {{fnid}}::oid
{% else %}
    AND pronamespace = {{scid}}::oid
{% endif %}
ORDER BY
    proname;

实际执行:

SELECT
    pr.oid, pr.xmin,
    CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
    pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
    pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
    pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
    pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
    typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
    pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
    pg_catalog.pg_get_function_sqlbody(pr.oid) AS prosrc_sql,
    CASE WHEN pr.prosqlbody IS NOT NULL THEN true ELSE false END as is_pure_sql,
    pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
    CASE WHEN prosupport = 0::oid THEN ''
    ELSE (
        SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfunctions
          FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
              WHERE p.pronamespace = n.oid
              AND p.oid = pr.prosupport::OID
    ) END AS prosupportfunc,
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
    FROM
        pg_catalog.pg_seclabel sl1
    WHERE
        sl1.objoid=pr.oid) AS seclabels
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
JOIN
    pg_catalog.pg_language lng ON lng.oid=prolang
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
WHERE
    pr.prokind IN ('f', 'w')
    AND typname NOT IN ('trigger', 'event_trigger')
    AND pr.oid = 24626::oid
ORDER BY
    proname;

查询安全标签内容:

SELECT
    COALESCE(gt.rolname, 'PUBLIC') AS grantee,
    g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
    pg_catalog.array_agg(is_grantable) AS grantable
FROM
    (SELECT
        d.grantee, d.grantor, d.is_grantable,
        CASE d.privilege_type
        WHEN 'CONNECT' THEN 'c'
        WHEN 'CREATE' THEN 'C'
        WHEN 'DELETE' THEN 'd'
        WHEN 'EXECUTE' THEN 'X'
        WHEN 'INSERT' THEN 'a'
        WHEN 'REFERENCES' THEN 'x'
        WHEN 'SELECT' THEN 'r'
        WHEN 'TEMPORARY' THEN 'T'
        WHEN 'TRIGGER' THEN 't'
        WHEN 'TRUNCATE' THEN 'D'
        WHEN 'UPDATE' THEN 'w'
        WHEN 'USAGE' THEN 'U'
        ELSE 'UNKNOWN'
        END AS privilege_type
    FROM
        (SELECT
            (d).grantee AS grantee, (d).grantor AS grantor,
            (d).is_grantable AS is_grantable,
            (d).privilege_type AS privilege_type
        FROM
            (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
            WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
        ) d
    ) d
    LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
    LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
GROUP BY g.rolname, gt.rolname
ORDER BY grantee

(四)删除

请求参数:

gid=1
sid=1
did=13799
scid=2200
fnid=24626
data={'ids': [24626]}

pg模板:

{% if scid and fnid %}
SELECT
    pr.proname as name, '(' || COALESCE(pg_catalog
    .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
    nspname
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
WHERE
    proisagg = FALSE
    AND pronamespace = {{scid}}::oid
    AND typname NOT IN ('trigger', 'event_trigger')
    AND pr.oid = {{fnid}};
{% endif %}

{% if name %}
DROP FUNCTION IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
{% endif %}

实际执行:

SELECT
    pr.proname as name, '(' || COALESCE(pg_catalog
    .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
    nspname
FROM
    pg_catalog.pg_proc pr
JOIN
    pg_catalog.pg_type typ ON typ.oid=prorettype
JOIN
    pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
WHERE
    pr.prokind IN ('f', 'w')
    AND pronamespace = 2200::oid
    AND typname NOT IN ('trigger', 'event_trigger')
    AND pr.oid = 24626;

DROP FUNCTION IF EXISTS public.get_user_age(birthdate integer);

十二,视图

(一)查询

pgadmin4树节点增删查_第40张图片

  • 视图下的列、规则、触发器见表下的列、规则、触发器。

请求参数:

gid=1
sid=1
scid=2200

实际执行:

SELECT
    c.oid,
    c.relname AS name
FROM pg_catalog.pg_class c
WHERE
  c.relkind = 'v'
    AND c.relnamespace = 2200::oid
ORDER BY
    c.relname

(二)创建

1,常规标签

pgadmin4树节点增删查_第41张图片

2,定义标签

pgadmin4树节点增删查_第42张图片

3,代码标签

在这里插入图片描述

4,安全标签

pgadmin4树节点增删查_第43张图片

5,点击保存

请求参数:

gid=1
sid=1
did=13799
scid=2200
data={'definition': 'SELECT  *\n   FROM student\n   LEFT JOIN teacher \n   ON student.teacher_id = teacher.id;', 'name': 'student_view', 'owner': 'postgres', 'schema': 'public'}

pg模板:

{#============================Create new view=========================#}
{% if display_comments %}
-- View: {{ data.schema }}.{{ data.name }}

-- DROP VIEW {{ conn|qtIdent(data.schema, data.name) }};

{% endif %}
{% if data.name and data.schema and data.definition %}
CREATE{% if add_replace_clause %} OR REPLACE{% endif %} VIEW {{ conn|qtIdent(data.schema, data.name) }}
{% if ((data.check_option and data.check_option.lower() != 'no') or data.security_barrier) %}
WITH ({% if data.check_option and data.check_option.lower() != 'no' %}

  check_option={{ data.check_option }}{% endif %}{{ ',' if data.check_option and data.check_option.lower() != 'no' and data.security_barrier }}
{% if data.security_barrier %}
  security_barrier={{ data.security_barrier|lower }}
{% endif %}
){% endif %} AS
{{ data.definition.rstrip(';') }};
{% if data.owner and data.m_view is undefined %}

ALTER TABLE {{ conn|qtIdent(data.schema, data.name) }}
    OWNER TO {{ conn|qtIdent(data.owner) }};
{% endif %}
{% if data.comment %}
COMMENT ON VIEW {{ conn|qtIdent(data.schema, data.name) }}
    IS {{ data.comment|qtLiteral }};
{% endif %}
{% endif %}

实际执行:

CREATE VIEW public.student_view
 AS
SELECT  *
   FROM student
   LEFT JOIN teacher 
   ON student.teacher_id = teacher.id;

ALTER TABLE public.student_view
    OWNER TO postgres;

(三)属性

请求参数:

gid=1
sid=1
scid=2200
vid=24584

pg模板:

{# ========================== Fetch View Properties ========================= #}
{% if (vid and datlastsysoid) or scid %}
SELECT
    c.oid,
    c.xmin,
    c.relkind,
    description AS comment,
    (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
    c.relname AS name,
    c.reltablespace AS spcoid,
    nsp.nspname AS schema,
    c.relispopulated AS ispopulated,
    pg_catalog.pg_get_userbyid(c.relowner) AS owner,
    pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
    pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
    {# ===== Checks if it is system view ===== #}
    {% if vid and datlastsysoid %}
    CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
    {% endif %}
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
     FROM
        pg_catalog.pg_seclabels sl1
     WHERE
        sl1.objoid=c.oid AND sl1.objsubid=0
    ) AS seclabels,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
        FROM 'check_option=([a-z]*)') AS check_option,
    (substring(pg_catalog.array_to_string(c.reloptions, ',')
        FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier
FROM pg_catalog.pg_class c
LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
    WHERE ((c.relhasrules AND (EXISTS (
        SELECT
            r.rulename
        FROM
            pg_catalog.pg_rewrite r
        WHERE
            ((r.ev_class = c.oid)
                AND (bpchar(r.ev_type) = '1'::bpchar)) )))
            AND (c.relkind = 'v'::char)
          )
{% if (vid and datlastsysoid) %}
    AND c.oid = {{vid}}::oid
{% elif scid %}
    AND c.relnamespace = {{scid}}::oid
ORDER BY
    c.relname
{% endif %}

{% elif type == 'roles' %}
SELECT
    pr.rolname
FROM
    pg_catalog.pg_roles pr
WHERE
    pr.rolcanlogin
ORDER BY
    pr.rolname

{% elif type == 'schemas' %}
SELECT
    nsp.nspname
FROM
    pg_catalog.pg_namespace nsp
WHERE
    (nsp.nspname NOT LIKE E'pg\\_%'
        AND nsp.nspname != 'information_schema')
{% endif %}
  • 其中的 datlastsysoid 是 web/pgadmin/utils/constants.py 文件中配置的常量,数值为 16383

实际执行:

SELECT
    c.oid,
    c.xmin,
    c.relkind,
    description AS comment,
    (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
    c.relname AS name,
    c.reltablespace AS spcoid,
    nsp.nspname AS schema,
    c.relispopulated AS ispopulated,
    pg_catalog.pg_get_userbyid(c.relowner) AS owner,
    pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
    pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
            CASE WHEN 24584 <= 16383 THEN True ELSE False END AS system_view,
        (SELECT
        pg_catalog.array_agg(provider || '=' || label)
     FROM
        pg_catalog.pg_seclabels sl1
     WHERE
        sl1.objoid=c.oid AND sl1.objsubid=0
    ) AS seclabels,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
        FROM 'check_option=([a-z]*)') AS check_option,
    (substring(pg_catalog.array_to_string(c.reloptions, ',')
        FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier
FROM pg_catalog.pg_class c
LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
    WHERE ((c.relhasrules AND (EXISTS (
        SELECT
            r.rulename
        FROM
            pg_catalog.pg_rewrite r
        WHERE
            ((r.ev_class = c.oid)
                AND (bpchar(r.ev_type) = '1'::bpchar)) )))
            AND (c.relkind = 'v'::char)
          )
    AND c.oid = 24584::oid

(四)删除

请求参数:

gid=1
sid=1
scid=2200
vid=24584
data={'ids': [24584]}

pg模板:

{# ====================== Drop/Cascade view by name ===================== #}
{% if vid %}
SELECT
    c.relname AS name,
    nsp.nspname
FROM
    pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace nsp ON c.relnamespace = nsp.oid
WHERE
    c.relfilenode = {{ vid }};
{% elif (name and nspname) %}
DROP VIEW IF EXISTS {{ conn|qtIdent(nspname, name) }}{% if cascade %} CASCADE {% endif %};
{% endif %}

实际执行:根据vid查询name,再根据name删除视图

SELECT
    c.oid,
    c.xmin,
    c.relkind,
    description AS comment,
    (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
    c.relname AS name,
    c.reltablespace AS spcoid,
    nsp.nspname AS schema,
    c.relispopulated AS ispopulated,
    pg_catalog.pg_get_userbyid(c.relowner) AS owner,
    pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
    pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
            CASE WHEN 24584 <= 16383 THEN True ELSE False END AS system_view,
        (SELECT
        pg_catalog.array_agg(provider || '=' || label)
     FROM
        pg_catalog.pg_seclabels sl1
     WHERE
        sl1.objoid=c.oid AND sl1.objsubid=0
    ) AS seclabels,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
        FROM 'check_option=([a-z]*)') AS check_option,
    (substring(pg_catalog.array_to_string(c.reloptions, ',')
        FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier
FROM pg_catalog.pg_class c
LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
    WHERE ((c.relhasrules AND (EXISTS (
        SELECT
            r.rulename
        FROM
            pg_catalog.pg_rewrite r
        WHERE
            ((r.ev_class = c.oid)
                AND (bpchar(r.ev_type) = '1'::bpchar)) )))
            AND (c.relkind = 'v'::char)
          )
    AND c.oid = 24584::oid

DROP VIEW IF EXISTS public.student_view;

十三,物化视图

(一)查询

pgadmin4树节点增删查_第44张图片

  • 视图下的列、索引见表下的列、索引。

请求参数:

gid=1
sid=1
scid=2200

pg模板:

SELECT
    c.oid,
    c.relname AS name
FROM pg_catalog.pg_class c
WHERE
  c.relkind = 'm'
{% if (vid and datlastsysoid) %}
    AND c.oid = {{vid}}::oid
{% elif scid %}
    AND c.relnamespace = {{scid}}::oid
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY
    c.relname
{% endif %}

实际执行:

SELECT
    c.oid,
    c.relname AS name
FROM pg_catalog.pg_class c
WHERE
  c.relkind = 'm'
    AND c.relnamespace = 2200::oid
ORDER BY
    c.relname

(二)创建

1,常规标签

pgadmin4树节点增删查_第45张图片

2,定义标签

pgadmin4树节点增删查_第46张图片

3,存储标签

pgadmin4树节点增删查_第47张图片

4,参数标签

pgadmin4树节点增删查_第48张图片
pgadmin4树节点增删查_第49张图片

  • 未进行修改或选择。

5,安全标签

pgadmin4树节点增删查_第50张图片

5,点击保存

请求参数:

gid=1
sid=1
did=13799
scid=2200
data={'spcname': 'pg_default', 'toast_autovacuum_enabled': 'x', 'autovacuum_enabled': 'x', 'owner': 'postgres', 'schema': 'public', 'name': 'student_view_m', 'comment': '测试', 'definition': 'SELECT  *\n   FROM student\n   LEFT JOIN teacher \n   ON student.teacher_id = teacher.id;', 'with_data': True, 'fillfactor': '50'}

pg模板:

{# ===================== Create new view ===================== #}
{% if display_comments %}
-- View: {{ data.schema }}.{{ data.name }}

-- DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }};

{% endif %}
{% if data.name and data.schema and data.definition %}
CREATE MATERIALIZED VIEW{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
{% if(data.fillfactor or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') or data['vacuum_data']|length > 0) %}
{% set ns = namespace(add_comma=false) %}
WITH (
{% if data.fillfactor %}
    FILLFACTOR = {{ data.fillfactor }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
{% if ns.add_comma %},
{% endif %}
    autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f')  %}
{% if ns.add_comma %},
{% endif %}
    toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
{% for field in data['vacuum_data'] %}
{% if field.value is defined and field.value != '' and field.value != none %}
{% if ns.add_comma %},
{% endif %}    {{ field.name }} = {{ field.value|lower }}{% set ns.add_comma = true%}{% endif %}{% endfor %}
{{ '\n' }})
{% endif %}
{% if data.spcname %}TABLESPACE {{ data.spcname }}
{% endif %}AS
{{ data.definition.rstrip(';') }}
{% if data.with_data %}
WITH DATA;
{% else %}
WITH NO DATA;
{% endif %}
{% if data.owner %}

ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
    OWNER TO {{ conn|qtIdent(data.owner) }};
{% endif %}
{% if data.comment %}

COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }}
    IS {{ data.comment|qtLiteral }};
{% endif %}
{% endif %}

实际执行:

CREATE MATERIALIZED VIEW public.student_view_m
WITH (
    FILLFACTOR = 50
)
TABLESPACE pg_default
AS
SELECT  *
   FROM student
   LEFT JOIN teacher 
   ON student.teacher_id = teacher.id
WITH DATA;

ALTER TABLE IF EXISTS public.student_view_m
    OWNER TO postgres;

COMMENT ON MATERIALIZED VIEW public.student_view_m
    IS '测试';

(三)属性

请求参数:

gid=1
sid=1
scid=2200
vid=24588

pg模板:

{# ========================== Fetch Materialized View Properties ========================= #}
{% if (vid and datlastsysoid) or scid %}
SELECT
    c.oid,
    c.xmin,
    c.relname AS name,
    c.reltablespace AS spcoid,
    c.relispopulated AS with_data,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = {{ did }}::oid)
    END as spcname,
    c.relacl,
    nsp.nspname as schema,
    pg_catalog.pg_get_userbyid(c.relowner) AS owner,
    description AS comment,
    pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
    {# ============= Checks if it is system view ================ #}
    {% if vid and datlastsysoid %}
    CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
    {% endif %}
    pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'fillfactor=([0-9]*)') AS fillfactor,
    (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
    (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
    c.reloptions AS reloptions, tst.reloptions AS toast_reloptions,
    (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
FROM
    pg_catalog.pg_class c
LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
    WHERE ((c.relhasrules AND (EXISTS (
        SELECT
            r.rulename
        FROM
            pg_catalog.pg_rewrite r
        WHERE
            ((r.ev_class = c.oid)
                AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
            AND (c.relkind = 'm'::char)
          )
{% if (vid and datlastsysoid) %}
    AND c.oid = {{vid}}::oid
{% elif scid %}
    AND c.relnamespace = {{scid}}::oid
ORDER BY
    c.relname
{% endif %}

{% elif type == 'roles' %}
SELECT
    pr.rolname
FROM
    pg_catalog.pg_roles pr
WHERE
    pr.rolcanlogin
ORDER BY
    pr.rolname

{% elif type == 'schemas' %}
SELECT
    nsp.nspname
FROM
    pg_catalog.pg_namespace nsp
WHERE
    (nsp.nspname NOT LIKE E'pg\\_%'
        AND nsp.nspname != 'information_schema')
{% endif %}

  • 其中的 datlastsysoid 是 web/pgadmin/utils/constants.py 文件中配置的常量,数值为 16383

实际执行:

SELECT
    c.oid,
    c.xmin,
    c.relname AS name,
    c.reltablespace AS spcoid,
    c.relispopulated AS with_data,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    c.relacl,
    nsp.nspname as schema,
    pg_catalog.pg_get_userbyid(c.relowner) AS owner,
    description AS comment,
    pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
            CASE WHEN 24588 <= 16383 THEN True ELSE False END AS system_view,
        pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'fillfactor=([0-9]*)') AS fillfactor,
    (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
    (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
    c.reloptions AS reloptions, tst.reloptions AS toast_reloptions,
    (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
FROM
    pg_catalog.pg_class c
LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
    WHERE ((c.relhasrules AND (EXISTS (
        SELECT
            r.rulename
        FROM
            pg_catalog.pg_rewrite r
        WHERE
            ((r.ev_class = c.oid)
                AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
            AND (c.relkind = 'm'::char)
          )
    AND c.oid = 24588::oid

(四)删除

请求参数:

gid=1
sid=1
scid=2200
vid=24588
data = {'ids': 24588}

pg模板:

{# =================== Drop/Cascade materialized view by name ====================#}
{% if vid %}
SELECT
    c.relname As name,
    nsp.nspname
FROM
    pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace nsp ON c.relnamespace = nsp.oid
WHERE
    c.relfilenode = {{ vid }};
{% elif (name and nspname) %}
DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(nspname, name) }} {% if cascade %} CASCADE {% endif %};
{% endif %}

实际执行:

SELECT
    c.oid,
    c.xmin,
    c.relname AS name,
    c.reltablespace AS spcoid,
    c.relispopulated AS with_data,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    c.relacl,
    nsp.nspname as schema,
    pg_catalog.pg_get_userbyid(c.relowner) AS owner,
    description AS comment,
    pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
            CASE WHEN 24588 <= 16383 THEN True ELSE False END AS system_view,
        pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'fillfactor=([0-9]*)') AS fillfactor,
    (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
    substring(pg_catalog.array_to_string(c.reloptions, ',')
      FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
    (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
    substring(pg_catalog.array_to_string(tst.reloptions, ',')
      FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
    c.reloptions AS reloptions, tst.reloptions AS toast_reloptions,
    (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
FROM
    pg_catalog.pg_class c
LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
    WHERE ((c.relhasrules AND (EXISTS (
        SELECT
            r.rulename
        FROM
            pg_catalog.pg_rewrite r
        WHERE
            ((r.ev_class = c.oid)
                AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
            AND (c.relkind = 'm'::char)
          )
    AND c.oid = 24588::oid

DROP MATERIALIZED VIEW IF EXISTS public.student_view_m ;

十四,表

(一)查询

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(二)创建

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(三)属性

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(四)更新

源码——数据表的更新:

请求参数:

gid=1
sid=1
dis=13700
scid=2200
tid=25264
data={'name': 't0', 'oid': 25264}

(五)删除与级联删除

1,删除

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

2,级联删除

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(五)备份与恢复

查看这里:pgadmin4中的备份与恢复

(六)行总数

请求参数:

gid=1
sid=1
dis=13799
scid=2200
tid=24580
data={'name': 'student', 'schema': 'public'}

pg模板:

SELECT COUNT(*)::text FROM {{ conn|qtIdent(data.schema, data.name) }};

实际执行:

SELECT COUNT(*)::text FROM public.student;

十五,列

(一)查询

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(二)创建

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(三)属性

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

(四)删除

请求参数:

在这里插入代码片

pg模板:

在这里插入代码片

实际执行:

在这里插入代码片

十六,索引

第 11 章 索引

(一)查询

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500

pg模板:

SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name,
(SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description ELSE des.description END AS description
FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
    JOIN pg_catalog.pg_am am ON am.oid=cls.relam
    LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
    LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = {{tid}}::OID
    AND conname is NULL
{% if idx %}
    AND cls.oid = {{ idx }}::OID
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = cls.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
    ORDER BY cls.relname

实际执行:

SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name,
(SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description ELSE des.description END AS description
FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
    JOIN pg_catalog.pg_am am ON am.oid=cls.relam
    LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
    LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 24580::OID
    AND conname is NULL
    ORDER BY cls.relname

(二)创建

1,常规标签

pgadmin4树节点增删查_第51张图片

2,定义标签

pgadmin4树节点增删查_第52张图片
1,获取访问方法:

SELECT oid, amname
FROM pg_catalog.pg_am

2,获取操作符类:

SELECT opcname,  opcmethod
FROM pg_catalog.pg_opclass
    WHERE opcmethod = 3580::OID
    AND NOT opcdefault
    ORDER BY 1;

3,获取排序规则:

SELECT --nspname, collname,
	CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0  THEN
	  pg_catalog.concat(quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
	ELSE '' END AS collation
FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
    WHERE c.collnamespace=n.oid
    ORDER BY nspname, collname;

3,点击保存

pgadmin4树节点增删查_第53张图片

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
data={'name': 'index_test', 'description': '测试', 'is_sys_obj': False, 'spcname': 'pg_default', 'amname': 'btree', 'columns': [{'colname': 'tname', 'collspcname': 'pg_catalog."C"', 'op_class': 'bpchar_pattern_ops', 'sort_order': False, 'nulls': False, 'is_sort_nulls_applicable': True}]}

pg模板:
1,ddl:

CREATE {% if data.indisunique %}UNIQUE {% endif %}INDEX{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {% if data.isconcurrent %}CONCURRENTLY {% endif %}{{conn|qtIdent(data.name)}}
    ON {{conn|qtIdent(data.schema, data.table)}} {% if data.amname %}USING {{conn|qtIdent(data.amname)}}{% endif %}

{% if mode == 'create' %}
    ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(c.colname)}}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
 {{c.op_class}}{% endif %}{% if data.amname is defined %}{% if c.sort_order is defined and c.is_sort_nulls_applicable %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined and c.is_sort_nulls_applicable %} NULLS {% if c.nulls %}
FIRST{% else %}LAST{% endif %}{% endif %}{% endif %}{% endfor %})
{% if data.include|length > 0 %}
    INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
{% endif %}
{% else %}
{## We will get indented data from postgres for column ##}
    ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{c.colname}}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
 {{c.op_class}}{% endif %}{% if c.sort_order is defined %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined %} NULLS {% if c.nulls %}
FIRST{% else %}LAST{% endif %}{% endif %}{% endfor %})
{% if data.include|length > 0 %}
    INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
{% endif %}
{% endif %}
{% if data.fillfactor %}
    WITH (FILLFACTOR={{data.fillfactor}})
{% endif %}{% if data.spcname %}
    TABLESPACE {{conn|qtIdent(data.spcname)}}{% endif %}{% if data.indconstraint %}

    WHERE {{data.indconstraint}}{% endif %};

2,Alter:

{## Alter index to use cluster type ##}
{% if data.indisclustered %}

ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
    CLUSTER ON {{conn|qtIdent(data.name)}};
{% endif %}
{## Changes description ##}
{% if data.description is defined and data.description %}

COMMENT ON INDEX {{conn|qtIdent(data.schema, data.name)}}
    IS {{data.description|qtLiteral}};{% endif %}

3,获取创建后的 oid:

SELECT DISTINCT ON(cls.relname) cls.oid
FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
WHERE indrelid = {{tid}}::OID
    AND cls.relname = {{data.name|qtLiteral}};

实际执行:

CREATE INDEX index_test
    ON public.student USING btree
    (tname COLLATE pg_catalog."C" bpchar_pattern_ops ASC NULLS LAST)
    TABLESPACE pg_default;

COMMENT ON INDEX public.index_test
    IS '测试';


SELECT DISTINCT ON(cls.relname) cls.oid
FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
WHERE indrelid = 24580::OID
    AND cls.relname = 'index_test';

(三)属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
idc=24604

pg模板:

SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
    indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid,
    CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = {{ did }}::oid)
    END as spcname,
    tab.relname as tabname, indclass, con.oid AS conoid,
    CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
         ELSE des.description END AS description,
    pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
    (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
    {% if datlastsysoid %}, (CASE WHEN cls.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_idx {% endif %}
FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
    JOIN pg_catalog.pg_am am ON am.oid=cls.relam
    LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
    LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = {{tid}}::OID
    AND conname is NULL
    {% if idx %}AND cls.oid = {{idx}}::OID {% endif %}
    ORDER BY cls.relname

实际执行:

SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
    indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid,
    CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    tab.relname as tabname, indclass, con.oid AS conoid,
    CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
         ELSE des.description END AS description,
    pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
    (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
    , (CASE WHEN cls.oid <= 16383::oid THEN true ElSE false END) AS is_sys_idx FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
    JOIN pg_catalog.pg_am am ON am.oid=cls.relam
    LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
    LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 24580::OID
    AND conname is NULL
    AND cls.oid = 24604::OID     ORDER BY cls.relname

(四)删除

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
idc=24604
data={'idx': 24604}

pg模板:

DROP INDEX IF EXISTS {{conn|qtIdent(data.nspname, data.name)}}{% if cascade %} cascade{% endif %};

实际执行:先查再删

SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
    indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid,
    CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    tab.relname as tabname, indclass, con.oid AS conoid,
    CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
         ELSE des.description END AS description,
    pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
    (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
    , (CASE WHEN cls.oid <= 16383::oid THEN true ElSE false END) AS is_sys_idx FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
    JOIN pg_catalog.pg_am am ON am.oid=cls.relam
    LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
    LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 24580::OID
    AND conname is NULL
    AND cls.oid = 24604::OID     ORDER BY cls.relname

DROP INDEX IF EXISTS public.index_test;

十七,约束

5.4. 约束

(一)查询

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
{{ cid || exid }}=xxxxx
constraint_type={{ 'p' || 'f' || 'u' || 'c' || 'x' }}

pg模板:

#  查询主键、唯一、检查约束
SELECT cls.oid, cls.relname as name
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
                            dep.objid = cls.oid AND
                            dep.refobjsubid = '0' AND
                            dep.refclassid=(SELECT oid
                                            FROM pg_catalog.pg_class
                                            WHERE relname='pg_constraint') AND
                            dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
                                      con.oid = dep.refobjid)
WHERE indrelid = {{tid}}::oid
AND contype='{{constraint_type}}'
{% if cid %}
AND cls.oid = {{cid}}::oid
{% endif %}


# 查询外键约束
SELECT ct.oid,
    conname as name,
    NOT convalidated as convalidated
FROM pg_catalog.pg_constraint ct
WHERE contype='f' AND
    conrelid = {{tid}}::oid
ORDER BY conname


# 查询排他约束
SELECT conindid as oid,
    conname as name,
    NOT convalidated as convalidated
FROM pg_catalog.pg_constraint ct
WHERE contype='x' AND
    conrelid = {{tid}}::oid
{% if exid %}
    AND conindid = {{exid}}::oid
{% endif %}
ORDER BY conname

更简单的查询方式:

1,根据表名获取 tid:
SELECT oid 
FROM pg_class
WHERE relname = 'auth_group';
返回-------------------------
"oid"
"24628"


2,根据 tid 获取表中的所有约束
SELECT 
  conname AS name,
  contype AS type
FROM pg_constraint
WHERE conrelid = '16512'::regclass
返回-------------------------------
"name"							"type"
"auth_group_pkey"				"p"	# 主键约束
"auth_group_name_key"			"u" # 唯一约束
  									# f 外键约束
  									# c 查询约束
  									# x 排除约束

3,查询表中主键约束:
SELECT 
  conname AS name,
  pg_get_constraintdef(oid) AS definition  
FROM pg_constraint
WHERE conrelid = '表OID'::regclass
  AND contype = 'p'

4,查询表中唯一约束
SELECT
  conname AS name,
  pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = '表OID'::regclass
  AND contype = 'u'

5,查询表中外键约束
SELECT
  conname AS name,
  pg_get_constraintdef(oid) AS definition
FROM pg_constraint
  JOIN pg_class ON conrelid=pg_class.oid
WHERE conrelid = '表OID'::regclass
  AND contype = 'f'

6,查询表检查约束
SELECT 
  conname AS name,
  pg_get_constraintdef(oid) AS definition
FROM pg_constraint
  JOIN pg_class ON conrelid=pg_class.oid
WHERE conrelid = '表OID'::regclass
  AND contype = 'c'

6,查询表排除约束
SELECT oid, conname AS name 
FROM pg_constraint
WHERE contype = 'x';

(二)创建

1,创建主键约束

1>常规标签

pgadmin4树节点增删查_第54张图片

2>定义标签

pgadmin4树节点增删查_第55张图片1,获取列与包含列:

SELECT DISTINCT att.attname as name, att.attnum as OID, pg_catalog.format_type(ty.oid,NULL) AS datatype,
att.attnotnull as not_null, att.atthasdef as has_default_val
FROM pg_catalog.pg_attribute att
    JOIN pg_catalog.pg_type ty ON ty.oid=atttypid
    JOIN pg_catalog.pg_namespace tn ON tn.oid=ty.typnamespace
    JOIN pg_catalog.pg_class cl ON cl.oid=att.attrelid
    JOIN pg_catalog.pg_namespace na ON na.oid=cl.relnamespace
    LEFT OUTER JOIN pg_catalog.pg_type et ON et.oid=ty.typelem
    LEFT OUTER JOIN pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
    LEFT OUTER JOIN (pg_catalog.pg_depend JOIN pg_catalog.pg_class cs ON classid='pg_class'::regclass AND objid=cs.oid AND cs.relkind='S') ON refobjid=att.attrelid AND refobjsubid=att.attnum
    LEFT OUTER JOIN pg_catalog.pg_namespace ns ON ns.oid=cs.relnamespace
    LEFT OUTER JOIN pg_catalog.pg_index pi ON pi.indrelid=att.attrelid AND indisprimary
WHERE
    att.attrelid = 24580::oid
    AND att.attnum > 0
    AND att.attisdropped IS FALSE
ORDER BY att.attnum
  • tid=24580

2,获取表空间:

SELECT
    ts.oid AS oid, spcname AS name, spcowner as owner
FROM
    pg_catalog.pg_tablespace ts
ORDER BY name;

3,获取索引:

SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name,
(SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description ELSE des.description END AS description
FROM pg_catalog.pg_index idx
    JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
    JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
    LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
    JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
    JOIN pg_catalog.pg_am am ON am.oid=cls.relam
    LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
    LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 24580::OID
    AND conname is NULL
    ORDER BY cls.relname

3>点击保存

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
data={'columns': [{'column': 'sid'}], 'comment': '测试主键', 'include': [], 'name': 'student_pk', 'spcname': 'pg_default'}

pg模板:

ALTER TABLE IF EXISTS testschema.tablefor_primary_key_cons
    ADD CONSTRAINT "Pk_$%{}[]()&*^!@""'`\/#" PRIMARY KEY (col1)
    WITH (FILLFACTOR=20)
    DEFERRABLE INITIALLY DEFERRED;

COMMENT ON CONSTRAINT "Pk_$%{}[]()&*^!@""'`\/#" ON testschema.tablefor_primary_key_cons
    IS 'Comment for create';

实际执行:

ALTER TABLE IF EXISTS public.student
    ADD CONSTRAINT student_pk PRIMARY KEY (sid);

COMMENT ON CONSTRAINT student_pk ON public.student
    IS '测试主键';

2,创建外键约束

1>常规标签

pgadmin4树节点增删查_第56张图片

2>定义标签

pgadmin4树节点增删查_第57张图片- 覆盖索引中的内容是自动生成的。

3>列标签

pgadmin4树节点增删查_第58张图片pgadmin4树节点增删查_第59张图片获取列:

在这里插入代码片

获取参考:

在这里插入代码片

获取引用:

在这里插入代码片

4>行动标签

pgadmin4树节点增删查_第60张图片
获取行动:

在这里插入代码片

5>点击保存

pgadmin4树节点增删查_第61张图片

请求参数:

gid=1
sid=1
scid=2200
tid=25280
data={'name': 'c_fk', 'comment': 'd表外键', 'confmatchtype': False, 'columns': [{'local_column': 'emp_id', 'referenced': 'id', 'references': 25273, 'references_table_name': 'public.company6'}], 'confupdtype': 'a', 'confdeltype': 'a', 'autoindex': True, 'coveringindex': 'fki_C'}
  • data.references 为主表 OID 。

pg模板:

1,查询 schematable 信息:
SELECT nsp.nspname AS schema,
    rel.relname AS table
FROM
    pg_catalog.pg_class rel
JOIN pg_catalog.pg_namespace nsp
ON rel.relnamespace = nsp.oid::oid
WHERE rel.oid = {{tid}}::oid


2,创建外键:
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
    ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} FOREIGN KEY ({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
    REFERENCES {{ conn|qtIdent(data.remote_schema, data.remote_table) }} ({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}){% if data.confmatchtype is defined %} {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}{% endif%}{% if data.confupdtype is defined %}

    ON UPDATE{% if data.confupdtype  == 'a' %}
 NO ACTION{% elif data.confupdtype  == 'r' %}
 RESTRICT{% elif data.confupdtype  == 'c' %}
 CASCADE{% elif data.confupdtype  == 'n' %}
 SET NULL{% elif data.confupdtype  == 'd' %}
 SET DEFAULT{% endif %}{% endif %}{% if data.confdeltype is defined %}

    ON DELETE{% if data.confdeltype  == 'a' %}
 NO ACTION{% elif data.confdeltype  == 'r' %}
 RESTRICT{% elif data.confdeltype  == 'c' %}
 CASCADE{% elif data.confdeltype  == 'n' %}
 SET NULL{% elif data.confdeltype  == 'd' %}
 SET DEFAULT{% endif %}{% endif %}
{% if data.condeferrable %}

    DEFERRABLE{% if data.condeferred %}
 INITIALLY DEFERRED{% endif%}
{% endif%}
{% if not data.convalidated %}

    NOT VALID{% endif%};
{% if data.comment and data.name %}

COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
    IS {{ data.comment|qtLiteral }};

{% endif %}

{% if data.autoindex and data.coveringindex%}
CREATE INDEX IF NOT EXISTS {{ conn|qtIdent(data.coveringindex) }}
    ON {{ conn|qtIdent(data.schema, data.table) }}({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %});
{% endif %}


4,获取外键 OID 信息:
SELECT ct.oid,
    NOT convalidated as convalidated
FROM pg_catalog.pg_constraint ct
WHERE contype='f' AND
ct.conname = {{ name|qtLiteral }};

实际执行:

1,获取从表 schematable 信息:
SELECT nsp.nspname AS schema,
    rel.relname AS table
FROM
    pg_catalog.pg_class rel
JOIN pg_catalog.pg_namespace nsp
ON rel.relnamespace = nsp.oid::oid
WHERE rel.oid = 25280::oid


2,获取主表 schematable 信息:
SELECT nsp.nspname AS schema,
    rel.relname AS table
FROM
    pg_catalog.pg_class rel
JOIN pg_catalog.pg_namespace nsp
ON rel.relnamespace = nsp.oid::oid
WHERE rel.oid = 25273::oid



3,创建外键
ALTER TABLE IF EXISTS public.department1
    ADD CONSTRAINT c_fk FOREIGN KEY (emp_id)
    REFERENCES public.company6 (id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;

COMMENT ON CONSTRAINT c_fk ON public.department1
    IS 'd表外键';


CREATE INDEX IF NOT EXISTS "fki_C"
    ON public.department1(emp_id);


4,获取外键 OID 信息:
SELECT ct.oid,
    NOT convalidated as convalidated
FROM pg_catalog.pg_constraint ct
WHERE contype='f' AND
ct.conname = 'c_fk';

3,创建唯一约束

1>常规标签

pgadmin4树节点增删查_第62张图片

2>定义标签

pgadmin4树节点增删查_第63张图片

3>点击保存

pgadmin4树节点增删查_第64张图片

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
data={'columns': [{'column': 'sid'}], 'comment': '测试唯一约束', 'include': [], 'name': 'student_uk', 'spcname': 'pg_default'}

pg模板:

在这里插入代码片

实际执行:

ALTER TABLE IF EXISTS public.student
    ADD CONSTRAINT student_uk UNIQUE (sid);

COMMENT ON CONSTRAINT student_uk ON public.student
    IS '测试唯一约束';

4,创建检查约束

1>常规标签

pgadmin4树节点增删查_第65张图片

2>定义标签

pgadmin4树节点增删查_第66张图片

3>点击保存

pgadmin4树节点增删查_第67张图片

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
data={'comment': '检查约束', 'consrc': 'sid > 0', 'convalidated': True, 'name': 'student_ck', 'schema': 'public', 'table': 'student'}

pg模板:

{% if data %}
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
    ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} CHECK ({{ data.consrc }}){% if data.convalidated %}

    NOT VALID{% endif %}{% if data.connoinherit %} NO INHERIT{% endif %};
{% endif %}
{% if data.comment %}

COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
    IS {{ data.comment|qtLiteral }};
{% endif %}


SELECT ct.oid,
    ct.conname as name,
    NOT convalidated as convalidated
FROM pg_catalog.pg_constraint ct
WHERE contype='c' AND
    conrelid = {{tid}}::oid LIMIT 1;

实际执行:

ALTER TABLE IF EXISTS public.student
    ADD CONSTRAINT student_ck CHECK (sid > 0)
    NOT VALID;

COMMENT ON CONSTRAINT student_ck ON public.student
    IS '检查约束';

# 查出并返回 oid
SELECT
    oid, conname as name,
    NOT convalidated as convalidated
FROM
    pg_catalog.pg_constraint
WHERE
    conrelid = 24580::oid
    AND conname='student_ck';

5,创建排他约束

1>常规标签

pgadmin4树节点增删查_第68张图片

2>定义标签

pgadmin4树节点增删查_第69张图片获取访问方法:

在这里插入代码片

3>列标签

pgadmin4树节点增删查_第70张图片获取操作符:

在这里插入代码片

3>点击保存

pgadmin4树节点增删查_第71张图片

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=25264
data={'name': 't2_ek', 'comment': '测试排他约束', 'spcname': 'pg_default', 'amname': 'gist', 'columns': [{'column': 'c1', 'order': False, 'nulls_order': False, 'operator': '=', 'col_type': 'integer'}, {'column': 'c2', 'order': False, 'nulls_order': False, 'operator': '<>', 'col_type': 'text'}], 'include': []}

pg模板:

ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
    ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} EXCLUDE {% if data.amname and data.amname != '' %}USING {{data.amname}}{% endif %} (
    {% for col in data.columns %}{% if loop.index != 1 %},
    {% endif %}{% if col.is_exp %}{{col.column}}{% else %}{{ conn|qtIdent(col.column)}}{% endif %}{% if col.oper_class and col.oper_class != '' %} {{col.oper_class}}{% endif%}{% if col.order is defined and col.is_sort_nulls_applicable %}{% if col.order %} ASC{% else %} DESC{% endif %} NULLS{% endif %} {% if col.nulls_order is defined and col.is_sort_nulls_applicable %}{% if col.nulls_order %}FIRST {% else %}LAST {% endif %}{% endif %}WITH {{col.operator}}{% endfor %}){% if data.fillfactor %}

    WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}

    USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% if data.indconstraint %}

    WHERE ({{data.indconstraint}}){% endif%}
{% if data.condeferrable %}

    DEFERRABLE{% if data.condeferred %}
 INITIALLY DEFERRED{% endif%}{% endif%};
{% if data.comment and data.name %}

COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
    IS {{ data.comment|qtLiteral }};
{% endif %}

实际执行:

ALTER TABLE IF EXISTS public.t2
    ADD CONSTRAINT t2_ek EXCLUDE USING gist (
    c1 WITH =,
    c2 WITH <>);

COMMENT ON CONSTRAINT t2_ek ON public.t2
    IS '测试排他约束';

同时返回oid等信息:

SELECT ct.conindid AS oid
FROM pg_catalog.pg_constraint ct
WHERE contype='x' AND
ct.conname = 't2_ek';

(三)属性

1,主键约束属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
cid=24620
constraint_type='p'		# 查询主键

pg模板:

1,查询基本信息:
SELECT cls.oid,
    cls.relname as name,
    indnatts as col_count,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = {{ did }}::oid)
    END as spcname,
    CASE contype
        WHEN 'p' THEN desp.description
        WHEN 'u' THEN desp.description
        WHEN 'x' THEN desp.description
        ELSE des.description
    END AS comment,
    condeferrable,
    condeferred,
    conislocal,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = {{tid}}::oid
{% if cid %}
AND cls.oid = {{cid}}::oid
{% endif %}
AND contype='{{constraint_type}}'
ORDER BY cls.relname

2,查询列信息:
{###
We need outer SELECT & dummy column to preserve the ordering
because we lose ordering when we use UNION
###}
SELECT * FROM (
{% for n in range(colcnt|int) %}
{% if loop.index != 1 %}
UNION SELECT  pg_catalog.pg_get_indexdef({{ cid|string }}, {{ loop.index|string }}, true) AS column, {{ n }} AS dummy
{% else %}
SELECT  pg_catalog.pg_get_indexdef({{ cid|string }} , {{ loop.index|string }} , true) AS column, {{ n }} AS dummy
{% endif %}
{% endfor %}
) tmp
ORDER BY dummy

实际执行:

SELECT cls.oid,
    cls.relname as name,
    indnkeyatts as col_count,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    CASE contype
        WHEN 'p' THEN desp.description
        WHEN 'u' THEN desp.description
        WHEN 'x' THEN desp.description
        ELSE des.description
    END AS comment,
    condeferrable,
    condeferred,
    conislocal,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 24580::oid
AND cls.oid = 24620::oid
AND contype='p'
ORDER BY cls.relname


SELECT * FROM (
SELECT  pg_catalog.pg_get_indexdef(24620 , 1 , true) AS column, 0 AS dummy
) tmp
ORDER BY dummy

2,外键约束属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24580
fkid=25285

pg模板:

1,查询外键基本属性
SELECT ct.oid,
      conname as name,
      condeferrable,
      condeferred,
      confupdtype,
      confdeltype,
      CASE confmatchtype
        WHEN 's' THEN FALSE
        WHEN 'f' THEN TRUE
      END AS confmatchtype,
      conkey,
      confkey,
      confrelid,
      nl.nspname as fknsp,
      cl.relname as fktab,
      nr.oid as refnspoid,
      nr.nspname as refnsp,
      cr.relname as reftab,
      description as comment,
      convalidated,
      conislocal
FROM pg_catalog.pg_constraint ct
JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
JOIN pg_catalog.pg_namespace nl ON nl.oid=cl.relnamespace
JOIN pg_catalog.pg_class cr ON cr.oid=confrelid
JOIN pg_catalog.pg_namespace nr ON nr.oid=cr.relnamespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=ct.oid AND des.classoid='pg_constraint'::regclass)
WHERE contype='f' AND
conrelid = {{tid}}::oid
{% if fkid %}
AND ct.oid = {{fkid}}::oid
{% endif %}
ORDER BY conname


2,根据上面的查询结果,查询主表信息
{% for keypair in keys %}
{% if loop.index != 1 %}
UNION
{% endif %}
SELECT a1.attname as conattname,
    a2.attname as confattname
FROM pg_catalog.pg_attribute a1,
    pg_catalog.pg_attribute a2
WHERE a1.attrelid={{tid}}::oid
    AND a1.attnum={{keypair[1]}}
    AND a2.attrelid={{confrelid}}::oid
    AND a2.attnum={{keypair[0]}}
{% endfor %}

实际执行:

SELECT ct.oid,
      conname as name,
      condeferrable,
      condeferred,
      confupdtype,
      confdeltype,
      CASE confmatchtype
        WHEN 's' THEN FALSE
        WHEN 'f' THEN TRUE
      END AS confmatchtype,
      conkey,
      confkey,
      confrelid,
      nl.nspname as fknsp,
      cl.relname as fktab,
      nr.oid as refnspoid,
      nr.nspname as refnsp,
      cr.relname as reftab,
      description as comment,
      convalidated,
      conislocal
FROM pg_catalog.pg_constraint ct
JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
JOIN pg_catalog.pg_namespace nl ON nl.oid=cl.relnamespace
JOIN pg_catalog.pg_class cr ON cr.oid=confrelid
JOIN pg_catalog.pg_namespace nr ON nr.oid=cr.relnamespace
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=ct.oid AND des.classoid='pg_constraint'::regclass)
WHERE contype='f' AND
conrelid = 25280::oid
AND ct.oid = 25285::oid
ORDER BY conname


2,
SELECT a1.attname as conattname,
    a2.attname as confattname
FROM pg_catalog.pg_attribute a1,
    pg_catalog.pg_attribute a2
WHERE a1.attrelid=25280::oid
    AND a1.attnum=3
    AND a2.attrelid=25273::oid
    AND a2.attnum=1

3,唯一约束属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24580
cid=24620
constraint_type='u'		# 查询唯一约束

pg模板:

SELECT cls.oid,
    cls.relname as name,
    indnatts as col_count,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = {{ did }}::oid)
    END as spcname,
    CASE contype
        WHEN 'p' THEN desp.description
        WHEN 'u' THEN desp.description
        WHEN 'x' THEN desp.description
        ELSE des.description
    END AS comment,
    condeferrable,
    condeferred,
    conislocal,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = {{tid}}::oid
{% if cid %}
AND cls.oid = {{cid}}::oid
{% endif %}
AND contype='{{constraint_type}}'
ORDER BY cls.relname


{###
We need outer SELECT & dummy column to preserve the ordering
because we lose ordering when we use UNION
###}
SELECT * FROM (
{% for n in range(colcnt|int) %}
{% if loop.index != 1 %}
UNION SELECT  pg_catalog.pg_get_indexdef({{ cid|string }}, {{ loop.index|string }}, true) AS column, {{ n }} AS dummy
{% else %}
SELECT  pg_catalog.pg_get_indexdef({{ cid|string }} , {{ loop.index|string }} , true) AS column, {{ n }} AS dummy
{% endif %}
{% endfor %}
) tmp
ORDER BY dummy

实际执行:

SELECT cls.oid,
    cls.relname as name,
    indnkeyatts as col_count,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    CASE contype
        WHEN 'p' THEN desp.description
        WHEN 'u' THEN desp.description
        WHEN 'x' THEN desp.description
        ELSE des.description
    END AS comment,
    condeferrable,
    condeferred,
    conislocal,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 24580::oid
AND cls.oid = 24626::oid
AND contype='u'
ORDER BY cls.relname


SELECT * FROM (
SELECT  pg_catalog.pg_get_indexdef(24626 , 1 , true) AS column, 0 AS dummy
) tmp
ORDER BY dummy

4,检查约束属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
cid=24628
constraint_type='c'		# 查询检查约束

pg模板:

SELECT c.oid, conname as name, relname, nspname, description as comment,
       pg_catalog.pg_get_expr(conbin, conrelid, true) as consrc,
       connoinherit, NOT convalidated as convalidated, conislocal
    FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
    JOIN pg_catalog.pg_namespace nl ON nl.oid=relnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND
                           des.classoid='pg_constraint'::regclass)
WHERE contype = 'c'
    AND conrelid = {{ tid }}::oid
{% if cid %}
    AND c.oid = {{ cid }}::oid
{% endif %}

实际执行:

SELECT c.oid, conname as name, relname, nspname, description as comment,
       pg_catalog.pg_get_expr(conbin, conrelid, true) as consrc,
       connoinherit, NOT convalidated as convalidated, conislocal
    FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
    JOIN pg_catalog.pg_namespace nl ON nl.oid=relnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND
                           des.classoid='pg_constraint'::regclass)
WHERE contype = 'c'
    AND conrelid = 24580::oid
    AND c.oid = 24628::oid

5,排他约束属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=25264
exid=25269

pg模板:

# 1,查询基本信息
SELECT cls.oid,
    cls.relname as name,
    indnatts as col_count,
    amname,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = {{ did }}::oid)
    END as spcname,
    CASE contype
        WHEN 'p' THEN desp.description
        WHEN 'u' THEN desp.description
        WHEN 'x' THEN desp.description
        ELSE des.description
    END AS comment,
    condeferrable,
    condeferred,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
    pg_catalog.pg_get_expr(idx.indpred, idx.indrelid, true) AS indconstraint
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
JOIN pg_catalog.pg_am am ON am.oid=cls.relam
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = {{tid}}::oid
{% if cid %}
AND cls.oid = {{cid}}::oid
{% endif %}
AND contype='x'
ORDER BY cls.relname


# 2,查询列相关信息
{% for n in range(colcnt|int) %}
{% if loop.index != 1 %}
UNION
{% endif %}
SELECT
  i.indoption[{{loop.index -1}}] AS options,
  pg_catalog.pg_get_indexdef(i.indexrelid, {{loop.index}}, true) AS coldef,
  op.oprname,
  CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname
,
  coll.collname,
  nspc.nspname as collnspname,
  pg_catalog.format_type(ty.oid,NULL) AS datatype,
  CASE WHEN pg_catalog.pg_get_indexdef(i.indexrelid, {{loop.index}}, true) = a.attname THEN FALSE ELSE TRUE END AS is_exp
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_attribute a ON (a.attrelid = i.indexrelid AND attnum = {{loop.index}})
JOIN pg_catalog.pg_type ty ON ty.oid=a.atttypid
LEFT OUTER JOIN pg_catalog.pg_opclass o ON (o.oid = i.indclass[{{loop.index -1}}])
LEFT OUTER JOIN pg_catalog.pg_constraint c ON (c.conindid = i.indexrelid) LEFT OUTER JOIN pg_catalog.pg_operator op ON (op.oid = c.conexclop[{{loop.index}}])
LEFT OUTER JOIN pg_catalog.pg_collation coll ON a.attcollation=coll.oid
LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
WHERE i.indexrelid = {{cid}}::oid
{% endfor %}

实际执行:

SELECT cls.oid,
    cls.relname as name,
    indnkeyatts as col_count,
    amname,
    CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
        (SELECT sp.spcname FROM pg_catalog.pg_database dtb
        JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
        WHERE dtb.oid = 13799::oid)
    END as spcname,
    CASE contype
        WHEN 'p' THEN desp.description
        WHEN 'u' THEN desp.description
        WHEN 'x' THEN desp.description
        ELSE des.description
    END AS comment,
    condeferrable,
    condeferred,
    substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
    pg_catalog.pg_get_expr(idx.indpred, idx.indrelid, true) AS indconstraint
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
JOIN pg_catalog.pg_am am ON am.oid=cls.relam
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
WHERE indrelid = 25264::oid
AND cls.oid = 25269::oid
AND contype='x'
ORDER BY cls.relname


SELECT
  i.indoption[0] AS options,
  pg_catalog.pg_get_indexdef(i.indexrelid, 1, true) AS coldef,
  op.oprname,
  CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname
,
  coll.collname,
  nspc.nspname as collnspname,
  pg_catalog.format_type(ty.oid,NULL) AS datatype,
  CASE WHEN pg_catalog.pg_get_indexdef(i.indexrelid, 1, true) = a.attname THEN FALSE ELSE TRUE END AS is_exp
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_attribute a ON (a.attrelid = i.indexrelid AND attnum = 1)
JOIN pg_catalog.pg_type ty ON ty.oid=a.atttypid
LEFT OUTER JOIN pg_catalog.pg_opclass o ON (o.oid = i.indclass[0])
LEFT OUTER JOIN pg_catalog.pg_constraint c ON (c.conindid = i.indexrelid) LEFT OUTER JOIN pg_catalog.pg_operator op ON (op.oid = c.conexclop[1])
LEFT OUTER JOIN pg_catalog.pg_collation coll ON a.attcollation=coll.oid
LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
WHERE i.indexrelid = 25269::oid
UNION
SELECT
  i.indoption[1] AS options,
  pg_catalog.pg_get_indexdef(i.indexrelid, 2, true) AS coldef,
  op.oprname,
  CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname
,
  coll.collname,
  nspc.nspname as collnspname,
  pg_catalog.format_type(ty.oid,NULL) AS datatype,
  CASE WHEN pg_catalog.pg_get_indexdef(i.indexrelid, 2, true) = a.attname THEN FALSE ELSE TRUE END AS is_exp
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_attribute a ON (a.attrelid = i.indexrelid AND attnum = 2)
JOIN pg_catalog.pg_type ty ON ty.oid=a.atttypid
LEFT OUTER JOIN pg_catalog.pg_opclass o ON (o.oid = i.indclass[1])
LEFT OUTER JOIN pg_catalog.pg_constraint c ON (c.conindid = i.indexrelid) LEFT OUTER JOIN pg_catalog.pg_operator op ON (op.oid = c.conexclop[2])
LEFT OUTER JOIN pg_catalog.pg_collation coll ON a.attcollation=coll.oid
LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
WHERE i.indexrelid = 25269::oid

(四)删除

1,删除主键约束

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
cid=24618

pg模板:

SELECT cls.relname as name
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
                            dep.objid = cls.oid AND
                            dep.refobjsubid = '0'
                            AND dep.refclassid=(SELECT oid
                                                FROM pg_catalog.pg_class
                                                WHERE relname='pg_constraint') AND
                            dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
                                      con.oid = dep.refobjid)
WHERE indrelid = {{tid}}::oid
AND contype='{{constraint_type}}'
AND cls.oid = {{cid}}::oid;

{% if data %}
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
{% endif %}

实际执行:先查再删

SELECT cls.relname as name
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
                            dep.objid = cls.oid AND
                            dep.refobjsubid = '0'
                            AND dep.refclassid=(SELECT oid
                                                FROM pg_catalog.pg_class
                                                WHERE relname='pg_constraint') AND
                            dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
                                      con.oid = dep.refobjid)
WHERE indrelid = 24580::oid
AND contype='p'
AND cls.oid = 24618::oid;

ALTER TABLE IF EXISTS public.student DROP CONSTRAINT IF EXISTS student_pk;

2,删除外键约束

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24580
fkid=25285

pg模板:

1,
SELECT conname as name
FROM pg_catalog.pg_constraint ct
WHERE ct.oid = {{fkid}}::oid


2,
{% if data %}
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
{% endif %}

实际执行:先查再删:

1,
SELECT conname as name
FROM pg_catalog.pg_constraint ct
WHERE ct.oid = 25285::oid

2,
ALTER TABLE IF EXISTS public.department1 DROP CONSTRAINT IF EXISTS c_fk;

3,删除唯一约束

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
cid=24620

pg模板:

SELECT cls.relname as name
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
                            dep.objid = cls.oid AND
                            dep.refobjsubid = '0'
                            AND dep.refclassid=(SELECT oid
                                                FROM pg_catalog.pg_class
                                                WHERE relname='pg_constraint') AND
                            dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
                                      con.oid = dep.refobjid)
WHERE indrelid = {{tid}}::oid
AND contype='{{constraint_type}}'
AND cls.oid = {{cid}}::oid;

{% if data %}
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
{% endif %}

实际执行:

SELECT cls.relname as name
FROM pg_catalog.pg_index idx
JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
                            dep.objid = cls.oid AND
                            dep.refobjsubid = '0'
                            AND dep.refclassid=(SELECT oid
                                                FROM pg_catalog.pg_class
                                                WHERE relname='pg_constraint') AND
                            dep.deptype='i')
LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
                                      con.oid = dep.refobjid)
WHERE indrelid = 24580::oid
AND contype='u'
AND cls.oid = 24626::oid;

ALTER TABLE IF EXISTS public.student DROP CONSTRAINT IF EXISTS student_uk;

4,删除检查约束

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500
cid=25272

pg模板:

1,先获取基本信息
SELECT c.oid, conname as name, relname, nspname, description as comment,
       pg_catalog.pg_get_expr(conbin, conrelid, true) as consrc,
       connoinherit, NOT convalidated as convalidated, conislocal
    FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
    JOIN pg_catalog.pg_namespace nl ON nl.oid=relnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND
                           des.classoid='pg_constraint'::regclass)
WHERE contype = 'c'
    AND conrelid = {{ tid }}::oid
{% if cid %}
    AND c.oid = {{ cid }}::oid
{% endif %}


2,再删除:
{% if data %}
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.nspname, data.relname) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }};
{% endif %}

实际执行:先查再删:

SELECT c.oid, conname as name, relname, nspname, description as comment,
       pg_catalog.pg_get_expr(conbin, conrelid, true) as consrc,
       connoinherit, NOT convalidated as convalidated, conislocal
    FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
    JOIN pg_catalog.pg_namespace nl ON nl.oid=relnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND
                           des.classoid='pg_constraint'::regclass)
WHERE contype = 'c'
    AND conrelid = 24580::oid
    AND c.oid = 25272::oid


ALTER TABLE IF EXISTS public.student DROP CONSTRAINT IF EXISTS student_ck;

5,删除排他约束

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=25264
exid=25269

pg模板:

SELECT conname as name
FROM pg_catalog.pg_constraint ct
WHERE ct.conindid = {{exid}}::oid


{% if data %}
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
{% endif %}

实际执行:先查再删:

SELECT conname as name
FROM pg_catalog.pg_constraint ct
WHERE ct.conindid = 25269::oid

ALTER TABLE IF EXISTS public.t2 DROP CONSTRAINT IF EXISTS t2_ek;

十八,规则

第 41 章 规则系统

(一)查询

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24500

pg模板:

SELECT
    rw.oid AS oid,
    rw.rulename AS name,
    CASE WHEN rw.ev_enabled != 'D' THEN True ELSE False END AS enabled,
    rw.ev_enabled AS is_enable_rule

FROM
    pg_catalog.pg_rewrite rw
WHERE
{% if tid %}
    rw.ev_class = {{ tid }}
{% elif rid %}
    rw.oid = {{ rid }}
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = rw.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY
    rw.rulename

实际执行:

SELECT
    rw.oid AS oid,
    rw.rulename AS name,
    CASE WHEN rw.ev_enabled != 'D' THEN True ELSE False END AS enabled,
    rw.ev_enabled AS is_enable_rule

FROM
    pg_catalog.pg_rewrite rw
WHERE
    rw.ev_class = 24580
ORDER BY
    rw.rulename

十九,触发器

(一)查询

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24611

pg模板:

SELECT t.oid, t.tgname as name, t.tgenabled AS is_enable_trigger
FROM pg_catalog.pg_trigger t
    WHERE NOT tgisinternal
    AND tgrelid = {{tid}}::OID
{% if trid %}
    AND t.oid = {{trid}}::OID
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
    ORDER BY tgname;

实际执行:

SELECT t.oid, t.tgname as name, t.tgenabled AS is_enable_trigger
FROM pg_catalog.pg_trigger t
    WHERE NOT tgisinternal
    AND tgrelid = 24611::OID
    ORDER BY tgname;

(二)创建

1,常规标签

pgadmin4树节点增删查_第72张图片

2,定义标签

pgadmin4树节点增删查_第73张图片

3,事件标签

pgadmin4树节点增删查_第74张图片

4,转换标签

pgadmin4树节点增删查_第75张图片

5,代码标签

pgadmin4树节点增删查_第76张图片

6,点击保存

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24611
data={'description': '测试', 'evnt_insert': True, 'evnt_truncate': False, 'fires': 'BEFORE', 'is_row_trigger': True, 'name': 'update_order_status_trigger', 'tfunction': 'public.update_order_status'}

pg模板:

{### Set a flag which allows us to put OR between events ###}
{% set or_flag = False %}
{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
{% else %}
CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
{% endif %}
    {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
{% endif %}{% if data.evnt_delete %}
{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
{% endif %}{% if data.evnt_truncate %}
{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
{% endif %}{% if data.evnt_update %}
{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
{% endif %}

    ON {{ conn|qtIdent(data.schema, data.table) }}
{% if data.tgdeferrable %}
    DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}

{% endif %}
{% if data.tgoldtable or data.tgnewtable %}
    REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}

{% endif %}
    FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
{% if data.whenclause %}

    WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}

    {% if data.prosrc is defined and
    (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};

{% if data.description %}
COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
    IS {{data.description|qtLiteral}};
{% endif %}

实际执行:

CREATE TRIGGER update_order_status_trigger
    BEFORE INSERT
    ON public.orders
    FOR EACH ROW
    EXECUTE FUNCTION public.update_order_status();

COMMENT ON TRIGGER update_order_status_trigger ON public.orders
    IS '测试';

再获取时间触发器的OID并连同type等信息返回给前端:

SELECT t.oid
FROM pg_catalog.pg_trigger t
    WHERE NOT tgisinternal
    AND tgrelid = 24611::OID
    AND tgname = 'update_order_status_trigger';

(三)属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24611
trid=24617

pg模板:

SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
    nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
    COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
    pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*)  \$trigger')) AS whenclause,
    -- We need to convert tgargs column bytea datatype to array datatype
    (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
{% if datlastsysoid %}
    (CASE WHEN t.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_trigger,
{% endif %}
    (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
    tgoldtable,
    tgnewtable
FROM pg_catalog.pg_trigger t
    JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
    JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
    LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
WHERE NOT tgisinternal
    AND tgrelid = {{tid}}::OID
{% if trid %}
    AND t.oid = {{trid}}::OID
{% endif %}
ORDER BY tgname;

实际执行:

SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
    nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
    COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
    pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*)  \$trigger')) AS whenclause,
    -- We need to convert tgargs column bytea datatype to array datatype
    (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
    (CASE WHEN t.oid <= 16383::oid THEN true ElSE false END) AS is_sys_trigger,
    (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
    tgoldtable,
    tgnewtable
FROM pg_catalog.pg_trigger t
    JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
    JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
    LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
WHERE NOT tgisinternal
    AND tgrelid = 24611::OID
    AND t.oid = 24617::OID
ORDER BY tgname;

(四)删除

请求参数:

gid=1
sid=1
did=13799
scid=2200
tid=24611
trid=24617

pg模板:

# 1,
SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
    nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
    COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
    pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*)  \$trigger')) AS whenclause,
    -- We need to convert tgargs column bytea datatype to array datatype
    (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
{% if datlastsysoid %}
    (CASE WHEN t.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_trigger,
{% endif %}
    (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
    tgoldtable,
    tgnewtable
FROM pg_catalog.pg_trigger t
    JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
    JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
    LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
WHERE NOT tgisinternal
    AND tgrelid = {{tid}}::OID
{% if trid %}
    AND t.oid = {{trid}}::OID
{% endif %}
ORDER BY tgname;


# 2,
DROP TRIGGER IF EXISTS {{conn|qtIdent(data.name)}} ON {{conn|qtIdent(data.nspname, data.relname )}}{% if cascade %} CASCADE{% endif %};

实际执行:同样是先根据trid查询出触发器名称,再根据触发器名称删除触发器:

SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
    nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
    COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
    pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*)  \$trigger')) AS whenclause,
    -- We need to convert tgargs column bytea datatype to array datatype
    (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
    (CASE WHEN t.oid <= 16383::oid THEN true ElSE false END) AS is_sys_trigger,
    (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
    tgoldtable,
    tgnewtable
FROM pg_catalog.pg_trigger t
    JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
    JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
    LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
    LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
WHERE NOT tgisinternal
    AND tgrelid = 24611::OID
    AND t.oid = 24617::OID
ORDER BY tgname;


DROP TRIGGER IF EXISTS update_order_status_trigger ON public.orders;

二十,序列

(一)查询

在这里插入图片描述

请求参数:

gid=1
sid=1
scid=2200

pg模板:

SELECT cl.oid as oid, relname as name, relnamespace as schema
FROM pg_catalog.pg_class cl
{% if show_internal %}
LEFT JOIN pg_catalog.pg_depend d1 ON d1.refobjid = cl.oid AND d1.deptype = 'i'
{% endif %}
WHERE
    relkind = 'S'
{% if scid %}
    AND relnamespace = {{scid|qtLiteral}}::oid
{% endif %}
{% if seid %}
    AND cl.oid = {{seid|qtLiteral}}::oid
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = cl.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY relname

实际执行:

SELECT cl.oid as oid, relname as name, relnamespace as schema
FROM pg_catalog.pg_class cl
WHERE
    relkind = 'S'
    AND relnamespace = 2200::oid
ORDER BY relname

(二)创建

1,常规标签

pgadmin4树节点增删查_第77张图片

2,定义标签

在这里插入图片描述

3,安全标签

pgadmin4树节点增删查_第78张图片

4,点击保存

请求参数:

gid=1
sid=1
scid=2200
data={'name': 'test', 'seqowner': 'postgres', 'schema': 'public', 'comment': '测试', 'increment': '1', 'start': '1', 'minimum': '1', 'maximum': '9223372036854775807', 'cache': '1', 'cycled': True, 'relacl': [], 'securities': [], 'owned_table': 'student', 'owned_column': 'sid'}

pg模板:
1,create-ddl:

CREATE SEQUENCE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}{% if data.increment is defined and data.cycled %}

    CYCLE{% endif %}{% if data.increment is defined %}

    INCREMENT {{data.increment|int}}{% endif %}{% if data.start is defined %}

    START {{data.start|int}}{% elif data.current_value is defined %}

    START {{data.current_value|int}}{% endif %}{% if data.minimum is defined %}

    MINVALUE {{data.minimum|int}}{% endif %}{% if data.maximum is defined %}

    MAXVALUE {{data.maximum|int}}{% endif %}{% if data.cache is defined and data.cache|int(-1) > -1%}

    CACHE {{data.cache|int}}{% endif %}{% if data.owned_table is defined and data.owned_table != None and data.owned_column is defined and data.owned_column != None %}

    OWNED BY {{ conn|qtIdent(data.owned_table) }}.{{ conn|qtIdent(data.owned_column) }}{% endif %};

2,grant:

{% import 'macros/schemas/security.macros' as SECLABEL %}
{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
{# Construct sequence name from name and schema #}
{% set seqname=conn|qtIdent(data.schema, data.name) %}
{% if data.seqowner %}

ALTER SEQUENCE {{ seqname }}
    OWNER TO {{ conn|qtIdent(data.seqowner) }};
{% endif %}
{% if data.comment %}

COMMENT ON SEQUENCE {{ seqname }}
    IS {{ data.comment|qtLiteral }};
{% endif %}
{% if data.securities %}

{% for r in data.securities %}
{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, data.schema) }}
{% endfor %}
{% endif %}
{% if data.relacl %}

{% for priv in data.relacl %}
{% if priv.without_grant %}
GRANT {{ priv.without_grant|join(', ') }} ON 'SEQUENCE' {{ conn|qtIdent(data.schema, data.name) }} TO priv.grantee;
{% endif %}
{% if priv.with_grant %}
    {% if priv.without_grant %}
    {# This empty if is to add new line in between #}
    {% endif %}
GRANT {{ priv.with_grant|join(', ') }} ON 'SEQUENCE' {{ conn|qtIdent(data.schema, data.name) }} TO priv.grantee WITH GRANT OPTION;
{% endif %}
{%- endmacro %}
{% endfor %}
{% endif %}

实际执行:

CREATE SEQUENCE public.test
    CYCLE
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1
    OWNED BY student.sid;

ALTER SEQUENCE public.test
    OWNER TO postgres;

COMMENT ON SEQUENCE public.test
    IS '测试';

创建后执行下面语句获取oid:

SELECT cl.oid as oid, relnamespace
FROM pg_catalog.pg_class cl
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON (nsp.oid = cl.relnamespace)
WHERE relkind = 'S'
AND relname = 'test'
AND nspname = 'public'
SELECT cl.oid as oid, relnamespace
FROM pg_catalog.pg_class cl
LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid AND des.classoid='pg_class'::regclass)
LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON (nsp.oid = cl.relnamespace)
WHERE relkind = 'S'
AND relname = {{ name|qtLiteral }}
AND nspname = {{ schema|qtLiteral }}

(三)属性

请求参数:

gid=1
sid=1
scid=2200
seid=24603

pg模板:

获取基础信息:
{% if scid %}
SELECT
    cl.oid as oid,
    cl.relname as name,
    nsp.nspname as schema,
    pg_catalog.pg_get_userbyid(cl.relowner) AS seqowner,
    description as comment,
    pg_catalog.array_to_string(cl.relacl::text[], ', ') as acl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=cl.oid) AS securities,
    depcl.relname AS owned_table,
    att.attname AS owned_column
FROM pg_catalog.pg_class cl
    LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON cl.relnamespace = nsp.oid
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid
        AND des.classoid='pg_class'::regclass)
	LEFT OUTER JOIN pg_catalog.pg_depend dep ON (dep.objid=cl.oid and deptype = 'a')
	LEFT JOIN pg_catalog.pg_attribute att ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
	LEFT JOIN pg_catalog.pg_class depcl ON depcl.oid = att.attrelid
WHERE cl.relkind = 'S' AND cl.relnamespace  = {{scid}}::oid
{% if seid %}AND cl.oid = {{seid}}::oid {% endif %}
ORDER BY cl.relname
{% endif %}

获取acl信息:
SELECT 'relacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
FROM
    (SELECT
        d.grantee, d.grantor, d.is_grantable,
        CASE d.privilege_type
        WHEN 'CONNECT' THEN 'c'
        WHEN 'CREATE' THEN 'C'
        WHEN 'DELETE' THEN 'd'
        WHEN 'EXECUTE' THEN 'X'
        WHEN 'INSERT' THEN 'a'
        WHEN 'REFERENCES' THEN 'x'
        WHEN 'SELECT' THEN 'r'
        WHEN 'TEMPORARY' THEN 'T'
        WHEN 'TRIGGER' THEN 't'
        WHEN 'TRUNCATE' THEN 'D'
        WHEN 'UPDATE' THEN 'w'
        WHEN 'USAGE' THEN 'U'
        ELSE 'UNKNOWN'
        END AS privilege_type
    FROM
        pg_catalog.aclexplode((SELECT relacl
            FROM pg_catalog.pg_class cl
            LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid AND des.classoid='pg_class'::regclass)
            WHERE relkind = 'S' AND relnamespace  = {{scid}}::oid
            AND cl.oid = {{seid}}::oid )) d
        ) d
    LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
    LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
GROUP BY g.rolname, gt.rolname
ORDER BY grantee

实际执行:

SELECT
    cl.oid as oid,
    cl.relname as name,
    nsp.nspname as schema,
    pg_catalog.pg_get_userbyid(cl.relowner) AS seqowner,
    description as comment,
    pg_catalog.array_to_string(cl.relacl::text[], ', ') as acl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=cl.oid) AS securities,
    depcl.relname AS owned_table,
    att.attname AS owned_column
FROM pg_catalog.pg_class cl
    LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON cl.relnamespace = nsp.oid
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid
        AND des.classoid='pg_class'::regclass)
	LEFT OUTER JOIN pg_catalog.pg_depend dep ON (dep.objid=cl.oid and deptype = 'a')
	LEFT JOIN pg_catalog.pg_attribute att ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
	LEFT JOIN pg_catalog.pg_class depcl ON depcl.oid = att.attrelid
WHERE cl.relkind = 'S' AND cl.relnamespace  = 2200::oid
AND cl.oid = 24603::oid ORDER BY cl.relname


SELECT 'relacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
FROM
    (SELECT
        d.grantee, d.grantor, d.is_grantable,
        CASE d.privilege_type
        WHEN 'CONNECT' THEN 'c'
        WHEN 'CREATE' THEN 'C'
        WHEN 'DELETE' THEN 'd'
        WHEN 'EXECUTE' THEN 'X'
        WHEN 'INSERT' THEN 'a'
        WHEN 'REFERENCES' THEN 'x'
        WHEN 'SELECT' THEN 'r'
        WHEN 'TEMPORARY' THEN 'T'
        WHEN 'TRIGGER' THEN 't'
        WHEN 'TRUNCATE' THEN 'D'
        WHEN 'UPDATE' THEN 'w'
        WHEN 'USAGE' THEN 'U'
        ELSE 'UNKNOWN'
        END AS privilege_type
    FROM
        pg_catalog.aclexplode((SELECT relacl
            FROM pg_catalog.pg_class cl
            LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid AND des.classoid='pg_class'::regclass)
            WHERE relkind = 'S' AND relnamespace  = 2200::oid
            AND cl.oid = 24603::oid )) d
        ) d
    LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
    LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
GROUP BY g.rolname, gt.rolname
ORDER BY grantee

(四)删除

请求参数:

gid=1
sid=1
scid=2200
seid=24603
data={'ids': [24603]}

pg模板:

DROP SEQUENCE IF EXISTS {{ conn|qtIdent(data.schema) }}.{{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};

实际执行:先根据seid查出name等信息,再删除:

SELECT
    cl.oid as oid,
    cl.relname as name,
    nsp.nspname as schema,
    pg_catalog.pg_get_userbyid(cl.relowner) AS seqowner,
    description as comment,
    pg_catalog.array_to_string(cl.relacl::text[], ', ') as acl,
    (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=cl.oid) AS securities,
    depcl.relname AS owned_table,
    att.attname AS owned_column
FROM pg_catalog.pg_class cl
    LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON cl.relnamespace = nsp.oid
    LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid
        AND des.classoid='pg_class'::regclass)
	LEFT OUTER JOIN pg_catalog.pg_depend dep ON (dep.objid=cl.oid and deptype = 'a')
	LEFT JOIN pg_catalog.pg_attribute att ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
	LEFT JOIN pg_catalog.pg_class depcl ON depcl.oid = att.attrelid
WHERE cl.relkind = 'S' AND cl.relnamespace  = 2200::oid
AND cl.oid = 24603::oid ORDER BY cl.relname


DROP SEQUENCE IF EXISTS public.test;

二十一,排序规则

(一)查询

请求参数:

gid=1
sid=1
scid=2200

pg模板:

SELECT c.oid, c.collname AS name
FROM pg_catalog.pg_collation c
{% if scid %}
WHERE c.collnamespace = {{scid}}::oid
{% elif coid %}
WHERE c.oid = {{coid}}::oid
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY c.collname;

实际执行:

SELECT c.oid, c.collname AS name
FROM pg_catalog.pg_collation c
WHERE c.collnamespace = 2200::oid
ORDER BY c.collname;

二十二,域

8.18. 域类型

(一)查询

在这里插入图片描述

请求参数:

gid=1
sid=1
did=13799
scid=2200

pg模板:

SELECT
    d.oid, d.typname as name, pg_catalog.pg_get_userbyid(d.typowner) as owner,
    bn.nspname as basensp
FROM
    pg_catalog.pg_type d
JOIN
    pg_catalog.pg_type b ON b.oid = d.typbasetype
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
{% if scid is defined %}
WHERE
    d.typnamespace = {{scid}}::oid
{% elif doid %}
WHERE d.oid = {{doid}}::oid
{% endif %}
{% if schema_diff %}
    AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
        WHERE objid = d.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
{% endif %}
ORDER BY
    d.typname;

实际执行:

SELECT
    d.oid, d.typname as name, pg_catalog.pg_get_userbyid(d.typowner) as owner,
    bn.nspname as basensp
FROM
    pg_catalog.pg_type d
JOIN
    pg_catalog.pg_type b ON b.oid = d.typbasetype
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
WHERE
    d.typnamespace = 2200::oid
ORDER BY
    d.typname;

(二)创建

1,常规标签

pgadmin4树节点增删查_第79张图片

2,定义标签

pgadmin4树节点增删查_第80张图片

3,约束标签

pgadmin4树节点增删查_第81张图片

4,安全标签

pgadmin4树节点增删查_第82张图片

5,点击保存

请求参数:

gid=1
sid=1
did=13799
scid=2200
data={'basensp': 'public', 'basetype': 'integer', 'constraints': [{'conname': 'posint_check', 'consrc': 'VALUE > 0', 'convalidated': True}], 'name': 'posint', 'owner': 'postgres', 'schema': 'public', 'seclabels': [], 'typnotnull': True}

pg模板:

{% import 'macros/schemas/security.macros' as SECLABEL %}
{% if data %}
CREATE DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
    AS {{ conn|qtTypeIdent(data.basetype) }}{% if data.typlen %}({{data.typlen}}{% if data.precision %},{{data.precision}}{% endif %}){% endif %}{% if data.collname and data.collname != "pg_catalog.\"default\"" %}

    COLLATE {{ data.collname }}{% endif %}{% if data.typdefault %}

    DEFAULT {{ data.typdefault }}{% endif %}{% if data.typnotnull %}

    NOT NULL{% endif %};

{% if data.owner %}
ALTER DOMAIN {{ conn|qtIdent(data.basensp, data.name) }} OWNER TO {{ conn|qtIdent(data.owner) }};{% endif %}

{% if data.constraints %}
{% for c in data.constraints %}{% if c.conname and c.consrc %}

ALTER DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
    ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
{% if c.description %}

COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
    IS '{{ c.description }}';
{% endif %}
{% endfor -%}
{% endif %}

{% if data.description %}
COMMENT ON DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
    IS '{{ data.description }}';{% endif -%}

{% if data.seclabels %}
{% for r in data.seclabels %}
{% if r.label and r.provider %}

SECURITY LABEL{% if r.provider and r.provider != '' %} FOR {{ conn|qtIdent(r.provider) }}{% endif %} ON 'DOMAIN' {{ conn|qtIdent(data.basensp, data.name) }} IS {{ r.label|qtLiteral }};
{% endfor -%}
{% endif -%}

{% endif -%}

实际执行:

CREATE DOMAIN public.posint
    AS integer
    NOT NULL;

ALTER DOMAIN public.posint OWNER TO postgres;

ALTER DOMAIN public.posint
    ADD CONSTRAINT posint_check CHECK (VALUE > 0);

(三)属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
doid=24600

pg模板:

SELECT
    d.oid, d.typname as name, d.typbasetype, pg_catalog.format_type(b.oid,NULL) as basetype, pg_catalog.pg_get_userbyid(d.typowner) as owner,
    c.oid AS colloid, pg_catalog.format_type(b.oid, d.typtypmod) AS fulltype,
    CASE WHEN length(cn.nspname::text) > 0 AND length(c.collname::text) > 0 THEN
    pg_catalog.concat(cn.nspname, '."', c.collname,'"')
    ELSE '' END AS collname,
    d.typtypmod, d.typnotnull, d.typdefault, d.typndims, d.typdelim, bn.nspname as basensp,
    description, (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=d.typname) > 1 AS domisdup,
    (SELECT COUNT(1) FROM pg_catalog.pg_type t3 WHERE t3.typname=b.typname) > 1 AS baseisdup,
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
    FROM
        pg_catalog.pg_seclabel sl1
    WHERE
        sl1.objoid=d.oid) AS seclabels
FROM
    pg_catalog.pg_type d
JOIN
    pg_catalog.pg_type b ON b.oid = d.typbasetype
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=d.oid AND des.classoid='pg_type'::regclass)
LEFT OUTER JOIN
    pg_catalog.pg_collation c ON d.typcollation=c.oid
LEFT OUTER JOIN
    pg_catalog.pg_namespace cn ON c.collnamespace=cn.oid
WHERE
    d.typnamespace = {{scid}}::oid
{% if doid %}
  AND d.oid={{doid}}::oid
{% endif %}
ORDER BY
    d.typname;

实际执行:

SELECT
    d.oid, d.typname as name, d.typbasetype, pg_catalog.format_type(b.oid,NULL) as basetype, pg_catalog.pg_get_userbyid(d.typowner) as owner,
    c.oid AS colloid, pg_catalog.format_type(b.oid, d.typtypmod) AS fulltype,
    CASE WHEN length(cn.nspname::text) > 0 AND length(c.collname::text) > 0 THEN
    pg_catalog.concat(cn.nspname, '."', c.collname,'"')
    ELSE '' END AS collname,
    d.typtypmod, d.typnotnull, d.typdefault, d.typndims, d.typdelim, bn.nspname as basensp,
    description, (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=d.typname) > 1 AS domisdup,
    (SELECT COUNT(1) FROM pg_catalog.pg_type t3 WHERE t3.typname=b.typname) > 1 AS baseisdup,
    (SELECT
        pg_catalog.array_agg(provider || '=' || label)
    FROM
        pg_catalog.pg_seclabel sl1
    WHERE
        sl1.objoid=d.oid) AS seclabels
FROM
    pg_catalog.pg_type d
JOIN
    pg_catalog.pg_type b ON b.oid = d.typbasetype
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=d.oid AND des.classoid='pg_type'::regclass)
LEFT OUTER JOIN
    pg_catalog.pg_collation c ON d.typcollation=c.oid
LEFT OUTER JOIN
    pg_catalog.pg_namespace cn ON c.collnamespace=cn.oid
WHERE
    d.typnamespace = 2200::oid
  AND d.oid=24600::oid
ORDER BY
    d.typname;

(四)删除

请求参数:

gid=1
sid=1
did=13799
scid=2200
doid=24600
data={'ids': [24600]}

pg模板:

{% if scid and doid %}
SELECT
    d.typname as name, bn.nspname as basensp
FROM
    pg_catalog.pg_type d
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
WHERE
    d.typnamespace = {{scid}}::oid
AND
    d.oid={{doid}}::oid;
{% endif %}

{% if name %}
DROP DOMAIN IF EXISTS {{ conn|qtIdent(basensp, name) }}{% if cascade %} CASCADE{% endif %};
{% endif %}

实际执行:

SELECT
    d.typname as name, bn.nspname as basensp
FROM
    pg_catalog.pg_type d
JOIN
    pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
WHERE
    d.typnamespace = 2200::oid
AND
    d.oid=24600::oid;

DROP DOMAIN IF EXISTS public.posint;

二十三,域约束

(一)查询

pgadmin4树节点增删查_第83张图片

请求参数:

gid=1
sid=1
did=13799
scid=2200
doid=24600

pg模板:

SELECT
    c.oid, conname AS name, typname AS relname, nspname, description,
    pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') AS consrc,
    connoinherit, convalidated, convalidated AS convalidated_p
FROM
    pg_catalog.pg_constraint c
JOIN
    pg_catalog.pg_type t ON t.oid=contypid
JOIN
    pg_catalog.pg_namespace nl ON nl.oid=typnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
{% if doid %}
WHERE
    contype = 'c' AND contypid =  {{doid}}::oid
{% if coid %}
    AND c.oid = {{ coid }}
{% endif %}
{% elif coid %}
WHERE
c.oid = {{ coid }}
{% endif %}

实际执行:

SELECT
    c.oid, conname AS name, typname AS relname, nspname, description,
    pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') AS consrc,
    connoinherit, convalidated, convalidated AS convalidated_p
FROM
    pg_catalog.pg_constraint c
JOIN
    pg_catalog.pg_type t ON t.oid=contypid
JOIN
    pg_catalog.pg_namespace nl ON nl.oid=typnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
WHERE
    contype = 'c' AND contypid =  24600::oid

(二)创建

1,常规标签

pgadmin4树节点增删查_第84张图片

2,定义标签

pgadmin4树节点增删查_第85张图片

3,点击保存

请求参数:

gid=1
sid=1
did=13799
scid=2200
doid=24600
data={'consrc': 'VALUE < 100', 'convalidated': True, 'name': 'posint_check2'}

pg模板:

{% if data and schema and domain %}
ALTER DOMAIN {{ conn|qtIdent(schema, domain) }}
    ADD CONSTRAINT {{ conn|qtIdent(data.name) }} CHECK ({{ data.consrc }}){% if not data.convalidated %}

    NOT VALID{% endif %};{% if data.description %}


COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON DOMAIN {{ conn|qtIdent(schema, domain) }}
    IS '{{ data.description }}';{% endif %}
{% endif %}

实际执行:

ALTER DOMAIN public.posint
    ADD CONSTRAINT posint_check2 CHECK (VALUE < 100);

(三)属性

请求参数:

gid=1
sid=1
did=13799
scid=2200
doid=24600
coid=24601

pg模板:

SELECT
    c.oid, conname AS name, typname AS relname, nspname, description,
    pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') AS consrc,
    connoinherit, convalidated, convalidated AS convalidated_p
FROM
    pg_catalog.pg_constraint c
JOIN
    pg_catalog.pg_type t ON t.oid=contypid
JOIN
    pg_catalog.pg_namespace nl ON nl.oid=typnamespace
LEFT OUTER JOIN
    pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
{% if doid %}
WHERE
    contype = 'c' AND contypid =  {{doid}}::oid
{% if coid %}
    AND c.oid = {{ coid }}
{% endif %}
{% elif coid %}
WHERE
c.oid = {{ coid }}
{% endif %}

实际执行:

SELECT
    c.oid, conname AS name, typname AS relname, nspname, description,
    pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true

你可能感兴趣的:(postgreSQL,sql,数据库,postgresql)