百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

PostgreSQL技术内幕19:逻辑备份工具pg_dump、pg_dumpall

liebian365 2024-11-20 18:25 20 浏览 0 评论

0.简介

上一篇文章介绍了逻辑备份和物理备份概念,主要介绍了PG的物理备份工具,本文主要介绍PG逻辑备份工具g_dump和pg_dumpall,包括其使用方法和对应的流程以及代码分析。

1. 使用方法

pg_dump可以备份单个数据库。它只会备份指定数据库的数据和结构,不包括全局对象、角色和用户定义的函数;而pg_dumpall是备份整个PostgreSQL集群,并且想要包含全局对象和角色等。其中pg_dumall就是调用的pg_dump,从下面参数看pg_dump支持更多格式的导出,而pg_dumpall只能默认导出成sql文件。

1.1 pg_dump

直接使用--help查看

pg_dump --help
pg_dump dumps a database as a text file or to other formats.

Usage:
  pg_dump [OPTION]... [DBNAME]

General options:
  -f, --file=FILENAME          output file or directory name
  -F, --format=c|d|t|p         output file format (custom, directory, tar,
                               plain text (default))
  -j, --jobs=NUM               use this many parallel jobs to dump
  -v, --verbose                verbose mode
  -V, --version                output version information, then exit
  -Z, --compress=0-9           compression level for compressed formats
  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock
  --no-sync                    do not wait for changes to be written safely to disk
  -?, --help                   show this help, then exit

Options controlling the output content:
  -a, --data-only              dump only the data, not the schema
  -b, --blobs                  include large objects in dump
  -B, --no-blobs               exclude large objects in dump
  -c, --clean                  clean (drop) database objects before recreating
  -C, --create                 include commands to create database in dump
  -E, --encoding=ENCODING      dump the data in encoding ENCODING
  -n, --schema=SCHEMA          dump the named schema(s) only
  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)
  -o, --oids                   include OIDs in dump
  -O, --no-owner               skip restoration of object ownership in
                               plain-text format
  -s, --schema-only            dump only the schema, no data
  -S, --superuser=NAME         superuser user name to use in plain-text format
  -t, --table=TABLE            dump the named table(s) only
  -T, --exclude-table=TABLE    do NOT dump the named table(s)
  -x, --no-privileges          do not dump privileges (grant/revoke)
  --binary-upgrade             for use by upgrade utilities only
  --column-inserts             dump data as INSERT commands with column names
  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting
  --disable-triggers           disable triggers during data-only restore
  --enable-row-security        enable row security (dump only content user has
                               access to)
  --exclude-table-data=TABLE   do NOT dump data for the named table(s)
  --if-exists                  use IF EXISTS when dropping objects
  --inserts                    dump data as INSERT commands, rather than COPY
  --load-via-partition-root    load partitions via the root table
  --no-comments                do not dump comments
  --no-publications            do not dump publications
  --no-security-labels         do not dump security label assignments
  --no-subscriptions           do not dump subscriptions
  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs
  --no-tablespaces             do not dump tablespace assignments
  --no-unlogged-table-data     do not dump unlogged table data
  --quote-all-identifiers      quote all identifiers, even if not key words
  --section=SECTION            dump named section (pre-data, data, or post-data)
  --serializable-deferrable    wait until the dump can run without anomalies
  --snapshot=SNAPSHOT          use given snapshot for the dump
  --strict-names               require table and/or schema include patterns to
                               match at least one entity each
  --use-set-session-authorization
                               use SET SESSION AUTHORIZATION commands instead of
                               ALTER OWNER commands to set ownership

Connection options:
  -d, --dbname=DBNAME      database to dump
  -h, --host=HOSTNAME      database server host or socket directory
  -p, --port=PORT          database server port number
  -U, --username=NAME      connect as specified database user
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
  --role=ROLENAME          do SET ROLE before dump

If no database name is supplied, then the PGDATABASE environment
variable value is used.

Report bugs to <pgsql-bugs@postgresql.org>.

1.2 pg_dumpall

也是直接使用--help查看

pg_dumpall --help
pg_dumpall extracts a PostgreSQL database cluster into an SQL script file.

Usage:
  pg_dumpall [OPTION]...

General options:
  -f, --file=FILENAME          output file name
  -v, --verbose                verbose mode
  -V, --version                output version information, then exit
  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock
  -?, --help                   show this help, then exit

