
    VhP                         d dl mZmZmZ eZdZdZdZd dl	m
Z
 d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZmZmZ g Zd
ZdZdZd Zd Zd Zd Zd Z d Z!d Z"d Z#d Z$e%dk(  r e$        yy)    )absolute_importdivisionprint_functiona  
---
module: postgresql_set
short_description: Change a PostgreSQL server configuration parameter
description:
   - "IMPORTANT: If your PostgreSQL server version is 14 or later,
     use the M(community.postgresql.postgresql_alter_system) module instead as it will
     replace this module in future."
   - Allows to change a PostgreSQL server configuration parameter.
   - The module uses ALTER SYSTEM command and applies changes by reload server configuration.
   - ALTER SYSTEM is used for changing server configuration parameters across the entire database cluster.
   - It can be more convenient and safe than the traditional method of manually editing the postgresql.conf file.
   - ALTER SYSTEM writes the given parameter setting to the $PGDATA/postgresql.auto.conf file,
     which is read in addition to postgresql.conf.
   - The module allows to reset parameter to boot_val (cluster initial value) by I(reset=true) or remove parameter
     string from postgresql.auto.conf and reload I(value=default) (for settings with postmaster context restart is required).
   - After change you can see in the ansible output the previous and
     the new parameter value and other information using returned values and M(ansible.builtin.debug) module.
options:
  name:
    description:
    - Name of PostgreSQL server parameter. Pay attention that parameters are case sensitive (see examples below).
    type: str
    required: true
  value:
    description:
    - Parameter value to set.
    - To remove parameter string from postgresql.auto.conf and
      reload the server configuration you must pass I(value=default).
      With I(value=default) the playbook always returns changed is true.
    type: str
  reset:
    description:
    - Restore parameter to initial state (boot_val). Mutually exclusive with I(value).
    type: bool
    default: false
  session_role:
    description:
    - Switch to session_role after connecting. The specified session_role must
      be a role that the current login_user is a member of.
    - Permissions checking for SQL commands is carried out as though
      the session_role were the one that had logged in originally.
    type: str
  login_db:
    description:
    - Name of database to connect.
    - The V(db) alias is deprecated and will be removed in version 5.0.0.
    type: str
    aliases:
    - db
  trust_input:
    description:
    - If C(false), check whether values of parameters are potentially dangerous.
    - It makes sense to use C(false) only when SQL injections are possible.
    type: bool
    default: true
    version_added: '0.2.0'

notes:
- Supported version of PostgreSQL is 9.4 and later.
  For PostgreSQL version 14 or later, the M(community.postgresql.postgresql_alter_system) module is recommended.
- Pay attention, change setting with 'postmaster' context can return changed is true
  when actually nothing changes because the same value may be presented in
  several different form, for example, 1024MB, 1GB, etc. However in pg_settings
  system view it can be defined like 131072 number of 8kB pages.
  The final check of the parameter value cannot compare it because the server was
  not restarted and the value in pg_settings is not updated yet.
