PostgreSQL 常用维护操作(三)
PostgreSQL配置文件的修改方法:1. 配置文件所在路径:
$ pwd/opt/postgresql/data$ ll总用量 1332drwx------ 8 postgres dba 40967月 13 10:50 basedrwx------ 2 postgres dba 40967月 19 03:42 global-rw------- 1 postgres dba 11813577月 17 16:17 gmon.outdrwx------159 postgres dba 40967月 19 03:44 gprofdrwx------ 2 postgres dba 40967月9 09:42 pg_clog-rw------- 1 postgres dba 37557月9 14:54 pg_hba.conf-rw------- 1 postgres dba 16317月9 09:42 pg_ident.confdrwx------ 4 postgres dba 40967月9 09:42 pg_multixactdrwx------ 2 postgres dba 40967月 19 05:57 pg_stat_tmpdrwx------ 2 postgres dba 40967月9 09:42 pg_subtransdrwx------ 2 postgres dba 40967月 13 10:54 pg_tblspcdrwx------ 2 postgres dba 40967月9 09:42 pg_twophase-rw------- 1 postgres dba 47月9 09:42 PG_VERSIONdrwx------ 3 postgres dba 40967月9 09:42 pg_xlog-rw------- 1 postgres dba 168377月9 14:52 postgresql.conf-rw------- 1 postgres dba 168157月9 14:51 postgresql.conf_duanyx_bak-rw------- 1 postgres dba 297月 19 03:42 postmaster.opts-rw------- 1 postgres dba 467月 19 03:42 postmaster.pid$
2. SQL方式修改,可以在运行时设置,当然只有于部分选项,使用方法如下:
kevin_test=# SET work_mem = '16MB';SETkevin_test=#kevin_test=# SELECT * FROM pg_settings WHERE source = 'session';-[ RECORD 1 ]---------------------------------------------------------------------------------------------------------------------name | work_memsetting | 16384unit | kBcategory | Resource Usage / Memoryshort_desc | Sets the maximum memory to be used for query workspaces.extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.context | uservartype | integersource | sessionmin_val | 64max_val | 2097151enumvals |boot_val | 1024reset_val| 1024sourcefile |sourceline |kevin_test=#
恢复默认设置的方法:
kevin_test=# RESET work_mem;RESETkevin_test=# SELECT * FROM pg_settings WHERE name = 'work_mem';-[ RECORD 1 ]---------------------------------------------------------------------------------------------------------------------name | work_memsetting | 1024unit | kBcategory | Resource Usage / Memoryshort_desc | Sets the maximum memory to be used for query workspaces.extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.context | uservartype | integersource | defaultmin_val | 64max_val | 2097151enumvals |boot_val | 1024reset_val| 1024sourcefile |sourceline |kevin_test=#
3.查看配置项的值,当然你可以看接查看postgre.conf文件的内容,不过最好使用SQL方法查看和修改,更为快速,当然你要先知道要查看的选项的名称。
kevin_test=# SHOW work_mem;work_mem----------1MB(1 row)kevin_test=#
补充一下,如果确实不知道选项的名了,可以先查一下,这些均存储在pg_settings表中,呵呵,PostgreSQL的一个特点就在这,所有数据均由数据库自己维护。
kevin_test=# SELECT name, short_desc FROM pg_settings;name | short_desc---------------------------------+-------------------------------------------------------------------------------------------------------------------------------add_missing_from | Automatically adds missing table references to FROM clauses.allow_system_table_mods | Allows modifications of the structure of system tables.archive_command | Sets the shell command that will be called to archive a WAL file.archive_mode | Allows archiving of WAL files using archive_command.archive_timeout | Forces a switch to the next xlog file if a new file has not been started within N seconds.array_nulls | Enable input of NULL elements in arrays.authentication_timeout | Sets the maximum allowed time to complete client authentication.autovacuum | Starts the autovacuum subprocess.autovacuum_analyze_scale_factor | Number of tuple inserts, updates or deletes prior to analyze as a fraction of reltuples.autovacuum_analyze_threshold | Minimum number of tuple inserts, updates or deletes prior to analyze.autovacuum_freeze_max_age | Age at which to autovacuum a table to prevent transaction ID wraparound.autovacuum_max_workers | Sets the maximum number of simultaneously running autovacuum worker processes.autovacuum_naptime | Time to sleep between autovacuum runs.autovacuum_vacuum_cost_delay | Vacuum cost delay in milliseconds, for autovacuum.autovacuum_vacuum_cost_limit | Vacuum cost amount available before napping, for autovacuum.autovacuum_vacuum_scale_factor| Number of tuple updates or deletes prior to vacuum as a fraction of reltuples.autovacuum_vacuum_threshold | Minimum number of tuple updates or deletes prior to vacuum.backslash_quote | Sets whether "\'" is allowed in string literals.bgwriter_delay | Background writer sleep time between rounds.bgwriter_lru_maxpages | Background writer maximum number of LRU pages to flush per round.bgwriter_lru_multiplier | Multiple of the average buffer usage to free per round.block_size | Shows the size of a disk block.bonjour_name | Sets the Bonjour broadcast service name.check_function_bodies | Check function bodies during CREATE FUNCTION.checkpoint_completion_target | Time spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval.checkpoint_segments | Sets the maximum distance in log segments between automatic WAL checkpoints.checkpoint_timeout | Sets the maximum time between automatic WAL checkpoints.checkpoint_warning | Enables warnings if checkpoint segments are filled more frequently than this.client_encoding | Sets the client's character set encoding.client_min_messages | Sets the message levels that are sent to the client.commit_delay | Sets the delay in microseconds between transaction commit and flushing WAL to disk.commit_siblings | Sets the minimum concurrent open transactions before performing commit_delay.config_file | Sets the server's main configuration file.constraint_exclusion | Enables the planner to use constraints to optimize queries.cpu_index_tuple_cost | Sets the planner's estimate of the cost of processing each index entry during an index scan.cpu_operator_cost | Sets the planner's estimate of the cost of processing each operator or function call.cpu_tuple_cost | Sets the planner's estimate of the cost of processing each tuple (row).cursor_tuple_fraction | Sets the planner's estimate of the fraction of a cursor's rows that will be retrieved.custom_variable_classes | Sets the list of known custom variable classes.data_directory | Sets the server's data directory.DateStyle | Sets the display format for date and time values.db_user_namespace | Enables per-database user names.deadlock_timeout | Sets the time to wait on a lock before checking for deadlock.debug_assertions | Turns on various assertion checks.debug_pretty_print | Indents parse and plan tree displays.debug_print_parse | Logs each query's parse tree.debug_print_plan | Logs each query's execution plan.debug_print_rewritten | Logs each query's rewritten parse tree.default_statistics_target | Sets the default statistics target.default_tablespace | Sets the default tablespace to create tables and indexes in.default_text_search_config | Sets default text search configuration.default_transaction_isolation | Sets the transaction isolation level of each new transaction.default_transaction_read_only | Sets the default read-only status of new transactions.default_with_oids | Create new tables with OIDs by default.dynamic_library_path | Sets the path for dynamically loadable modules.effective_cache_size | Sets the planner's assumption about the size of the disk cache.effective_io_concurrency | Number of simultaneous requests that can be handled efficiently by the disk subsystem.enable_bitmapscan | Enables the planner's use of bitmap-scan plans.enable_hashagg | Enables the planner's use of hashed aggregation plans.enable_hashjoin | Enables the planner's use of hash join plans.enable_indexscan | Enables the planner's use of index-scan plans.enable_mergejoin | Enables the planner's use of merge join plans.enable_nestloop | Enables the planner's use of nested-loop join plans.enable_seqscan | Enables the planner's use of sequential-scan plans.enable_sort | Enables the planner's use of explicit sort steps.enable_tidscan | Enables the planner's use of TID scan plans.escape_string_warning | Warn about backslash escapes in ordinary string literals.external_pid_file | Writes the postmaster PID to the specified file.extra_float_digits | Sets the number of digits displayed for floating-point values.from_collapse_limit | Sets the FROM-list size beyond which subqueries are not collapsed.fsync | Forces synchronization of updates to disk.full_page_writes | Writes full pages to WAL when first modified after a checkpoint.geqo | Enables genetic query optimization.geqo_effort | GEQO: effort is used to set the default for other GEQO parameters.geqo_generations | GEQO: number of iterations of the algorithm.geqo_pool_size | GEQO: number of individuals in the population.geqo_selection_bias | GEQO: selective pressure within the population.geqo_threshold | Sets the threshold of FROM items beyond which GEQO is used.gin_fuzzy_search_limit | Sets the maximum allowed result for exact search by GIN.hba_file | Sets the server's "hba" configuration file.ident_file | Sets the server's "ident" configuration file.ignore_system_indexes | Disables reading from system indexes.integer_datetimes | Datetimes are integer based.IntervalStyle | Sets the display format for interval values.join_collapse_limit | Sets the FROM-list size beyond which JOIN constructs are not flattened.krb_caseins_users | Sets whether Kerberos and GSSAPI user names should be treated as case-insensitive.krb_server_keyfile | Sets the location of the Kerberos server key file.krb_srvname | Sets the name of the Kerberos service.lc_collate | Shows the collation order locale.lc_ctype | Shows the character classification and case conversion locale.lc_messages | Sets the language in which messages are displayed.lc_monetary | Sets the locale for formatting monetary amounts.lc_numeric | Sets the locale for formatting numbers.lc_time | Sets the locale for formatting date and time values.listen_addresses | Sets the host name or IP address(es) to listen to.local_preload_libraries | Lists shared libraries to preload into each backend.log_autovacuum_min_duration | Sets the minimum execution time above which autovacuum actions will be logged.log_checkpoints | Logs each checkpoint.log_connections | Logs each successful connection.log_destination | Sets the destination for server log output.log_directory | Sets the destination directory for log files.log_disconnections | Logs end of a session, including duration.log_duration | Logs the duration of each completed SQL statement.log_error_verbosity | Sets the verbosity of logged messages.log_executor_stats | Writes executor performance statistics to the server log.log_filename | Sets the file name pattern for log files.log_hostname | Logs the host name in the connection logs.log_line_prefix | Controls information prefixed to each log line.log_lock_waits | Logs long lock waits.log_min_duration_statement | Sets the minimum execution time above which statements will be logged.log_min_error_statement | Causes all statements generating error at or above this level to be logged.log_min_messages | Sets the message levels that are logged.log_parser_stats | Writes parser performance statistics to the server log.log_planner_stats | Writes planner performance statistics to the server log.log_rotation_age | Automatic log file rotation will occur after N minutes.log_rotation_size | Automatic log file rotation will occur after N kilobytes.log_statement | Sets the type of statements logged.log_statement_stats | Writes cumulative performance statistics to the server log.log_temp_files | Log the use of temporary files larger than this number of kilobytes.log_timezone | Sets the time zone to use in log messages.log_truncate_on_rotation | Truncate existing log files of same name during log rotation.logging_collector | Start a subprocess to capture stderr output and/or csvlogs into log files.maintenance_work_mem | Sets the maximum memory to be used for maintenance operations.max_connections | Sets the maximum number of concurrent connections.max_files_per_process | Sets the maximum number of simultaneously open files for each server process.max_function_args | Shows the maximum number of function arguments.max_identifier_length | Shows the maximum identifier length.max_index_keys | Shows the maximum number of index keys.max_locks_per_transaction | Sets the maximum number of locks per transaction.max_prepared_transactions | Sets the maximum number of simultaneously prepared transactions.max_stack_depth | Sets the maximum stack depth, in kilobytes.password_encryption | Encrypt passwords.port | Sets the TCP port the server listens on.post_auth_delay | Waits N seconds on connection startup after authentication.pre_auth_delay | Waits N seconds on connection startup before authentication.random_page_cost | Sets the planner's estimate of the cost of a nonsequentially fetched disk page.regex_flavor | Sets the regular expression "flavor".search_path | Sets the schema search order for names that are not schema-qualified.segment_size | Shows the number of pages per disk file.seq_page_cost | Sets the planner's estimate of the cost of a sequentially fetched disk page.server_encoding | Sets the server (database) character set encoding.server_version | Shows the server version.server_version_num | Shows the server version as an integer.session_replication_role | Sets the session's behavior for triggers and rewrite rules.shared_buffers | Sets the number of shared memory buffers used by the server.shared_preload_libraries | Lists shared libraries to preload into server.silent_mode | Runs the server silently.sql_inheritance | Causes subtables to be included by default in various commands.ssl | Enables SSL connections.standard_conforming_strings | Causes '...' strings to treat backslashes literally.statement_timeout | Sets the maximum allowed duration of any statement.stats_temp_directory | Writes temporary statistics files to the specified directory.superuser_reserved_connections| Sets the number of connection slots reserved for superusers.synchronize_seqscans | Enable synchronized sequential scans.synchronous_commit | Sets immediate fsync at commit.syslog_facility | Sets the syslog "facility" to be used when syslog enabled.syslog_ident | Sets the program name used to identify PostgreSQL messages in syslog.tcp_keepalives_count | Maximum number of TCP keepalive retransmits.tcp_keepalives_idle | Time between issuing TCP keepalives.tcp_keepalives_interval | Time between TCP keepalive retransmits.temp_buffers | Sets the maximum number of temporary buffers used by each session.temp_tablespaces | Sets the tablespace(s) to use for temporary tables and sort files.TimeZone | Sets the time zone for displaying and interpreting time stamps.timezone_abbreviations | Selects a file of time zone abbreviations.trace_notify | Generates debugging output for LISTEN and NOTIFY.trace_sort | Emit information about resource usage in sorting.track_activities | Collects information about executing commands.track_activity_query_size | Sets the size reserved for pg_stat_activity.current_query, in bytes.track_counts | Collects statistics on database activity.track_functions | Collects function-level statistics on database activity.transaction_isolation | Sets the current transaction's isolation level.transaction_read_only | Sets the current transaction's read-only status.transform_null_equals | Treats "expr=NULL" as "expr IS NULL".unix_socket_directory | Sets the directory where the Unix-domain socket will be created.unix_socket_group | Sets the owning group of the Unix-domain socket.unix_socket_permissions | Sets the access permissions of the Unix-domain socket.update_process_title | Updates the process title to show the active SQL command.vacuum_cost_delay | Vacuum cost delay in milliseconds.vacuum_cost_limit | Vacuum cost amount available before napping.vacuum_cost_page_dirty | Vacuum cost for a page dirtied by vacuum.vacuum_cost_page_hit | Vacuum cost for a page found in the buffer cache.vacuum_cost_page_miss | Vacuum cost for a page not found in the buffer cache.vacuum_freeze_min_age | Minimum age at which VACUUM should freeze a table row.vacuum_freeze_table_age | Age at which VACUUM should scan whole table to freeze tuples.wal_block_size | Shows the block size in the write ahead log.wal_buffers | Sets the number of disk-page buffers in shared memory for WAL.wal_segment_size | Shows the number of pages per write ahead log segment.wal_sync_method | Selects the method used for forcing WAL updates to disk.wal_writer_delay | WAL writer sleep time between WAL flushes.work_mem | Sets the maximum memory to be used for query workspaces.xmlbinary | Sets how binary values are to be encoded in XML.xmloption | Sets whether XML data in implicit parsing and serialization operations is to be considered as documents or content fragments.zero_damaged_pages | Continues processing past damaged page headers.(193 rows)kevin_test=#
4.记住选项值的改动并不一定对整个数据库生效,有时仅对当前session在效,在执行SET语句时,可通过LOCAL选项明确指定。
kevin_test=# SET LOCAL work_mem='16MB';SETkevin_test=# 5.查看系统中哪些选项被修改过。
kevin_test=# SELECT name, source, setting FROM pg_settingsWHERE source != 'default'AND source != 'override'ORDER BY 2, 1;name | source | setting----------------------------+----------------------+-------------------log_timezone | command line | PRCTimeZone | command line | PRCtimezone_abbreviations | command line | DefaultDateStyle | configuration file | ISO, YMDdefault_text_search_config | configuration file | pg_catalog.simplelc_messages | configuration file | zh_CN.UTF-8lc_monetary | configuration file | zh_CN.UTF-8lc_numeric | configuration file | zh_CN.UTF-8lc_time | configuration file | zh_CN.UTF-8listen_addresses | configuration file | *max_connections | configuration file | 100shared_buffers | configuration file | 3584max_stack_depth | environment variable | 2048(13 rows)kevin_test=#
页:
[1]