Options controlling the output content:
  -a, --data-only              dump only the data, not the schema
  -c, --clean                  clean (drop) databases before recreating
  -E, --encoding=ENCODING      dump the data in encoding ENCODING
  -g, --globals-only           dump only global objects, no databases
  -o, --oids                   include OIDs in dump
  -O, --no-owner               skip restoration of object ownership
  -r, --roles-only             dump only roles, no databases or tablespaces
  -s, --schema-only            dump only the schema, no data
  -S, --superuser=NAME         superuser user name to use in the dump
  -t, --tablespaces-only       dump only tablespaces, no databases or roles
  -x, --no-privileges          do not dump privileges (grant/revoke)
  --binary-upgrade             for use by upgrade utilities only
  --column-inserts             dump data as INSERT commands with column names
  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting
  --disable-triggers           disable triggers during data-only restore
  --if-exists                  use IF EXISTS when dropping objects
  --inserts                    dump data as INSERT commands, rather than COPY
  --load-via-partition-root    load partitions via the root table
  --no-comments                do not dump comments
  --no-publications            do not dump publications
  --no-role-passwords          do not dump passwords for roles
  --no-security-labels         do not dump security label assignments
  --no-subscriptions           do not dump subscriptions
  --no-sync                    do not wait for changes to be written safely to disk
  --no-tablespaces             do not dump tablespace assignments
  --no-unlogged-table-data     do not dump unlogged table data
  --quote-all-identifiers      quote all identifiers, even if not key words
  --use-set-session-authorization
                               use SET SESSION AUTHORIZATION commands instead of
                               ALTER OWNER commands to set ownership

Connection options:
  -d, --dbname=CONNSTR     connect using connection string
  -h, --host=HOSTNAME      database server host or socket directory
  -l, --database=DBNAME    alternative default database
  -p, --port=PORT          database server port number
  -U, --username=NAME      connect as specified database user
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
  --role=ROLENAME          do SET ROLE before dump

If -f/--file is not used, then the SQL script will be written to the standard
output.

Report bugs to <pgsql-bugs@postgresql.org>

2.逻辑备份原理概述

概括地说,逻辑导出要干的事情就是连接对应数据库,读出各个数据库对象的定义和数据,此外还包括comment、服务器配置和权限控制等等,这些数据库对象定义的SQL语句会被写入到对应的dump文件中。其中可以设置只导出模式或者只导出数据,默认是导出模式和数据,这样就可以支持分步导出和恢复。而数据表数据可以选择COPY方式或者INSERT语句的方式写入备份文件中。

3.代码分析

3.1 pg_dump

主流程如下:

需要整理待导出对象的原因,一是为了处理依赖顺序,一是先组织数据库对象的基本信息(先占位,避免直接是所有数据导致占用过高)。

下面来看其中导出文件格式的不同处理,其打开输出文件,输出流为g_fout,g_fout是Archive类型,这里比较巧妙的地方就是根据不同的文件格式,会产生不同的g_fout,对应也就使用不同的.c文件独立封装了不同导出的文件格式下的处理函数,这样可以很容易地增加新的导出文件格式,提高了可维护性和扩展性。

custom

pg_backup_custom.c

导出对象存储到二进制格式的文件中

file

pg_backup_files.c

导出对象存储到指定的文件中

plain

pg_backup_null.c

导出文件到标准输出

tar

pg_backup_tar.c

以压缩文件的格式导出文件

可以查看pg_backup_archiver.h文件,其中有大量的函数指针。

typedef void (*ClosePtr) (struct _archiveHandle * AH);
typedef void (*ReopenPtr) (struct _archiveHandle * AH);
typedef void (*ArchiveEntryPtr) (struct _archiveHandle * AH, struct _tocEntry * te);
      这些函数指针,被用到了如下文件中(文件->被调用的函数):
     pg_backup_custom.c->InitArchiveFmt_Custom(ArchiveHandle *AH)
     pg_backup_null.c->InitArchiveFmt_Null(ArchiveHandle *AH)
     pg_backup_files.c->InitArchiveFmt_Files(ArchiveHandle *AH)
     pg_backup_tar.c->InitArchiveFmt_Tar(ArchiveHandle *AH)
      在数据结构ArchiveHandle中,使用了大量的函数指针,使得在初始化不同导出文件格式的Archive结构时能够为处理函数赋值为各自不同的处理函数。这样在pg_dump.c中,只要根据用户指定的文件格式的参数,就可以调用相应的处理函数,代码如下:
    /* open the output file */
    if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
    {
        /* This is used by pg_dumpall, and is not documented */
        plainText = 1;
        g_fout = CreateArchive(filename, archNull, 0, archModeAppend);
    }
    else if (pg_strcasecmp(format, "c") == 0 || pg_strcasecmp(format, "custom") == 0)
        g_fout = CreateArchive(filename, archCustom, compressLevel, archModeWrite);
    else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
    {
        /*
         * Dump files into the current directory; for demonstration only, not
         * documented.
         */
        g_fout = CreateArchive(filename, archFiles, compressLevel, archModeWrite);
    }
    else if (pg_strcasecmp(format, "p") == 0 || pg_strcasecmp(format, "plain") == 0)
    {
        plainText = 1;
        g_fout = CreateArchive(filename, archNull, 0, archModeWrite);
    }
    else if (pg_strcasecmp(format, "t") == 0 || pg_strcasecmp(format, "tar") == 0)
        g_fout = CreateArchive(filename, archTar, compressLevel, archModeWrite);
    else
    {
        write_msg(NULL, "invalid output format \"%s\" specified\n", format);
        exit(1);
    }