- For some parameters restart of PostgreSQL server is required.
  See official documentation U(https://www.postgresql.org/docs/current/view-pg-settings.html).

attributes:
  check_mode:
    support: full

seealso:
- module: community.postgresql.postgresql_alter_system
- module: community.postgresql.postgresql_info
- name: PostgreSQL server configuration
  description: General information about PostgreSQL server configuration.
  link: https://www.postgresql.org/docs/current/runtime-config.html
- name: PostgreSQL view pg_settings reference
  description: Complete reference of the pg_settings view documentation.
  link: https://www.postgresql.org/docs/current/view-pg-settings.html
- name: PostgreSQL ALTER SYSTEM command reference
  description: Complete reference of the ALTER SYSTEM command documentation.
  link: https://www.postgresql.org/docs/current/sql-altersystem.html

author:
- Andrew Klychkov (@Andersson007)
- Daniele Giudice (@RealGreenDragon)

extends_documentation_fragment:
- community.postgresql.postgres
ah  
- name: Restore wal_keep_segments parameter to initial state
  community.postgresql.postgresql_set:
    name: wal_keep_segments
    reset: true

# Set work_mem parameter to 32MB and show what's been changed and restart is required or not
# (output example: "msg": "work_mem 4MB >> 64MB restart_req: False")
- name: Set work mem parameter
  community.postgresql.postgresql_set:
    name: work_mem
    value: 32mb
  register: set

- name: Print the result if the setting changed
  ansible.builtin.debug:
    msg: "{{ set.name }} {{ set.prev_val_pretty }} >> {{ set.value_pretty }} restart_req: {{ set.restart_required }}"
  when: set.changed
# Ensure that the restart of PostgreSQL server must be required for some parameters.
# In this situation you see the same parameter in prev_val_pretty and value_pretty, but 'changed=True'
# (If you passed the value that was different from the current server setting).

- name: Set log_min_duration_statement parameter to 1 second
  community.postgresql.postgresql_set:
    name: log_min_duration_statement
    value: 1s

- name: Set wal_log_hints parameter to default value (remove parameter from postgresql.auto.conf)
  community.postgresql.postgresql_set:
    name: wal_log_hints
    value: default

- name: Set TimeZone parameter (careful, case sensitive)
  community.postgresql.postgresql_set:
    name: TimeZone
    value: 'Europe/Paris'
an  
name:
  description: Name of PostgreSQL server parameter.
  returned: success
  type: str
  sample: 'shared_buffers'
restart_required:
  description: Information about parameter current state.
  returned: success
  type: bool
  sample: true
prev_val_pretty:
  description: Information about previous state of the parameter.
  returned: success
  type: str
  sample: '4MB'
value_pretty:
  description: Information about current state of the parameter.
  returned: success
  type: str
  sample: '64MB'
value:
  description:
  - Dictionary that contains the current parameter value (at the time of playbook finish).
  - Pay attention that for real change some parameters restart of PostgreSQL server is required.
  - Returns the current value in the check mode.
  returned: success
  type: dict
  sample: { "value": 67108864, "unit": "b" }
context:
  description:
  - PostgreSQL setting context.
  returned: success
  type: str
  sample: user
queries:
  description:
  - List of executed DML queries.
  returned: success
  type: list
  elements: str
  sample: ["ALTER SYSTEM SET shared_preload_libraries = ''"]
  version_added: '3.7.0'
)deepcopy)	to_native)AnsibleModule)check_input)connect_to_dbensure_required_libsget_conn_paramsget_server_versionpg_cursor_argspostgres_common_argument_spec a )mbgbtb))" )local_preload_librariessearch_pathsession_preload_librariesshared_preload_librariestemp_tablespacesunix_socket_directories)r   )r   r   r   r   r   c                 6    t         D ]  \  }}| |k\  s||v c S  y)NF)PARAMETERS_GUC_LIST_QUOTE)server_versionnameguc_list_quote_verguc_list_quote_paramss       w/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_set.pyparam_is_guc_list_quoter"      s2    5N 111//0001     c                     dj                  | j                  d      D cg c]  }|j                  d       c}      S c c}w )Nz, ,z" )joinsplitstrip)valuevs     r!   param_guc_list_unquoter+      s2     99U[[-=>aggdm>??>s   >c           	         d}	 | j                  |d|i       | j                         }| j                  d|z         | j                         }s|j                  d|z         |   }|d   }	|d	   }
|d
   }|d   }|dk(  rd}n|dk(  rd}|
