| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2019, Loic Blot (@nerzhul) <[email protected]> |
| 5 |
# Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
|
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r''' |
| 14 |
--- |
| 15 |
module: postgresql_publication |
| 16 |
short_description: Add, update, or remove PostgreSQL publication |
| 17 |
description: |
| 18 |
- Add, update, or remove PostgreSQL publication. |
| 19 |
options: |
| 20 |
name: |
| 21 |
description: |
| 22 |
- Name of the publication to add, update, or remove. |
| 23 |
required: true |
| 24 |
type: str |
| 25 |
login_db: |
| 26 |
description: |
| 27 |
- Name of the database to connect to and where |
| 28 |
the publication state will be changed. |
| 29 |
- The V(db) alias is deprecated and will be removed in version 5.0.0. |
| 30 |
aliases: [ db ] |
| 31 |
type: str |
| 32 |
columns: |
| 33 |
description: |
| 34 |
- List of tables and its columns to add to the publication. |
| 35 |
- If no columns are passed for table, it will be published as a whole. |
| 36 |
- Mutually exclusive with I(tables) and I(tables_in_schema). |
| 37 |
type: dict |
| 38 |
version_added: '3.8.0' |
| 39 |
rowfilters: |
| 40 |
description: |
| 41 |
- Optional dictionary of row filters to apply to I(tables) or I(columns) of the publication. |
| 42 |
- Mutually exclusive with I(tables_in_schema). |
| 43 |
type: dict |
| 44 |
version_added: '3.12.0' |
| 45 |
tables: |
| 46 |
description: |
| 47 |
- List of tables to add to the publication. |
| 48 |
- If no value is set all tables are targeted. |
| 49 |
- If the publication already exists for specific tables and I(tables) is not passed, |
| 50 |
nothing will be changed. |
| 51 |
- If you need to add all tables to the publication with the same name, |
| 52 |
drop existent and create new without passing I(tables). |
| 53 |
- Mutually exclusive with I(tables_in_schema) and I(columns). |
| 54 |
type: list |
| 55 |
elements: str |
| 56 |
tables_in_schema: |
| 57 |
description: |
| 58 |
- Specifies a list of schemas to add to the publication to replicate changes |
| 59 |
for all tables in those schemas. |
| 60 |
- If you want to remove all schemas, explicitly pass an empty list C([]). |
| 61 |
- Supported since PostgreSQL 15. |
| 62 |
- Mutually exclusive with I(tables) and I(columns). |
| 63 |
type: list |
| 64 |
elements: str |
| 65 |
version_added: '3.5.0' |
| 66 |
state: |
| 67 |
description: |
| 68 |
- The publication state. |
| 69 |
default: present |
| 70 |
choices: [ absent, present ] |
| 71 |
type: str |
| 72 |
parameters: |
| 73 |
description: |
| 74 |
- Dictionary with optional publication parameters. |
| 75 |
- Available parameters depend on PostgreSQL version. |
| 76 |
type: dict |
| 77 |
owner: |
| 78 |
description: |
| 79 |
- Publication owner. |
| 80 |
- If I(owner) is not defined, the owner will be set as I(login_user) or I(session_role). |
| 81 |
type: str |
| 82 |
cascade: |
| 83 |
description: |
| 84 |
- Drop publication dependencies. Has effect with I(state=absent) only. |
| 85 |
type: bool |
| 86 |
default: false |
| 87 |
session_role: |
| 88 |
description: |
| 89 |
- Switch to session_role after connecting. The specified session_role must |
| 90 |
be a role that the current login_user is a member of. |
| 91 |
- Permissions checking for SQL commands is carried out as though |
| 92 |
the session_role were the one that had logged in originally. |
| 93 |
type: str |
| 94 |
version_added: '0.2.0' |
| 95 |
trust_input: |
| 96 |
description: |
| 97 |
- If C(false), check whether values of parameters I(name), I(tables), I(owner), |
| 98 |
I(session_role), I(params) are potentially dangerous. |
| 99 |
- It makes sense to use C(false) only when SQL injections via the parameters are possible. |
| 100 |
type: bool |
| 101 |
default: true |
| 102 |
version_added: '0.2.0' |
| 103 |
comment: |
| 104 |
description: |
| 105 |
- Sets a comment on the publication. |
| 106 |
- To reset the comment, pass an empty string. |
| 107 |
type: str |
| 108 |
version_added: '3.3.0' |
| 109 |
|
| 110 |
notes: |
| 111 |
- PostgreSQL version must be 10 or greater. |
| 112 |
|
| 113 |
attributes: |
| 114 |
check_mode: |
| 115 |
support: full |
| 116 |
|
| 117 |
seealso: |
| 118 |
- name: CREATE PUBLICATION reference |
| 119 |
description: Complete reference of the CREATE PUBLICATION command documentation. |
| 120 |
link: https://www.postgresql.org/docs/current/sql-createpublication.html |
| 121 |
- name: ALTER PUBLICATION reference |
| 122 |
description: Complete reference of the ALTER PUBLICATION command documentation. |
| 123 |
link: https://www.postgresql.org/docs/current/sql-alterpublication.html |
| 124 |
- name: DROP PUBLICATION reference |
| 125 |
description: Complete reference of the DROP PUBLICATION command documentation. |
| 126 |
link: https://www.postgresql.org/docs/current/sql-droppublication.html |
| 127 |
author: |
| 128 |
- Loic Blot (@nerzhul) <[email protected]> |
| 129 |
- Andrew Klychkov (@Andersson007) <[email protected]> |
| 130 |
- George Spanos (@grantanplan) <[email protected]> |
| 131 |
extends_documentation_fragment: |
| 132 |
- community.postgresql.postgres |
| 133 |
''' |
| 134 |
|
| 135 |
EXAMPLES = r''' |
| 136 |
- name: Create a new publication with name "acme" targeting all tables in database "test" |
| 137 |
community.postgresql.postgresql_publication: |
| 138 |
login_db: test |
| 139 |
name: acme |
| 140 |
comment: Made by Ansible |
| 141 |
|
| 142 |
- name: Create publication "acme" publishing only prices and vehicles tables |
| 143 |
community.postgresql.postgresql_publication: |
| 144 |
name: acme |
| 145 |
tables: |
| 146 |
- prices |
| 147 |
- vehicles |
| 148 |
|
| 149 |
- name: Create publication "acme" publishing only prices table and id and name from vehicles tables |
| 150 |
community.postgresql.postgresql_publication: |
| 151 |
name: acme |
| 152 |
columns: |
| 153 |
prices: |
| 154 |
vehicles: |
| 155 |
- id |
| 156 |
- name |
| 157 |
|
| 158 |
- name: Create publication "acme" publishing id and name from vehicles tables, with a row filter |
| 159 |
community.postgresql.postgresql_publication: |
| 160 |
name: acme |
| 161 |
columns: |
| 162 |
vehicles: |
| 163 |
- id |
| 164 |
- name |
| 165 |
rowfilters: |
| 166 |
vehicles: (id > 100) |
| 167 |
|
| 168 |
- name: > |
| 169 |
Assuming publication "acme" exists, publishing id and name from vehicles table with a |
| 170 |
row filter (id > 100), remove and re-add the table to the publication, with the updated row filter |
| 171 |
community.postgresql.postgresql_publication: |
| 172 |
name: acme |
| 173 |
columns: |
| 174 |
vehicles: |
| 175 |
- id |
| 176 |
- name |
| 177 |
rowfilters: |
| 178 |
vehicles: WHERE (id > 100) AND (id < 200) |
| 179 |
|
| 180 |
- name: Create a new publication "acme" for tables in schema "myschema" |
| 181 |
community.postgresql.postgresql_publication: |
| 182 |
login_db: test |
| 183 |
name: acme |
| 184 |
tables_in_schema: myschema |
| 185 |
|
| 186 |
- name: Remove all schemas from "acme" publication |
| 187 |
community.postgresql.postgresql_publication: |
| 188 |
login_db: test |
| 189 |
name: acme |
| 190 |
tables_in_schema: [] |
| 191 |
|
| 192 |
- name: > |
| 193 |
Create publication "acme", set user alice as an owner, targeting all tables |
| 194 |
Allowable DML operations are INSERT and UPDATE only |
| 195 |
community.postgresql.postgresql_publication: |
| 196 |
name: acme |
| 197 |
owner: alice |
| 198 |
parameters: |
| 199 |
publish: 'insert,update' |
| 200 |
|
| 201 |
- name: > |
| 202 |
Assuming publication "acme" exists and there are targeted |
| 203 |
tables "prices" and "vehicles", add table "stores" to the publication |
| 204 |
community.postgresql.postgresql_publication: |
| 205 |
name: acme |
| 206 |
tables: |
| 207 |
- prices |
| 208 |
- vehicles |
| 209 |
- stores |
| 210 |
|
| 211 |
- name: Remove publication "acme" if exists in database "test" |
| 212 |
community.postgresql.postgresql_publication: |
| 213 |
login_db: test |
| 214 |
name: acme |
| 215 |
state: absent |
| 216 |
''' |
| 217 |
|
| 218 |
RETURN = r''' |
| 219 |
exists: |
| 220 |
description: |
| 221 |
- Flag indicates the publication exists or not at the end of runtime. |
| 222 |
returned: success |
| 223 |
type: bool |
| 224 |
sample: true |
| 225 |
queries: |
| 226 |
description: List of executed queries. |
| 227 |
returned: success |
| 228 |
type: str |
| 229 |
sample: [ 'DROP PUBLICATION "acme" CASCADE' ] |
| 230 |
owner: |
| 231 |
description: Owner of the publication at the end of runtime. |
| 232 |
returned: if publication exists |
| 233 |
type: str |
| 234 |
sample: "alice" |
| 235 |
tables: |
| 236 |
description: |
| 237 |
- List of tables in the publication at the end of runtime. |
| 238 |
- If all tables are published, returns empty list. |
| 239 |
returned: if publication exists |
| 240 |
type: list |
| 241 |
sample: ["\"public\".\"prices\"", "\"public\".\"vehicles\""] |
| 242 |
alltables: |
| 243 |
description: |
| 244 |
- Flag indicates that all tables are published. |
| 245 |
returned: if publication exists |
| 246 |
type: bool |
| 247 |
sample: false |
| 248 |
parameters: |
| 249 |
description: Publication parameters at the end of runtime. |
| 250 |
returned: if publication exists |
| 251 |
type: dict |
| 252 |
sample: {'publish': {'insert': false, 'delete': false, 'update': true}} |
| 253 |
''' |
| 254 |
|
| 255 |
|
| 256 |
from ansible.module_utils.basic import AnsibleModule |
| 257 |
from ansible_collections.community.postgresql.plugins.module_utils.database import ( |
| 258 |
check_input, pg_quote_identifier) |
| 259 |
from ansible_collections.community.postgresql.plugins.module_utils.postgres import ( |
| 260 |
connect_to_db, ensure_required_libs, exec_sql, get_conn_params, |
| 261 |
get_server_version, pg_cursor_args, postgres_common_argument_spec, |
| 262 |
set_comment) |
| 263 |
|
| 264 |
SUPPORTED_PG_VERSION = 10000 |
| 265 |
|
| 266 |
|
| 267 |
################################ |
| 268 |
# Module functions and classes # |
| 269 |
################################ |
| 270 |
|
| 271 |
def normalize_table_name(table): |
| 272 |
"""Add 'public.' to name of table where a schema identifier is absent |
| 273 |
and add quotes to each element. |
| 274 |
|
| 275 |
Args: |
| 276 |
table (str): Table name. |
| 277 |
|
| 278 |
Returns: |
| 279 |
str: Normalized table name. |
| 280 |
""" |
| 281 |
if '.' not in table: |
| 282 |
return pg_quote_identifier('public.%s' % table.strip(), 'table') |
| 283 |
else: |
| 284 |
return pg_quote_identifier(table.strip(), 'table') |
| 285 |
|
| 286 |
|
| 287 |
def transform_tables_representation(tbl_list): |
| 288 |
"""Add 'public.' to names of tables where a schema identifier is absent |
| 289 |
and add quotes to each element. |
| 290 |
|
| 291 |
Args: |
| 292 |
tbl_list (list): List of table names. |
| 293 |
|
| 294 |
Returns: |
| 295 |
tbl_list (list): Changed list. |
| 296 |
""" |
| 297 |
for i, table in enumerate(tbl_list): |
| 298 |
tbl_list[i] = normalize_table_name(table) |
| 299 |
|
| 300 |
return tbl_list |
| 301 |
|
| 302 |
|
| 303 |
def transform_columns_keys(columns): |
| 304 |
"""Add quotes to each element of the columns list. |
| 305 |
|
| 306 |
Args: |
| 307 |
columns (dict): Dict with tables and columns. |
| 308 |
|
| 309 |
Returns: |
| 310 |
columns (dict): Changed dict. |
| 311 |
""" |
| 312 |
revmap_columns = {} |
| 313 |
for table in columns: |
| 314 |
revmap_columns[normalize_table_name(table)] = set(c.strip() for c in columns[table]) if columns[table] else None |
| 315 |
|
| 316 |
return revmap_columns |
| 317 |
|
| 318 |
|
| 319 |
def transform_rowfilters_keys(rowfilters): |
| 320 |
"""Add quotes to each element of the rowfilters list and removes any "WHERE" clauses |
| 321 |
from the filter, since it's not retained in the publication `rowfilter` column |
| 322 |
|
| 323 |
Args: |
| 324 |
rowfilters (dict): Dict with tables and row filter conditions. |
| 325 |
|
| 326 |
Returns: |
| 327 |
rowfilters (dict): Changed dict. |
| 328 |
""" |
| 329 |
revmap_filters = {} |
| 330 |
for table, fltr in rowfilters.items(): |
| 331 |
fltr = fltr.strip() |
| 332 |
if fltr: |
| 333 |
if fltr[:5].lower() == 'where': |
| 334 |
fltr = fltr[5:].strip() |
| 335 |
revmap_filters[normalize_table_name(table)] = RowFilter(fltr) |
| 336 |
|
| 337 |
return revmap_filters |
| 338 |
|
| 339 |
|
| 340 |
def pg_quote_column_list(table, columns): |
| 341 |
"""Convert a list of columns to a string. |
| 342 |
|
| 343 |
Args: |
| 344 |
table (str): Table name. |
| 345 |
columns (list): List of columns. |
| 346 |
|
| 347 |
Returns: |
| 348 |
str: String with columns. |
| 349 |
""" |
| 350 |
table = normalize_table_name(table) |
| 351 |
|
| 352 |
if not columns: |
| 353 |
return table |
| 354 |
|
| 355 |
quoted_columns = [pg_quote_identifier(col, 'column') for col in columns] |
| 356 |
quoted_sql = "%s (%s)" % (table, ', '.join(quoted_columns)) |
| 357 |
return quoted_sql |
| 358 |
|
| 359 |
|
| 360 |
class RowFilter(str): |
| 361 |
"""Represents a row filter `WHERE` clause on a particular `table` |
| 362 |
|
| 363 |
We overload the `==` and `!=` operators so that when comparing: |
| 364 |
1. any possible quoting on columns is not considered |
| 365 |
2. whitespace is not considered |
| 366 |
|
| 367 |
This makes possible to identify identical row filters and not perform any |
| 368 |
changes, regardless of insignificant (for Postgres) syntactic differences. |
| 369 |
e.g. |
| 370 |
'( id > 10)' will be equivalent to '("id" > 10)' |
| 371 |
""" |
| 372 |
def __init__(self, rfilter): |
| 373 |
self.rfilter = rfilter |
| 374 |
|
| 375 |
def __eq__(self, other): |
| 376 |
return (self.rfilter.replace('"', '').replace(' ', '') == other.rfilter.replace('"', '').replace(' ', '')) |
| 377 |
|
| 378 |
def __ne__(self, other): |
| 379 |
return not self.__eq__(other) |
| 380 |
|
| 381 |
|
| 382 |
class PgPublication(): |
| 383 |
"""Class to work with PostgreSQL publication. |
| 384 |
|
| 385 |
Args: |
| 386 |
module (AnsibleModule): Object of AnsibleModule class. |
| 387 |
cursor (cursor): Cursor object of psycopg library to work with PostgreSQL. |
| 388 |
name (str): The name of the publication. |
| 389 |
|
| 390 |
Attributes: |
| 391 |
module (AnsibleModule): Object of AnsibleModule class. |
| 392 |
cursor (cursor): Cursor object of psycopg library to work with PostgreSQL. |
| 393 |
name (str): Name of the publication. |
| 394 |
executed_queries (list): List of executed queries. |
| 395 |
attrs (dict): Dict with publication attributes. |
| 396 |
exists (bool): Flag indicates the publication exists or not. |
| 397 |
""" |
| 398 |
|
| 399 |
def __init__(self, module, cursor, name, pg_srv_ver): |
| 400 |
self.module = module |
| 401 |
self.cursor = cursor |
| 402 |
self.name = name |
| 403 |
self.pg_srv_ver = pg_srv_ver |
| 404 |
self.executed_queries = [] |
| 405 |
self.attrs = { |
| 406 |
'alltables': False, |
| 407 |
'tables': [], |
| 408 |
'parameters': {}, |
| 409 |
'owner': '', |
| 410 |
'schemas': [], |
| 411 |
'columns': {}, |
| 412 |
'rowfilters': {}, |
| 413 |
} |
| 414 |
self.exists = self.check_pub() |
| 415 |
|
| 416 |
def get_info(self): |
| 417 |
"""Refresh the publication information. |
| 418 |
|
| 419 |
Returns: |
| 420 |
``self.attrs``. |
| 421 |
""" |
| 422 |
self.exists = self.check_pub() |
| 423 |
return self.attrs |
| 424 |
|
| 425 |
def check_pub(self): |
| 426 |
"""Check the publication and refresh ``self.attrs`` publication attribute. |
| 427 |
|
| 428 |
Returns: |
| 429 |
True if the publication with ``self.name`` exists, False otherwise. |
| 430 |
""" |
| 431 |
|
| 432 |
pub_info = self.__get_general_pub_info() |
| 433 |
|
| 434 |
if not pub_info: |
| 435 |
# Publication does not exist: |
| 436 |
return False |
| 437 |
|
| 438 |
self.attrs['owner'] = pub_info.get('pubowner') |
| 439 |
self.attrs['comment'] = pub_info.get('comment') if pub_info.get('comment') is not None else '' |
| 440 |
|
| 441 |
# Publication DML operations: |
| 442 |
self.attrs['parameters']['publish'] = {} |
| 443 |
self.attrs['parameters']['publish']['insert'] = pub_info.get('pubinsert', False) |
| 444 |
self.attrs['parameters']['publish']['update'] = pub_info.get('pubupdate', False) |
| 445 |
self.attrs['parameters']['publish']['delete'] = pub_info.get('pubdelete', False) |
| 446 |
if pub_info.get('pubtruncate'): |
| 447 |
self.attrs['parameters']['publish']['truncate'] = pub_info.get('pubtruncate') |
| 448 |
|
| 449 |
# If alltables flag is False, get the list of targeted tables: |
| 450 |
if not pub_info.get('puballtables'): |
| 451 |
table_info = self.__get_tables_pub_info() |
| 452 |
for i, schema_and_table in enumerate(table_info): |
| 453 |
table_info[i] = pg_quote_identifier(schema_and_table["schema_dot_table"], 'table') |
| 454 |
|
| 455 |
self.attrs['tables'] = table_info |
| 456 |
|
| 457 |
if self.pg_srv_ver >= 150000: |
| 458 |
# FOR TABLES IN SCHEMA statement and row filters are supported since PostgreSQL 15 |
| 459 |
self.attrs['schemas'] = self.__get_schema_pub_info() |
| 460 |
column_info = self.__get_columns_pub_info() |
| 461 |
columns = {} |
| 462 |
for row in column_info: |
| 463 |
columns[normalize_table_name(row["schema_dot_table"])] = set(row['columns']) |
| 464 |
self.attrs['columns'] = columns |
| 465 |
|
| 466 |
filters_info = self.__get_rowfilters_pub_info() |
| 467 |
filters = {} |
| 468 |
for row in filters_info: |
| 469 |
filters[normalize_table_name(row["schema_dot_table"])] = RowFilter(row['rowfilter']) |
| 470 |
self.attrs['rowfilters'] = filters |
| 471 |
else: |
| 472 |
self.attrs['alltables'] = True |
| 473 |
|
| 474 |
# Publication exists: |
| 475 |
return True |
| 476 |
|
| 477 |
def create(self, tables, tables_in_schema, columns, rowfilters, params, owner, comment, check_mode=True): |
| 478 |
"""Create the publication. |
| 479 |
|
| 480 |
Args: |
| 481 |
tables (list): List with names of the tables that need to be added to the publication. |
| 482 |
tables_in_schema (list): List of schema names of the tables that need to be added to the publication. |
| 483 |
params (dict): Dict contains optional publication parameters and their values. |
| 484 |
owner (str): Name of the publication owner. |
| 485 |
comment (str): Comment on the publication. |
| 486 |
|
| 487 |
Kwargs: |
| 488 |
check_mode (bool): If True, don't actually change anything, |
| 489 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 490 |
|
| 491 |
Returns: |
| 492 |
changed (bool): True if publication has been created, otherwise False. |
| 493 |
""" |
| 494 |
changed = True |
| 495 |
|
| 496 |
query_fragments = ["CREATE PUBLICATION %s" % pg_quote_identifier(self.name, 'publication')] |
| 497 |
|
| 498 |
if columns: |
| 499 |
table_strings = [] |
| 500 |
for table in columns: |
| 501 |
quoted_cols = pg_quote_column_list(table, columns[table]) |
| 502 |
if table in rowfilters: |
| 503 |
quoted_cols += (" WHERE %s" % rowfilters[table]) |
| 504 |
table_strings.append(quoted_cols) |
| 505 |
query_fragments.append("FOR TABLE %s" % ', '.join(table_strings)) |
| 506 |
elif tables: |
| 507 |
table_strings = [] |
| 508 |
for table in tables: |
| 509 |
tbl_str = pg_quote_identifier(table, 'table') |
| 510 |
if table in rowfilters: |
| 511 |
tbl_str += " WHERE %s" % rowfilters[table] |
| 512 |
table_strings.append(tbl_str) |
| 513 |
query_fragments.append("FOR TABLE %s" % ', '.join(table_strings)) |
| 514 |
elif tables_in_schema: |
| 515 |
tables_in_schema = [pg_quote_identifier(schema, 'schema') for schema in tables_in_schema] |
| 516 |
query_fragments.append("FOR TABLES IN SCHEMA %s" % ', '.join(tables_in_schema)) |
| 517 |
else: |
| 518 |
query_fragments.append("FOR ALL TABLES") |
| 519 |
|
| 520 |
if params: |
| 521 |
params_list = [] |
| 522 |
# Make list ["param = 'value'", ...] from params dict: |
| 523 |
for (key, val) in params.items(): |
| 524 |
params_list.append("%s = '%s'" % (key, val)) |
| 525 |
|
| 526 |
# Add the list to query_fragments: |
| 527 |
query_fragments.append("WITH (%s)" % ', '.join(params_list)) |
| 528 |
|
| 529 |
changed = self.__exec_sql(' '.join(query_fragments), check_mode=check_mode) |
| 530 |
|
| 531 |
if owner: |
| 532 |
# If check_mode, just add possible SQL to |
| 533 |
# executed_queries and return: |
| 534 |
self.__pub_set_owner(owner, check_mode=check_mode) |
| 535 |
|
| 536 |
if comment is not None: |
| 537 |
set_comment(self.cursor, comment, 'publication', |
| 538 |
self.name, check_mode, self.executed_queries) |
| 539 |
|
| 540 |
return changed |
| 541 |
|
| 542 |
def update(self, tables, tables_in_schema, columns, rowfilters, params, owner, comment, check_mode=True): |
| 543 |
"""Update the publication. |
| 544 |
|
| 545 |
Args: |
| 546 |
tables (list): List with names of the tables that need to be presented in the publication. |
| 547 |
tables_in_schema (list): List of schema names of the tables that need to be presented in the publication. |
| 548 |
params (dict): Dict contains optional publication parameters and their values. |
| 549 |
owner (str): Name of the publication owner. |
| 550 |
comment (str): Comment on the publication. |
| 551 |
|
| 552 |
Kwargs: |
| 553 |
check_mode (bool): If True, don't actually change anything, |
| 554 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 555 |
|
| 556 |
Returns: |
| 557 |
changed (bool): True if publication has been updated, otherwise False. |
| 558 |
""" |
| 559 |
changed = False |
| 560 |
|
| 561 |
# Add or drop tables from published tables suit: |
| 562 |
if columns and not self.attrs['alltables']: |
| 563 |
need_set_columns = False |
| 564 |
for table in columns: |
| 565 |
if table not in self.attrs['tables']: |
| 566 |
continue |
| 567 |
elif not columns[table]: |
| 568 |
all_columns = self.__get_table_columns(table) |
| 569 |
if all_columns != self.attrs['columns'][table]: |
| 570 |
need_set_columns = True |
| 571 |
break |
| 572 |
elif self.attrs['columns'][table] != columns[table]: |
| 573 |
need_set_columns = True |
| 574 |
break |
| 575 |
elif columns[table] == self.attrs['columns'][table]: |
| 576 |
if (table in rowfilters |
| 577 |
and table in self.attrs['rowfilters'] |
| 578 |
and rowfilters[table] != self.attrs['rowfilters'][table]): |
| 579 |
need_set_columns = True |
| 580 |
break |
| 581 |
|
| 582 |
if need_set_columns: |
| 583 |
changed = self.__pub_set_columns(columns, rowfilters, check_mode=check_mode) |
| 584 |
else: |
| 585 |
# Add new tables to the publication: |
| 586 |
for table in columns: |
| 587 |
if table not in self.attrs['tables']: |
| 588 |
changed = self.__pub_add_columns(table, columns[table], rowfilters, check_mode=check_mode) |
| 589 |
|
| 590 |
# Drop redundant tables from the publication: |
| 591 |
for table in self.attrs['columns']: |
| 592 |
if table not in columns.keys(): |
| 593 |
changed = self.__pub_drop_table(table, check_mode=check_mode) |
| 594 |
|
| 595 |
elif columns and self.attrs['alltables']: |
| 596 |
changed = self.__pub_set_columns(columns, rowfilters, check_mode=check_mode) |
| 597 |
if tables and not self.attrs['alltables']: |
| 598 |
|
| 599 |
# 1. If needs to add table to the publication: |
| 600 |
for tbl in tables: |
| 601 |
if tbl not in self.attrs['tables']: |
| 602 |
changed = self.__pub_add_table(tbl, rowfilters, check_mode=check_mode) |
| 603 |
elif ((tbl in rowfilters and rowfilters[tbl] != self.attrs['rowfilters'][tbl]) |
| 604 |
or (tbl in self.attrs['rowfilters'] and tbl not in rowfilters)): |
| 605 |
# If table is part of the publication, but row filter input |
| 606 |
# doesn't match the actual state of the publication, then drop it and |
| 607 |
# re-ADD it so that the row filter gets applied. |
| 608 |
changed = self.__pub_drop_table(tbl, check_mode=check_mode) |
| 609 |
if changed: |
| 610 |
changed = self.__pub_add_table(tbl, rowfilters, check_mode=check_mode) |
| 611 |
|
| 612 |
# 2. if there is a table in targeted tables |
| 613 |
# that's not present in the passed tables: |
| 614 |
for tbl in self.attrs['tables']: |
| 615 |
if tbl not in tables: |
| 616 |
changed = self.__pub_drop_table(tbl, check_mode=check_mode) |
| 617 |
|
| 618 |
elif tables and self.attrs['alltables']: |
| 619 |
changed = self.__pub_set_tables(tables, rowfilters, check_mode=check_mode) |
| 620 |
|
| 621 |
elif tables_in_schema is not None: |
| 622 |
|
| 623 |
# 1. If needs to add schema to the publication: |
| 624 |
for schema in tables_in_schema: |
| 625 |
if schema not in self.attrs['schemas']: |
| 626 |
changed = self.__pub_add_schema(schema, check_mode=check_mode) |
| 627 |
|
| 628 |
# 2. if there is a schema that's already in the publication |
| 629 |
# but not present in the passed schemas we remove it from the publication: |
| 630 |
for schema in self.attrs['schemas']: |
| 631 |
if schema not in tables_in_schema: |
| 632 |
changed = self.__pub_drop_schema(schema, check_mode=check_mode) |
| 633 |
|
| 634 |
# Update pub parameters: |
| 635 |
if params: |
| 636 |
for key, val in params.items(): |
| 637 |
if self.attrs['parameters'].get(key): |
| 638 |
|
| 639 |
# In PostgreSQL 10/11 only 'publish' optional parameter is presented. |
| 640 |
if key == 'publish': |
| 641 |
# 'publish' value can be only a string with comma-separated items |
| 642 |
# of allowed DML operations like 'insert,update' or |
| 643 |
# 'insert,update,delete', etc. |
| 644 |
# Make dictionary to compare with current attrs later: |
| 645 |
val_dict = self.attrs['parameters']['publish'].copy() |
| 646 |
val_list = val.split(',') |
| 647 |
for v in val_dict: |
| 648 |
if v in val_list: |
| 649 |
val_dict[v] = True |
| 650 |
else: |
| 651 |
val_dict[v] = False |
| 652 |
|
| 653 |
# Compare val_dict and the dict with current 'publish' parameters, |
| 654 |
# if they're different, set new values: |
| 655 |
if val_dict != self.attrs['parameters']['publish']: |
| 656 |
changed = self.__pub_set_param(key, val, check_mode=check_mode) |
| 657 |
|
| 658 |
# Default behavior for other cases: |
| 659 |
elif self.attrs['parameters'][key] != val: |
| 660 |
changed = self.__pub_set_param(key, val, check_mode=check_mode) |
| 661 |
|
| 662 |
else: |
| 663 |
# If the parameter was not set before: |
| 664 |
changed = self.__pub_set_param(key, val, check_mode=check_mode) |
| 665 |
|
| 666 |
# Update pub owner: |
| 667 |
if owner and owner != self.attrs['owner']: |
| 668 |
changed = self.__pub_set_owner(owner, check_mode=check_mode) |
| 669 |
|
| 670 |
if comment is not None and comment != self.attrs['comment']: |
| 671 |
changed = set_comment(self.cursor, comment, 'publication', |
| 672 |
self.name, check_mode, self.executed_queries) |
| 673 |
|
| 674 |
return changed |
| 675 |
|
| 676 |
def drop(self, cascade=False, check_mode=True): |
| 677 |
"""Drop the publication. |
| 678 |
|
| 679 |
Kwargs: |
| 680 |
cascade (bool): Flag indicates that publication needs to be deleted |
| 681 |
with its dependencies. |
| 682 |
check_mode (bool): If True, don't actually change anything, |
| 683 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 684 |
|
| 685 |
Returns: |
| 686 |
changed (bool): True if publication has been updated, otherwise False. |
| 687 |
""" |
| 688 |
if self.exists: |
| 689 |
query_fragments = [] |
| 690 |
query_fragments.append("DROP PUBLICATION %s" % pg_quote_identifier(self.name, 'publication')) |
| 691 |
if cascade: |
| 692 |
query_fragments.append("CASCADE") |
| 693 |
|
| 694 |
return self.__exec_sql(' '.join(query_fragments), check_mode=check_mode) |
| 695 |
|
| 696 |
def __get_general_pub_info(self): |
| 697 |
"""Get and return general publication information. |
| 698 |
|
| 699 |
Returns: |
| 700 |
Dict with publication information if successful, False otherwise. |
| 701 |
""" |
| 702 |
# Check pg_publication.pubtruncate exists (supported from PostgreSQL 11): |
| 703 |
pgtrunc_sup = exec_sql(self, ("SELECT 1 FROM information_schema.columns " |
| 704 |
"WHERE table_name = 'pg_publication' " |
| 705 |
"AND column_name = 'pubtruncate'"), add_to_executed=False) |
| 706 |
|
| 707 |
if pgtrunc_sup: |
| 708 |
query = ("SELECT obj_description(p.oid, 'pg_publication') AS comment, " |
| 709 |
"r.rolname AS pubowner, p.puballtables, p.pubinsert, " |
| 710 |
"p.pubupdate , p.pubdelete, p.pubtruncate FROM pg_publication AS p " |
| 711 |
"JOIN pg_catalog.pg_roles AS r " |
| 712 |
"ON p.pubowner = r.oid " |
| 713 |
"WHERE p.pubname = %(pname)s") |
| 714 |
else: |
| 715 |
query = ("SELECT obj_description(p.oid, 'pg_publication') AS comment, " |
| 716 |
"r.rolname AS pubowner, p.puballtables, p.pubinsert, " |
| 717 |
"p.pubupdate , p.pubdelete FROM pg_publication AS p " |
| 718 |
"JOIN pg_catalog.pg_roles AS r " |
| 719 |
"ON p.pubowner = r.oid " |
| 720 |
"WHERE p.pubname = %(pname)s") |
| 721 |
|
| 722 |
result = exec_sql(self, query, query_params={'pname': self.name}, add_to_executed=False) |
| 723 |
if result: |
| 724 |
return result[0] |
| 725 |
else: |
| 726 |
return False |
| 727 |
|
| 728 |
def __get_tables_pub_info(self): |
| 729 |
"""Get and return tables that are published by the publication. |
| 730 |
|
| 731 |
Returns: |
| 732 |
List of dicts with published tables. |
| 733 |
""" |
| 734 |
query = ("SELECT schemaname || '.' || tablename as schema_dot_table " |
| 735 |
"FROM pg_publication_tables WHERE pubname = %(pname)s") |
| 736 |
return exec_sql(self, query, query_params={'pname': self.name}, add_to_executed=False) |
| 737 |
|
| 738 |
def __get_rowfilters_pub_info(self): |
| 739 |
"""Get and return any row filters for each table that are published by the publication. |
| 740 |
|
| 741 |
Returns: |
| 742 |
List of dicts with row filters for each table. |
| 743 |
""" |
| 744 |
query = ("SELECT schemaname || '.' || tablename as schema_dot_table, rowfilter " |
| 745 |
"FROM pg_publication_tables " |
| 746 |
"WHERE pubname = %(pname)s AND rowfilter is not NULL") |
| 747 |
return exec_sql(self, query, query_params={'pname': self.name}, add_to_executed=False) |
| 748 |
|
| 749 |
def __get_columns_pub_info(self): |
| 750 |
"""Get and return columns that are published by the publication. |
| 751 |
|
| 752 |
Returns: |
| 753 |
List of dicts with published columns. |
| 754 |
""" |
| 755 |
query = ("SELECT schemaname || '.' || tablename as schema_dot_table, attnames as columns " |
| 756 |
"FROM pg_publication_tables WHERE pubname = %(pname)s") |
| 757 |
return exec_sql(self, query, query_params={'pname': self.name}, add_to_executed=False) |
| 758 |
|
| 759 |
def __get_schema_pub_info(self): |
| 760 |
"""Get and return schemas added to the publication. |
| 761 |
|
| 762 |
Returns: |
| 763 |
List of schemas. |
| 764 |
""" |
| 765 |
query = ("SELECT n.nspname FROM pg_namespace AS n " |
| 766 |
"JOIN pg_publication_namespace AS pn ON n.oid = pn.pnnspid " |
| 767 |
"JOIN pg_publication AS p ON p.oid = pn.pnpubid " |
| 768 |
"WHERE p.pubname = %(pname)s") |
| 769 |
list_of_dicts = exec_sql(self, query, query_params={'pname': self.name}, |
| 770 |
add_to_executed=False) |
| 771 |
|
| 772 |
list_of_schemas = [] |
| 773 |
for d in list_of_dicts: |
| 774 |
list_of_schemas.extend(d.values()) |
| 775 |
return list_of_schemas |
| 776 |
|
| 777 |
def __get_table_columns(self, table): |
| 778 |
"""Get and return columns names of the table. |
| 779 |
|
| 780 |
Returns: |
| 781 |
Set of columns. |
| 782 |
""" |
| 783 |
query = ("SELECT attname as column_name FROM pg_attribute " |
| 784 |
"WHERE attrelid = %(table)s::regclass and attnum > 0 AND NOT attisdropped;") |
| 785 |
result = exec_sql(self, query, query_params={'table': table}, add_to_executed=False) |
| 786 |
return set([row['column_name'] for row in result]) |
| 787 |
|
| 788 |
def __pub_add_table(self, table, rowfilters, check_mode=False): |
| 789 |
"""Add a table to the publication. |
| 790 |
|
| 791 |
Args: |
| 792 |
table (str): Table name. |
| 793 |
|
| 794 |
Kwargs: |
| 795 |
check_mode (bool): If True, don't actually change anything, |
| 796 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 797 |
|
| 798 |
Returns: |
| 799 |
True if successful, False otherwise. |
| 800 |
""" |
| 801 |
quoted_tbl = pg_quote_identifier(table, 'table') |
| 802 |
if table in rowfilters: |
| 803 |
quoted_tbl += (" WHERE %s" % rowfilters[table]) |
| 804 |
query = ("ALTER PUBLICATION %s ADD TABLE %s" % (pg_quote_identifier(self.name, 'publication'), |
| 805 |
quoted_tbl)) |
| 806 |
return self.__exec_sql(query, check_mode=check_mode) |
| 807 |
|
| 808 |
def __pub_drop_table(self, table, check_mode=False): |
| 809 |
"""Drop a table from the publication. |
| 810 |
|
| 811 |
Args: |
| 812 |
table (str): Table name. |
| 813 |
|
| 814 |
Kwargs: |
| 815 |
check_mode (bool): If True, don't actually change anything, |
| 816 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 817 |
|
| 818 |
Returns: |
| 819 |
True if successful, False otherwise. |
| 820 |
""" |
| 821 |
query = ("ALTER PUBLICATION %s DROP TABLE %s" % (pg_quote_identifier(self.name, 'publication'), |
| 822 |
pg_quote_identifier(table, 'table'))) |
| 823 |
return self.__exec_sql(query, check_mode=check_mode) |
| 824 |
|
| 825 |
def __pub_set_tables(self, tables, rowfilters, check_mode=False): |
| 826 |
"""Set a table suit that need to be published by the publication. |
| 827 |
|
| 828 |
Args: |
| 829 |
tables (list): List of tables. |
| 830 |
|
| 831 |
Kwargs: |
| 832 |
check_mode (bool): If True, don't actually change anything, |
| 833 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 834 |
|
| 835 |
Returns: |
| 836 |
True if successful, False otherwise. |
| 837 |
""" |
| 838 |
quoted_tables = [] |
| 839 |
for table in tables: |
| 840 |
quoted_tbl = pg_quote_identifier(table, 'table') |
| 841 |
if table in rowfilters: |
| 842 |
quoted_tbl += (" WHERE %s" % rowfilters[table]) |
| 843 |
quoted_tables.append(quoted_tbl) |
| 844 |
query = ("ALTER PUBLICATION %s SET TABLE %s" % (pg_quote_identifier(self.name, 'publication'), |
| 845 |
', '.join(quoted_tables))) |
| 846 |
return self.__exec_sql(query, check_mode=check_mode) |
| 847 |
|
| 848 |
def __pub_add_columns(self, table, columns, rowfilters, check_mode=False): |
| 849 |
""" Add table with specific columns to the publication. |
| 850 |
Args: |
| 851 |
table (str): Table name. |
| 852 |
columns (list): List of columns. |
| 853 |
Kwargs: |
| 854 |
check_mode (bool): If True, don't actually change anything, |
| 855 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 856 |
Returns: |
| 857 |
True if successful, False otherwise. |
| 858 |
""" |
| 859 |
quoted_cols = pg_quote_column_list(table, columns) |
| 860 |
if table in rowfilters: |
| 861 |
quoted_cols += (" WHERE %s" % rowfilters[table]) |
| 862 |
query = ("ALTER PUBLICATION %s ADD TABLE %s" % (pg_quote_identifier(self.name, 'publication'), |
| 863 |
quoted_cols)) |
| 864 |
return self.__exec_sql(query, check_mode=check_mode) |
| 865 |
|
| 866 |
def __pub_set_columns(self, columns_map, rowfilters, check_mode=False): |
| 867 |
"""Set columns that need to be published by the publication. |
| 868 |
Args: |
| 869 |
columns_map (dict): Dictionary of all tables and list of columns. |
| 870 |
Kwargs: |
| 871 |
check_mode (bool): If True, don't actually change anything, |
| 872 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 873 |
Returns: |
| 874 |
True if successful, False otherwise. |
| 875 |
""" |
| 876 |
table_list = [] |
| 877 |
for table, columns in columns_map.items(): |
| 878 |
quoted_cols = pg_quote_column_list(table, columns) |
| 879 |
if table in rowfilters: |
| 880 |
quoted_cols += (" WHERE %s" % rowfilters[table]) |
| 881 |
table_list.append(quoted_cols) |
| 882 |
query = ( |
| 883 |
"ALTER PUBLICATION %s SET TABLE %s" % |
| 884 |
(pg_quote_identifier(self.name, 'publication'), |
| 885 |
', '.join(table_list)) |
| 886 |
) |
| 887 |
return self.__exec_sql(query, check_mode=check_mode) |
| 888 |
|
| 889 |
def __pub_add_schema(self, schema, check_mode=False): |
| 890 |
"""Add a schema to the publication. |
| 891 |
|
| 892 |
Args: |
| 893 |
schema (str): Schema name. |
| 894 |
|
| 895 |
Kwargs: |
| 896 |
check_mode (bool): If True, don't actually change anything, |
| 897 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 898 |
|
| 899 |
Returns: |
| 900 |
True if truly added, False otherwise. |
| 901 |
""" |
| 902 |
query = ("ALTER PUBLICATION %s ADD " |
| 903 |
"TABLES IN SCHEMA %s" % (pg_quote_identifier(self.name, 'publication'), |
| 904 |
pg_quote_identifier(schema, 'schema'))) |
| 905 |
return self.__exec_sql(query, check_mode=check_mode) |
| 906 |
|
| 907 |
def __pub_drop_schema(self, schema, check_mode=False): |
| 908 |
"""Drop a schema from the publication. |
| 909 |
|
| 910 |
Args: |
| 911 |
schema (str): Schema name. |
| 912 |
|
| 913 |
Kwargs: |
| 914 |
check_mode (bool): If True, don't actually change anything, |
| 915 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 916 |
|
| 917 |
Returns: |
| 918 |
True if truly dropped, False otherwise. |
| 919 |
""" |
| 920 |
query = ("ALTER PUBLICATION %s DROP " |
| 921 |
"TABLES IN SCHEMA %s" % (pg_quote_identifier(self.name, 'publication'), |
| 922 |
pg_quote_identifier(schema, 'schema'))) |
| 923 |
return self.__exec_sql(query, check_mode=check_mode) |
| 924 |
|
| 925 |
def __pub_set_param(self, param, value, check_mode=False): |
| 926 |
"""Set an optional publication parameter. |
| 927 |
|
| 928 |
Args: |
| 929 |
param (str): Name of the parameter. |
| 930 |
value (str): Parameter value. |
| 931 |
|
| 932 |
Kwargs: |
| 933 |
check_mode (bool): If True, don't actually change anything, |
| 934 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 935 |
|
| 936 |
Returns: |
| 937 |
True if successful, False otherwise. |
| 938 |
""" |
| 939 |
query = ("ALTER PUBLICATION %s SET (%s = '%s')" % (pg_quote_identifier(self.name, 'publication'), |
| 940 |
param, value)) |
| 941 |
return self.__exec_sql(query, check_mode=check_mode) |
| 942 |
|
| 943 |
def __pub_set_owner(self, role, check_mode=False): |
| 944 |
"""Set a publication owner. |
| 945 |
|
| 946 |
Args: |
| 947 |
role (str): Role (user) name that needs to be set as a publication owner. |
| 948 |
|
| 949 |
Kwargs: |
| 950 |
check_mode (bool): If True, don't actually change anything, |
| 951 |
just make SQL, add it to ``self.executed_queries`` and return True. |
| 952 |
|
| 953 |
Returns: |
| 954 |
True if successful, False otherwise. |
| 955 |
""" |
| 956 |
query = ('ALTER PUBLICATION %s ' |
| 957 |
'OWNER TO "%s"' % (pg_quote_identifier(self.name, 'publication'), role)) |
| 958 |
return self.__exec_sql(query, check_mode=check_mode) |
| 959 |
|
| 960 |
def __exec_sql(self, query, check_mode=False): |
| 961 |
"""Execute SQL query. |
| 962 |
|
| 963 |
Note: If we need just to get information from the database, |
| 964 |
we use ``exec_sql`` function directly. |
| 965 |
|
| 966 |
Args: |
| 967 |
query (str): Query that needs to be executed. |
| 968 |
|
| 969 |
Kwargs: |
| 970 |
check_mode (bool): If True, don't actually change anything, |
| 971 |
just add ``query`` to ``self.executed_queries`` and return True. |
| 972 |
|
| 973 |
Returns: |
| 974 |
True if successful, False otherwise. |
| 975 |
""" |
| 976 |
if check_mode: |
| 977 |
self.executed_queries.append(query) |
| 978 |
return True |
| 979 |
else: |
| 980 |
return exec_sql(self, query, return_bool=True) |
| 981 |
|
| 982 |
|
| 983 |
# =========================================== |
| 984 |
# Module execution. |
| 985 |
# |
| 986 |
|
| 987 |
|
| 988 |
def main(): |
| 989 |
argument_spec = postgres_common_argument_spec() |
| 990 |
argument_spec.update( |
| 991 |
name=dict(required=True), |
| 992 |
login_db=dict(type='str', aliases=['db'], deprecated_aliases=[ |
| 993 |
{ |
| 994 |
'name': 'db', |
| 995 |
'version': '5.0.0', |
| 996 |
'collection_name': 'community.postgresql', |
| 997 |
}], |
| 998 |
), |
| 999 |
state=dict(type='str', default='present', choices=['absent', 'present']), |
| 1000 |
tables=dict(type='list', elements='str'), |
| 1001 |
parameters=dict(type='dict'), |
| 1002 |
owner=dict(type='str'), |
| 1003 |
cascade=dict(type='bool', default=False), |
| 1004 |
session_role=dict(type='str'), |
| 1005 |
trust_input=dict(type='bool', default=True), |
| 1006 |
comment=dict(type='str', default=None), |
| 1007 |
tables_in_schema=dict(type='list', elements='str', default=None), |
| 1008 |
columns=dict(type='dict', default=None), |
| 1009 |
rowfilters=dict(type='dict', default=None), |
| 1010 |
) |
| 1011 |
module = AnsibleModule( |
| 1012 |
argument_spec=argument_spec, |
| 1013 |
supports_check_mode=True, |
| 1014 |
mutually_exclusive=[('tables', 'tables_in_schema', "columns"), |
| 1015 |
('rowfilters', 'tables_in_schema')], |
| 1016 |
) |
| 1017 |
|
| 1018 |
# Parameters handling: |
| 1019 |
name = module.params['name'] |
| 1020 |
state = module.params['state'] |
| 1021 |
tables = module.params['tables'] |
| 1022 |
params = module.params['parameters'] |
| 1023 |
owner = module.params['owner'] |
| 1024 |
cascade = module.params['cascade'] |
| 1025 |
session_role = module.params['session_role'] |
| 1026 |
trust_input = module.params['trust_input'] |
| 1027 |
comment = module.params['comment'] |
| 1028 |
tables_in_schema = module.params['tables_in_schema'] |
| 1029 |
columns = module.params['columns'] |
| 1030 |
rowfilters = module.params['rowfilters'] |
| 1031 |
|
| 1032 |
if not trust_input: |
| 1033 |
# Check input for potentially dangerous elements: |
| 1034 |
if not params: |
| 1035 |
params_list = None |
| 1036 |
else: |
| 1037 |
params_list = ['%s = %s' % (k, v) for k, v in params.items()] |
| 1038 |
|
| 1039 |
check_input(module, name, tables, owner, |
| 1040 |
session_role, params_list, comment) |
| 1041 |
|
| 1042 |
if state == 'absent': |
| 1043 |
if tables: |
| 1044 |
module.warn('parameter "tables" is ignored when "state=absent"') |
| 1045 |
if params: |
| 1046 |
module.warn('parameter "parameters" is ignored when "state=absent"') |
| 1047 |
if owner: |
| 1048 |
module.warn('parameter "owner" is ignored when "state=absent"') |
| 1049 |
|
| 1050 |
if state == 'present' and cascade: |
| 1051 |
module.warn('parameter "cascade" is ignored when "state=present"') |
| 1052 |
|
| 1053 |
# Ensure psycopg libraries are available before connecting to DB: |
| 1054 |
ensure_required_libs(module) |
| 1055 |
# Connect to DB and make cursor object: |
| 1056 |
conn_params = get_conn_params(module, module.params) |
| 1057 |
# We check publication state without DML queries execution, so set autocommit: |
| 1058 |
db_connection, dummy = connect_to_db(module, conn_params, autocommit=True) |
| 1059 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 1060 |
|
| 1061 |
# Check version: |
| 1062 |
pg_srv_ver = get_server_version(cursor.connection) |
| 1063 |
if pg_srv_ver < SUPPORTED_PG_VERSION: |
| 1064 |
module.fail_json(msg="PostgreSQL server version should be 10.0 or greater") |
| 1065 |
|
| 1066 |
if tables_in_schema is not None and pg_srv_ver < 150000: |
| 1067 |
module.fail_json(msg="Publication of tables in schema is supported by PostgreSQL 15 or greater") |
| 1068 |
if columns and pg_srv_ver < 150000: |
| 1069 |
module.fail_json(msg="Publication of columns is supported by PostgreSQL 15 or greater") |
| 1070 |
if rowfilters is not None and pg_srv_ver < 150000: |
| 1071 |
module.fail_json(msg="Row filtering is supported by PostgreSQL 15 or greater") |
| 1072 |
# Nothing was changed by default: |
| 1073 |
changed = False |
| 1074 |
|
| 1075 |
################################### |
| 1076 |
# Create object and do rock'n'roll: |
| 1077 |
publication = PgPublication(module, cursor, name, pg_srv_ver) |
| 1078 |
|
| 1079 |
if tables: |
| 1080 |
tables = transform_tables_representation(tables) |
| 1081 |
|
| 1082 |
if columns: |
| 1083 |
columns = transform_columns_keys(columns) |
| 1084 |
|
| 1085 |
rowfilters = transform_rowfilters_keys(rowfilters) if rowfilters else {} |
| 1086 |
|
| 1087 |
# If module.check_mode=True, nothing will be changed: |
| 1088 |
if state == 'present': |
| 1089 |
if not publication.exists: |
| 1090 |
changed = publication.create(tables, tables_in_schema, columns, rowfilters, params, owner, |
| 1091 |
comment, check_mode=module.check_mode) |
| 1092 |
|
| 1093 |
else: |
| 1094 |
changed = publication.update(tables, tables_in_schema, columns, rowfilters, params, owner, |
| 1095 |
comment, check_mode=module.check_mode) |
| 1096 |
|
| 1097 |
elif state == 'absent': |
| 1098 |
changed = publication.drop(cascade=cascade, check_mode=module.check_mode) |
| 1099 |
|
| 1100 |
# Get final publication info: |
| 1101 |
pub_fin_info = {} |
| 1102 |
if state == 'present' or (state == 'absent' and module.check_mode): |
| 1103 |
pub_fin_info = publication.get_info() |
| 1104 |
elif state == 'absent' and not module.check_mode: |
| 1105 |
publication.exists = False |
| 1106 |
|
| 1107 |
# Connection is not needed any more: |
| 1108 |
cursor.close() |
| 1109 |
db_connection.close() |
| 1110 |
|
| 1111 |
# Update publication info and return ret values: |
| 1112 |
module.exit_json(changed=changed, queries=publication.executed_queries, exists=publication.exists, **pub_fin_info) |
| 1113 |
|
| 1114 |
|
| 1115 |
if __name__ == '__main__': |
| 1116 |
main() |