3.2 pg_dumpall

pg_dumpall本质上是不断调用pg_dump。

if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
                 pg_dump_bin)) < 0)
  {
    char    full_path[MAXPGPATH];

    if (find_my_exec(argv[0], full_path) < 0)
      strlcpy(full_path, progname, sizeof(full_path));

    if (ret == -1)
      fprintf(stderr,
          _("The program \"pg_dump\" is needed by %s "
            "but was not found in the\n"
            "same directory as \"%s\".\n"
            "Check your installation.\n"),
          progname, full_path);
    else
      fprintf(stderr,
          _("The program \"pg_dump\" was found by \"%s\"\n"
            "but was not the same version as %s.\n"
            "Check your installation.\n"),
          full_path, progname);
    exit_nicely(1);
  }

  pgdumpopts = createPQExpBuffer();

  while ((c = getopt_long(argc, argv, "acd:E:f:gh:l:oOp:rsS:tU:vwWx", long_options, &optindex)) != -1)
  {
    switch (c)
    {
      case 'a':
        data_only = true;
        appendPQExpBufferStr(pgdumpopts, " -a");
        break;

      case 'c':
        output_clean = true;
        break;

      case 'd':
        connstr = pg_strdup(optarg);
        break;

      case 'E':
        dumpencoding = pg_strdup(optarg);
        appendPQExpBufferStr(pgdumpopts, " -E ");
        appendShellString(pgdumpopts, optarg);
        break;

      case 'f':
        filename = pg_strdup(optarg);
        appendPQExpBufferStr(pgdumpopts, " -f ");
        appendShellString(pgdumpopts, filename);
        break;

      case 'g':
        globals_only = true;
        break;

      case 'h':
        pghost = pg_strdup(optarg);
        break;

      case 'l':
        pgdb = pg_strdup(optarg);
        break;

      case 'o':
        appendPQExpBufferStr(pgdumpopts, " -o");
        break;

      case 'O':
        appendPQExpBufferStr(pgdumpopts, " -O");
        break;

      case 'p':
        pgport = pg_strdup(optarg);
        break;

      case 'r':
        roles_only = true;
        break;

      case 's':
        appendPQExpBufferStr(pgdumpopts, " -s");
        break;

      case 'S':
        appendPQExpBufferStr(pgdumpopts, " -S ");
        appendShellString(pgdumpopts, optarg);
        break;

      case 't':
        tablespaces_only = true;
        break;

      case 'U':
        pguser = pg_strdup(optarg);
        break;

      case 'v':
        verbose = true;
        appendPQExpBufferStr(pgdumpopts, " -v");
        break;

      case 'w':
        prompt_password = TRI_NO;
        appendPQExpBufferStr(pgdumpopts, " -w");
        break;

      case 'W':
        prompt_password = TRI_YES;
        appendPQExpBufferStr(pgdumpopts, " -W");
        break;

      case 'x':
        skip_acls = true;
        appendPQExpBufferStr(pgdumpopts, " -x");
        break;

      case 0:
        break;

      case 2:
        appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
        appendShellString(pgdumpopts, optarg);
        break;

      case 3:
        use_role = pg_strdup(optarg);
        appendPQExpBufferStr(pgdumpopts, " --role ");
        appendShellString(pgdumpopts, use_role);
        break;

      case 4:
        dosync = false;
        appendPQExpBufferStr(pgdumpopts, " --no-sync");
        break;

      default:
        fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
        exit_nicely(1);
    }
  }

相关推荐

“版本末期”了?下周平衡补丁!国服最强5套牌!上分首选

