Debian Codegraph @

ansible_collections/community/postgresql/plugins/modules/postgresql_schema.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2016, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: postgresql_schema
14 short_description: Add or remove PostgreSQL schema
15 description:
16 - Add or remove PostgreSQL schema.
17 options:
18 name:
19 description:
20 - Name of the schema to add or remove.
21 required: true
22 type: str
23 aliases:
24 - schema
25 login_db:
26 description:
27 - Name of the database to connect to and add or remove the schema.
28 - The V(db) alias is deprecated and will be removed in version 5.0.0.
29 type: str
30 default: postgres
31 aliases:
32 - db
33 - database
34 owner:
35 description:
36 - Name of the role to set as owner of the schema.
37 type: str
38 default: ''
39 session_role:
40 description:
41 - Switch to session_role after connecting.
42 - The specified session_role must be a role that the current login_user is a member of.
43 - Permissions checking for SQL commands is carried out as though the session_role
44 were the one that had logged in originally.
45 type: str
46 state:
47 description:
48 - The schema state.
49 type: str
50 default: present
51 choices: [ absent, present ]
52 cascade_drop:
53 description:
54 - Drop schema with CASCADE to remove child objects.
55 type: bool
56 default: false
57 trust_input:
58 description:
59 - If C(false), check whether values of parameters I(schema), I(owner), I(session_role) are potentially dangerous.
60 - It makes sense to use C(false) only when SQL injections via the parameters are possible.
61 type: bool
62 default: true
63 version_added: '0.2.0'
64 comment:
65 description:
66 - Sets a comment on the schema.
67 - To reset the comment, pass an empty string.
68 type: str
69 version_added: '3.3.0'
70 seealso:
71 - name: PostgreSQL schemas
72 description: General information about PostgreSQL schemas.
73 link: https://www.postgresql.org/docs/current/ddl-schemas.html
74 - name: CREATE SCHEMA reference
75 description: Complete reference of the CREATE SCHEMA command documentation.
76 link: https://www.postgresql.org/docs/current/sql-createschema.html
77 - name: ALTER SCHEMA reference
78 description: Complete reference of the ALTER SCHEMA command documentation.
79 link: https://www.postgresql.org/docs/current/sql-alterschema.html
80 - name: DROP SCHEMA reference
81 description: Complete reference of the DROP SCHEMA command documentation.
82 link: https://www.postgresql.org/docs/current/sql-dropschema.html
83
84 attributes:
85 check_mode:
86 support: full
87
88 author:
89 - Flavien Chantelot (@Dorn-) <[email protected]>
90 - Thomas O'Donnell (@andytom)
91
92 extends_documentation_fragment:
93 - community.postgresql.postgres
94 '''
95
96 EXAMPLES = r'''
97 - name: Create a new schema with name acme in test database
98 community.postgresql.postgresql_schema:
99 login_db: test
100 name: acme
101 comment: 'My test schema'
102
103 - name: Create a new schema acme with a user bob who will own it
104 community.postgresql.postgresql_schema:
105 name: acme
106 owner: bob
107
108 - name: Drop schema "acme" with cascade
109 community.postgresql.postgresql_schema:
110 name: acme
111 state: absent
112 cascade_drop: true
113 '''
114
115 RETURN = r'''
116 schema:
117 description: Name of the schema.
118 returned: success
119 type: str
120 sample: "acme"
121 queries:
122 description: List of executed queries.
123 returned: success
124 type: list
125 sample: ["CREATE SCHEMA \"acme\""]
126 '''
127
128 import traceback
129
130 from ansible.module_utils.common.text.converters import to_native
131 from ansible.module_utils.basic import AnsibleModule
132 from ansible_collections.community.postgresql.plugins.module_utils.database import (
133 SQLParseError,
134 check_input,
135 pg_quote_identifier,
136 )
137 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
138 connect_to_db,
139 ensure_required_libs,
140 get_conn_params,
141 pg_cursor_args,
142 postgres_common_argument_spec,
143 set_comment,
144 )
145
146 executed_queries = []
147
148
149 class NotSupportedError(Exception):
150 pass
151
152
153 # ===========================================
154 # PostgreSQL module specific support methods.
155 #
156
157 def set_owner(cursor, schema, owner):
158 query = 'ALTER SCHEMA %s OWNER TO "%s"' % (
159 pg_quote_identifier(schema, 'schema'), owner)
160 cursor.execute(query)
161 executed_queries.append(query)
162 return True
163
164
165 def get_schema_info(cursor, schema):
166 query = ("SELECT obj_description((SELECT oid "
167 "FROM pg_namespace WHERE nspname = %(schema)s), 'pg_namespace') "
168 "AS comment, schema_owner AS owner "
169 "FROM information_schema.schemata "
170 "WHERE schema_name = %(schema)s")
171 cursor.execute(query, {'schema': schema})
172 return cursor.fetchone()
173
174
175 def schema_exists(cursor, schema):
176 query = ("SELECT schema_name FROM information_schema.schemata "
177 "WHERE schema_name = %(schema)s")
178 cursor.execute(query, {'schema': schema})
179 return cursor.rowcount == 1
180
181
182 def schema_delete(cursor, schema, cascade):
183 if schema_exists(cursor, schema):
184 query = "DROP SCHEMA %s" % pg_quote_identifier(schema, 'schema')
185 if cascade:
186 query += " CASCADE"
187 cursor.execute(query)
188 executed_queries.append(query)
189 return True
190 else:
191 return False
192
193
194 def schema_create(cursor, schema, owner, comment):
195 if not schema_exists(cursor, schema):
196 query_fragments = ['CREATE SCHEMA %s' % pg_quote_identifier(schema, 'schema')]
197 if owner:
198 query_fragments.append('AUTHORIZATION "%s"' % owner)
199 query = ' '.join(query_fragments)
200 cursor.execute(query)
201 executed_queries.append(query)
202 if comment is not None:
203 set_comment(cursor, comment, 'schema', schema, False, executed_queries)
204 return True
205 else:
206 schema_info = get_schema_info(cursor, schema)
207 changed = False
208 if owner and owner != schema_info['owner']:
209 changed = set_owner(cursor, schema, owner)
210
211 if comment is not None:
212 current_comment = schema_info['comment'] if schema_info['comment'] is not None else ''
213 if comment != current_comment:
214 changed = set_comment(cursor, comment, 'schema', schema, False, executed_queries) or changed
215
216 return changed
217
218
219 def schema_matches(cursor, schema, owner, comment):
220 if not schema_exists(cursor, schema):
221 return False
222 else:
223 schema_info = get_schema_info(cursor, schema)
224 if owner and owner != schema_info['owner']:
225 return False
226 if comment is not None:
227 # For the resetting comment feature (comment: '') to work correctly
228 current_comment = schema_info['comment'] if schema_info['comment'] is not None else ''
229 if comment != current_comment:
230 return False
231
232 return True
233
234 # ===========================================
235 # Module execution.
236 #
237
238
239 def main():
240 argument_spec = postgres_common_argument_spec()
241 argument_spec.update(
242 schema=dict(type="str", required=True, aliases=['name']),
243 owner=dict(type="str", default=""),
244 login_db=dict(type='str', default='postgres', aliases=['db', 'database'], deprecated_aliases=[
245 {
246 'name': 'db',
247 'version': '5.0.0',
248 'collection_name': 'community.postgresql',
249 },
250 {
251 'name': 'database',
252 'version': '5.0.0',
253 'collection_name': 'community.postgresql',
254 }],
255 ),
256 cascade_drop=dict(type="bool", default=False),
257 state=dict(type="str", default="present", choices=["absent", "present"]),
258 session_role=dict(type="str"),
259 trust_input=dict(type="bool", default=True),
260 comment=dict(type="str", default=None),
261 )
262
263 module = AnsibleModule(
264 argument_spec=argument_spec,
265 supports_check_mode=True,
266 )
267
268 schema = module.params["schema"]
269 owner = module.params["owner"]
270 state = module.params["state"]
271 cascade_drop = module.params["cascade_drop"]
272 session_role = module.params["session_role"]
273 trust_input = module.params["trust_input"]
274 comment = module.params["comment"]
275
276 if not trust_input:
277 # Check input for potentially dangerous elements:
278 check_input(module, schema, owner, session_role, comment)
279
280 changed = False
281
282 # Ensure psycopg libraries are available before connecting to DB:
283 ensure_required_libs(module)
284 conn_params = get_conn_params(module, module.params)
285 db_connection, dummy = connect_to_db(module, conn_params, autocommit=True)
286 cursor = db_connection.cursor(**pg_cursor_args)
287
288 try:
289 if module.check_mode:
290 if state == "absent":
291 changed = schema_exists(cursor, schema)
292 elif state == "present":
293 changed = not schema_matches(cursor, schema, owner, comment)
294 module.exit_json(changed=changed, schema=schema)
295
296 if state == "absent":
297 try:
298 changed = schema_delete(cursor, schema, cascade_drop)
299 except SQLParseError as e:
300 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
301
302 elif state == "present":
303 try:
304 changed = schema_create(cursor, schema, owner, comment)
305 except SQLParseError as e:
306 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
307 except NotSupportedError as e:
308 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
309 except SystemExit:
310 # Avoid catching this on Python 2.4
311 raise
312 except Exception as e:
313 module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc())
314
315 db_connection.close()
316 module.exit_json(changed=changed, schema=schema, queries=executed_queries)
317
318
319 if __name__ == '__main__':
320 main()