dk(  r;t        |	      dkD  rt        |	      dz  }	t        |      dkD  rt        |      dz  }d}
nE|
dk(  r@t        |	      dkD  rt        |	      dz  dz  }	t        |      dkD  rt        |      dz  dz  }d}
|rt        |      }t        |	      }	||	|
||dS # t        $ r,}|j                  d|dt	        |             Y d }~d }~ww xY w)NzTSELECT name, setting, unit, context, boot_val FROM pg_settings WHERE name = %(name)sr   zSHOW %szUnable to get z value due to : msgzNo such parameter: %s. Please check its spelling or presence in your PostgreSQL version (https://www.postgresql.org/docs/current/runtime-config.html)settingunitcontextboot_valTrueonFalseoffkBr      bMB)current_valraw_valr0   r2   r1   )executefetchone	Exception	fail_jsonr   intr+   )cursormoduler   is_guc_list_quotequeryinfovaler;   r<   r0   r1   r2   s                r!   	param_getrI      s   6EZuvtn- y4'(oo
  ]_cd 	e d)K9oG<D9oGJHf		t|w<!'lT)Gx=18}t+H	w<!'lT)D0Gx=18}t+d2H,[9(1 # O  ZT9UV<XYYZs   AD0 0	E%9!E  E%c                 ,   | s| S | d   j                         s| S | d   j                         s	 t        |       } | S g }| D ]%  }|j                         s n|j                  |       ' t        dj                  |            }d }t        |       dk\  rEd| dd  v r|dz  }n8d| dd  v r	|dz  dz  }n(d	| dd  v r|dz  dz  dz  }nd
| dd  v r|dz  dz  dz  dz  }|s	d| d   v r|}||S | S # t        $ r# 	 t	        |       } Y | S # t        $ r | cY cY S w xY ww xY w)Nr       r7   r8   r:   GBTBB)isdigitisalpharA   
ValueErrorfloatappendr&   len)
pretty_valnum_partcval_in_bytess       r!   pretty_to_bytesr\   3  s     a=  " b>!!#	"ZJ  H  yy{OOA 2778$%HL
:!:bc?"#d?LZ_$#d?T1LZ_$#d?T1D8LZ_$#d?T1D84?L C:b>1W  	""":.

   "!!"		"s)   C' '	D1C??D
DDDc                 4   t        |t              rjd|v rf|j                  d      sU|dk  r|dk(  sKdj                  |j	                  d      D cg c]  }d|j                         z   dz    c}      }d|d|}n	d|d|d}d	}t        | ||||      S c c}w )
Nr%   )_command_prefixr   r   'zALTER SYSTEM SET z = z = 'z"Unable to set %s value due to : %s)
isinstancestrendswithr&   r'   r(   exec_set_sql)rB   rC   r   r)   r   elemrE   fail_msgs           r!   	param_setrg   u  s    %#,56&(T5N-N u{{3?OPt#

,s2PQ.2E:04e<3HtX>> Qs   Bc                 .    d|z  }d}t        | ||||      S )NzALTER SYSTEM SET %s = DEFAULTz.Unable to set default value for %s due to : %srd   rB   rC   r   rE   rf   s        r!   param_set_defaultrk     s$    +d2E?HtX>>r#   c                 .    d|z  }d}t        | ||||      S )NzALTER SYSTEM RESET %szUnable to reset %s due to : %sri   rj   s        r!   param_resetrm     s$    #d*E/HtX>>r#   c                     	 t         j                  |       | j                  |       y# t        $ r*}|j	                  ||t        |      fz         Y d }~yd }~ww xY w)Nr-   T)executed_queriesrV   r=   r?   r@   r   )rB   rC   rE   setting_namerf   rH   s         r!   rd   rd     s`    F&u   FXy|(DDEEFs   &) 	A AAc                  ^	   t               } | j                  t        dd      t        ddgddddg      t        d	      t        d
d      t        d	      t        d
d             t        | d      }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|st        ||||       |rut        |      dkD  r/|d d j                         r|dd  t        v r|j                         }n8t        |      dkD  r*d|d   v r#|d d j                         r|j                         }|dk(  r|dk(  rd}|j                  |       ||r|j                  d|z         ||s|j                  d|z         t        |       t        ||j                  d      }t        ||d       \  }	}
 |	j                  d;i t        }i }t!        |	      }|t"        k  rV|j%                  d!|d"t"        d#       t        ddddddd$%      }||d<   |	j'                           |j(                  d;i | t+        ||      }d}d}||d<   d|d&<   t-        ||||      }|d'   }|d(   }|d)   }|d*   }|d+   }|d,k(  rd-}n|d.k(  rd/}||d0<   t/        |d0         |d1<   ||d+<   |d2k(  r|j                  d3|z         |d4k(  rd}|j0                  rWt3        |      t3        |      k(  rd|d5<   n
||d1<   d|d5<   t        ||$      |d<   ||d&<   t4        |d6<    |j(                  d;i | |-||k7  r(|d7k(  rt7        |||      }nt9        |||||      }||d1<   n?|r=||k(  r+t        ||$      |d<   t4        |d6<    |j(                  d;i | t;        |||      }|j0                  s|r|d4k7  r|j=                  d8       |j'                          |	j'                          |d9v r~t        ||d       \  }	}
 |	j                  d;i t        }t-        ||||      }|d'   }|d(   }||k(  rd}nd}||d1<   t        ||$      |d<   |j'                          |	j'                          ||d5<   ||d&<   t4        |d6<   |r|r|j%                  d:|z          |j(                  d;i | y )<Nrb   T)typerequireddbz5.0.0zcommunity.postgresql)r   versioncollection_name)rr   aliasesdeprecated_aliases)rr   boolF)rr   default)r   login_dbr)   resetsession_roletrust_input)argument_specsupports_check_moder   r)   r|   r}   r~   rM   rN      r9   rK   r   rL   a  Due to a PostgreSQL bug in resetting shared_preload_libraries with ALTER SYSTEM SET, setting it as an empty string is not supported by the module to avoid crashes. Use the `value: default` or `reset: true` argument instead. If you think the bug has been fixed, please let us know.r-   z1%s: value and reset params are mutually exclusivez:%s: at least one of value or reset param must be specified)warn_db_default)
autocommitzPostgreSQL is z version but z or later is required)r)   r0   )changedrestart_requiredvalue_prettyprev_val_prettyr)   r   r;   r<   r0   r2   r1   r3   r4   r5   r6   r   r   internalzp%s: cannot be changed (internal context). See https://www.postgresql.org/docs/current/runtime-config-preset.html
postmasterr   queriesrz   zSELECT pg_reload_conf())sighupzsuperuser-backendbackend	superuseruserz0Restart of PostgreSQL is required for setting %s )r   updatedictr   paramsr	   rW   rR   LOWERCASE_SIZE_UNITSupperr@   r   r   r
   rB   r   r   
PG_REQ_VERwarnclose	exit_jsonr"   rI   r   
check_moder\   ro   rk   rg   rm   r=   )r   rC   r   r)   r|   r}   r~   r.   conn_paramsdb_connectiondummyrB   kwverrD   r   r   resr;   r<   r0   r2   r1   f_value	f_raw_vals                            r!   mainr     sw   13Mut,54&"#9F 
 .u%fd3   # F
 == DMM'"EMM'"E==0L--.KFD%6u:>eCRj002uRSzEY7YKKME Z!^b	!1eCRj6H6H6JKKME))erkJ
 	S!UPSWWX}UY\``a  !&&--OK(NM5!]!!3N3F	B
]
+C
ZcS]^_"+
 6
2 0T: GBvJ"B FFD*;
<Cm$K)nGv;D:H)nG	'	'B!"%6"78B~ByM * bdhi 	j , 5!_[%AA!ByM "'B~ ByM 
7 "2(92 Uk1I'=GeSAG"> 
hBwK -ByMF"r"ffd3 W-D01
LLN QQ,V[TRu%%%77.?@m$	N	iG G$>
7
 	ByM-B$ByMGFMNFrr#   __main__N)&
__future__r   r   r   rr   __metaclass__DOCUMENTATIONEXAMPLESRETURNcopyr   ansible.module_utils._textr   ansible.module_utils.basicr   Fansible_collections.community.postgresql.plugins.module_utils.databaser	   Fansible_collections.community.postgresql.plugins.module_utils.postgresr
   r   r   r   r   r   ro   r   r   r   r"   r+   rI   r\   rg   rk   rm   rd   r   __name__r   r#   r!   <module>r      s    A @]~$L+
Z  0 4   
 *  0@6r?D?(??}@ zF r#   