明天,酒馆战棋就将迎来大更新,也聊了很多天战棋相关的内容了,趁此机会,给兄弟们穿插一篇构筑模式的卡组推荐!老规矩,我们先来看10职业胜率。目前10职业胜率排名与一周前基本类似,没有太多的变化。平衡补丁...

VS2017 C++ 程序报错“error C2065:“M_PI”: 未声明的标识符&quot;

首先,程序中头文件的选择,要选择头文件,在文件中是没有对M_PI的定义的。选择:项目——>”XXX属性"——>配置属性——>C/C++——>预处理器——>预处理器定义,...

东营交警实名曝光一批酒驾人员名单 88人受处罚

齐鲁网·闪电新闻5月24日讯酒后驾驶是对自己和他人生命安全极不负责的行为,为守护大家的平安出行路,东营交警一直将酒驾作为重点打击对象。5月23日,东营交警公布最新一批饮酒、醉酒名单。对以下驾驶人醉酒...

Qt界面——搭配QCustomPlot(qt platform)

这是我第一个使用QCustomPlot控件的上位机,通过串口精确的5ms发送一次数据,再将读取的数据绘制到图表中。界面方面,尝试卡片式设计,外加QSS简单的配了个色。QCustomPlot官网:Qt...

大话西游2分享赢取种族坐骑手办!PK趣闻录由你书写

老友相聚,仗剑江湖!《大话西游2》2021全民PK季4月激燃打响,各PK玩法鏖战齐开,零门槛参与热情高涨。PK季期间,不仅各种玩法奖励丰厚,参与PK趣闻录活动,投稿自己在PK季遇到的趣事,还有机会带走...

测试谷歌VS Code AI 编程插件 Gemini Code Assist

用ClaudeSonnet3.7的天气测试编码,让谷歌VSCodeAI编程插件GeminiCodeAssist自动编程。生成的文件在浏览器中的效果如下:(附源代码)VSCode...

顾爷想知道第4.5期 国服便利性到底需优化啥?

前段时间DNF国服推出了名为“阿拉德B计划”的系列改版计划,截至目前我们已经看到了两项实装。不过关于便利性上,国服似乎还有很多路要走。自从顾爷回归DNF以来,几乎每天都在跟我抱怨关于DNF里面各种各样...

掌握Visual Studio项目配置【基础篇】

1.前言VisualStudio是Windows上最常用的C++集成开发环境之一,简称VS。VS功能十分强大,对应的,其配置系统较为复杂。不管是对于初学者还是有一定开发经验的开发者来说,捋清楚VS...

还嫌LED驱动设计套路深?那就来看看这篇文章吧

随着LED在各个领域的不同应用需求,LED驱动电路也在不断进步和发展。本文从LED的特性入手,推导出适合LED的电源驱动类型,再进一步介绍各类LED驱动设计。设计必读:LED四个关键特性特性一:非线...

Visual Studio Community 2022(VS2022)安装图文方法

直接上步骤:1,首先可以下载安装一个VisualStudio安装器,叫做VisualStudioinstaller。这个安装文件很小,很快就安装完成了。2,打开VisualStudioins...

Qt添加MSVC构建套件的方法(qt添加c++11)

前言有些时候,在Windows下因为某些需求需要使用MSVC编译器对程序进行编译,假设我们安装Qt的时候又只是安装了MingW构建套件,那么此时我们该如何给现有的Qt添加一个MSVC构建套件呢?本文以...

Qt为什么站稳c++GUI的top1(qt c)

为什么现在QT越来越成为c++界面编程的第一选择,从事QT编程多年,在这之前做C++界面都是基于MFC。当时为什么会从MFC转到QT?主要原因是MFC开发界面想做得好看一些十分困难,引用第三方基于MF...

qt开发IDE应该选择VS还是qt creator

如果一个公司选择了qt来开发自己的产品,在面临IDE的选择时会出现vs或者qtcreator,选择qt的IDE需要结合产品需求、部署平台、项目定位、程序猿本身和公司战略,因为大的软件产品需要明确IDE...

Qt 5.14.2超详细安装教程,不会来打我

Qt简介Qt(官方发音[kju:t],音同cute)是一个跨平台的C++开库,主要用来开发图形用户界面(GraphicalUserInterface,GUI)程序。Qt是纯C++开...

Cygwin配置与使用(四)——VI字体和颜色的配置

简介:VI的操作模式,基本上VI可以分为三种状态,分别是命令模式(commandmode)、插入模式(Insertmode)和底行模式(lastlinemode),各模式的功能区分如下:1)...

取消回复欢迎 发表评论: