Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]>
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_copy
14 short_description: Copy data between a file/program and a PostgreSQL table
15 description:
16 - Copy data between a file/program and a PostgreSQL table.
17
18 options:
19 copy_to:
20 description:
21 - Copy the contents of a table to a file.
22 - Can also copy the results of a SELECT query.
23 - Mutually exclusive with I(copy_from) and I(dst).
24 type: path
25 aliases: [ to ]
26 copy_from:
27 description:
28 - Copy data from a file to a table (appending the data to whatever is in the table already).
29 - Mutually exclusive with I(copy_to) and I(src).
30 type: path
31 aliases: [ from ]
32 src:
33 description:
34 - Copy data from I(copy_from) to I(src=tablename).
35 - Used with I(copy_to) only.
36 type: str
37 aliases: [ source ]
38 dst:
39 description:
40 - Copy data to I(dst=tablename) from I(copy_from=/path/to/data.file).
41 - Used with I(copy_from) only.
42 type: str
43 aliases: [ destination ]
44 columns:
45 description:
46 - List of column names for the src/dst table to COPY FROM/TO.
47 type: list
48 elements: str
49 aliases: [ column ]
50 program:
51 description:
52 - Mark I(src)/I(dst) as a program. Data will be copied to/from a program.
53 - See block Examples and PROGRAM arg description U(https://www.postgresql.org/docs/current/sql-copy.html).
54 type: bool
55 default: false
56 options:
57 description:
58 - Options of COPY command.
59 - See the full list of available options U(https://www.postgresql.org/docs/current/sql-copy.html).
60 type: dict
61 login_db:
62 description:
63 - Name of database to connect to.
64 - The V(db) alias is deprecated and will be removed in version 5.0.0.
65 type: str
66 aliases: [ db ]
67 session_role:
68 description:
69 - Switch to session_role after connecting.
70 The specified session_role must be a role that the current login_user is a member of.
71 - Permissions checking for SQL commands is carried out as though
72 the session_role were the one that had logged in originally.
73 type: str
74 trust_input:
75 description:
76 - If C(false), check whether values of parameters are potentially dangerous.
77 - It makes sense to use C(false) only when SQL injections are possible.
78 type: bool
79 default: true
80 version_added: '0.2.0'
81 notes:
82 - Supports PostgreSQL version 9.4+.
83 - COPY command is only allowed to database superusers.
84
85 attributes:
86 check_mode:
87 support: partial
88 details:
89 - If I(check_mode=true), we just check the src/dst table availability
90 and return the COPY query that actually has not been executed.
91 - If i(check_mode=true) and the source has been passed as SQL, the module
92 will execute it and roll the transaction back, but pay attention
93 it can affect database performance (e.g., if SQL collects a lot of data).
94
95 seealso:
96 - name: COPY command reference
97 description: Complete reference of the COPY command documentation.
98 link: https://www.postgresql.org/docs/current/sql-copy.html
99
100 author:
101 - Andrew Klychkov (@Andersson007)
102
103 extends_documentation_fragment:
104 - community.postgresql.postgres
105 '''
106
107 EXAMPLES = r'''
108 - name: Copy text TAB-separated data from file /tmp/data.txt to acme table
109 community.postgresql.postgresql_copy:
110 copy_from: /tmp/data.txt
111 dst: acme
112
113 - name: Copy CSV (comma-separated) data from file /tmp/data.csv to columns id, name of table acme
114 community.postgresql.postgresql_copy:
115 copy_from: /tmp/data.csv
116 dst: acme
117 columns: id,name
118 options:
119 format: csv
120
121 - name: >
122 Copy text vertical-bar-separated data from file /tmp/data.txt to bar table.
123 The NULL values are specified as N
124 community.postgresql.postgresql_copy:
125 copy_from: /tmp/data.csv
126 dst: bar
127 options:
128 delimiter: '|'
129 null: 'N'
130
131 - name: Copy data from acme table to file /tmp/data.txt in text format, TAB-separated
132 community.postgresql.postgresql_copy:
133 src: acme
134 copy_to: /tmp/data.txt
135
136 - name: Copy data from SELECT query to/tmp/data.csv in CSV format
137 community.postgresql.postgresql_copy:
138 src: 'SELECT * FROM acme'
139 copy_to: /tmp/data.csv
140 options:
141 format: csv
142
143 - name: Copy CSV data from my_table to gzip
144 community.postgresql.postgresql_copy:
145 src: my_table
146 copy_to: 'gzip > /tmp/data.csv.gz'
147 program: true
148 options:
149 format: csv
150
151 - name: >
152 Copy data from columns id, name of table bar to /tmp/data.txt.
153 Output format is text, vertical-bar-separated, NULL as N
154 community.postgresql.postgresql_copy:
155 src: bar
156 columns:
157 - id
158 - name
159 copy_to: /tmp/data.csv
160 options:
161 delimiter: '|'
162 null: 'N'
163 '''
164
165 RETURN = r'''
166 queries:
167 description: List of executed queries.
168 returned: success
169 type: str
170 sample: [ "COPY test_table FROM '/tmp/data_file.txt' (FORMAT csv, DELIMITER ',', NULL 'NULL')" ]
171 src:
172 description: Data source.
173 returned: success
174 type: str
175 sample: "mytable"
176 dst:
177 description: Data destination.
178 returned: success
179 type: str
180 sample: "/tmp/data.csv"
181 '''
182
183 from ansible.module_utils.basic import AnsibleModule
184 from ansible_collections.community.postgresql.plugins.module_utils.database import (
185 check_input,
186 pg_quote_identifier,
187 )
188 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
189 connect_to_db,
190 ensure_required_libs,
191 exec_sql, get_conn_params,
192 pg_cursor_args,
193 postgres_common_argument_spec,
194 )
195
196
197 class PgCopyData(object):
198
199 """Implements behavior of COPY FROM, COPY TO PostgreSQL command.
200
201 Arguments:
202 module (AnsibleModule) -- object of AnsibleModule class
203 cursor (cursor) -- cursor object of psycopg library
204
205 Attributes:
206 module (AnsibleModule) -- object of AnsibleModule class
207 cursor (cursor) -- cursor object of psycopg library
208 changed (bool) -- something was changed after execution or not
209 executed_queries (list) -- executed queries
210 dst (str) -- data destination table (when copy_from)
211 src (str) -- data source table (when copy_to)
212 opt_need_quotes (tuple) -- values of these options must be passed
213 to SQL in quotes
214 """
215
216 def __init__(self, module, cursor):
217 self.module = module
218 self.cursor = cursor
219 self.executed_queries = []
220 self.changed = False
221 self.dst = ''
222 self.src = ''
223 self.opt_need_quotes = (
224 'DELIMITER',
225 'NULL',
226 'QUOTE',
227 'ESCAPE',
228 'ENCODING',
229 )
230
231 def copy_from(self):
232 """Implements COPY FROM command behavior."""
233 self.src = self.module.params['copy_from']
234 self.dst = self.module.params['dst']
235
236 query_fragments = ['COPY %s' % pg_quote_identifier(self.dst, 'table')]
237
238 if self.module.params.get('columns'):
239 query_fragments.append('(%s)' % ','.join(self.module.params['columns']))
240
241 query_fragments.append('FROM')
242
243 if self.module.params.get('program'):
244 query_fragments.append('PROGRAM')
245
246 query_fragments.append("'%s'" % self.src)
247
248 if self.module.params.get('options'):
249 query_fragments.append(self.__transform_options())
250
251 # Note: check mode is implemented here:
252 if self.module.check_mode:
253 self.changed = self.__check_table(self.dst)
254
255 if self.changed:
256 self.executed_queries.append(' '.join(query_fragments))
257 else:
258 if exec_sql(self, ' '.join(query_fragments), return_bool=True):
259 self.changed = True
260
261 def copy_to(self):
262 """Implements COPY TO command behavior."""
263 self.src = self.module.params['src']
264 self.dst = self.module.params['copy_to']
265
266 if 'SELECT ' in self.src.upper():
267 # If src is SQL SELECT statement:
268 query_fragments = ['COPY (%s)' % self.src]
269 else:
270 # If src is a table:
271 query_fragments = ['COPY %s' % pg_quote_identifier(self.src, 'table')]
272
273 if self.module.params.get('columns'):
274 query_fragments.append('(%s)' % ','.join(self.module.params['columns']))
275
276 query_fragments.append('TO')
277
278 if self.module.params.get('program'):
279 query_fragments.append('PROGRAM')
280
281 query_fragments.append("'%s'" % self.dst)
282
283 if self.module.params.get('options'):
284 query_fragments.append(self.__transform_options())
285
286 # Note: check mode is implemented here:
287 if self.module.check_mode:
288 self.changed = self.__check_table(self.src)
289
290 if self.changed:
291 self.executed_queries.append(' '.join(query_fragments))
292 else:
293 if exec_sql(self, ' '.join(query_fragments), return_bool=True):
294 self.changed = True
295
296 def __transform_options(self):
297 """Transform options dict into a suitable string."""
298 for (key, val) in self.module.params['options'].items():
299 if key.upper() in self.opt_need_quotes:
300 self.module.params['options'][key] = "'%s'" % val
301
302 opt = ['%s %s' % (key, val) for (key, val) in self.module.params['options'].items()]
303 return '(%s)' % ', '.join(opt)
304
305 def __check_table(self, table):
306 """Check table or SQL in transaction mode for check_mode.
307
308 Return True if it is OK.
309
310 Arguments:
311 table (str) - Table name that needs to be checked.
312 It can be SQL SELECT statement that was passed
313 instead of the table name.
314 """
315 if 'SELECT ' in table.upper():
316 # In this case table is actually SQL SELECT statement.
317 # If SQL fails, it's handled by exec_sql():
318 exec_sql(self, table, add_to_executed=False)
319 # If exec_sql was passed, it means all is OK:
320 return True
321
322 exec_sql(self, 'SELECT 1 FROM %s' % pg_quote_identifier(table, 'table'),
323 add_to_executed=False)
324 # If SQL was executed successfully:
325 return True
326
327
328 # ===========================================
329 # Module execution.
330 #
331
332
333 def main():
334 argument_spec = postgres_common_argument_spec()
335 argument_spec.update(
336 copy_to=dict(type='path', aliases=['to']),
337 copy_from=dict(type='path', aliases=['from']),
338 src=dict(type='str', aliases=['source']),
339 dst=dict(type='str', aliases=['destination']),
340 columns=dict(type='list', elements='str', aliases=['column']),
341 options=dict(type='dict'),
342 program=dict(type='bool', default=False),
343 login_db=dict(type='str', aliases=['db'], deprecated_aliases=[
344 {
345 'name': 'db',
346 'version': '5.0.0',
347 'collection_name': 'community.postgresql',
348 }],
349 ),
350 session_role=dict(type='str'),
351 trust_input=dict(type='bool', default=True),
352 )
353 module = AnsibleModule(
354 argument_spec=argument_spec,
355 supports_check_mode=True,
356 mutually_exclusive=[
357 ['copy_from', 'copy_to'],
358 ['copy_from', 'src'],
359 ['copy_to', 'dst'],
360 ]
361 )
362
363 if not module.params['trust_input']:
364 # Check input for potentially dangerous elements:
365 opt_list = None
366 if module.params['options']:
367 opt_list = ['%s %s' % (key, val) for (key, val) in module.params['options'].items()]
368
369 check_input(module,
370 module.params['copy_to'],
371 module.params['copy_from'],
372 module.params['src'],
373 module.params['dst'],
374 opt_list,
375 module.params['columns'],
376 module.params['session_role'])
377
378 # Note: we don't need to check mutually exclusive params here, because they are
379 # checked automatically by AnsibleModule (mutually_exclusive=[] list above).
380 if module.params.get('copy_from') and not module.params.get('dst'):
381 module.fail_json(msg='dst param is necessary with copy_from')
382
383 elif module.params.get('copy_to') and not module.params.get('src'):
384 module.fail_json(msg='src param is necessary with copy_to')
385
386 # Ensure psycopg libraries are available before connecting to DB:
387 ensure_required_libs(module)
388 # Connect to DB and make cursor object:
389 conn_params = get_conn_params(module, module.params)
390 db_connection, dummy = connect_to_db(module, conn_params, autocommit=False)
391 cursor = db_connection.cursor(**pg_cursor_args)
392
393 ##############
394 # Create the object and do main job:
395 data = PgCopyData(module, cursor)
396
397 # Note: parameters like dst, src, etc. are got
398 # from module object into data object of PgCopyData class.
399 # Therefore not need to pass args to the methods below.
400 # Note: check mode is implemented inside the methods below
401 # by checking passed module.check_mode arg.
402 if module.params.get('copy_to'):
403 data.copy_to()
404
405 elif module.params.get('copy_from'):
406 data.copy_from()
407
408 # Finish:
409 if module.check_mode:
410 db_connection.rollback()
411 else:
412 db_connection.commit()
413
414 cursor.close()
415 db_connection.close()
416
417 # Return some values:
418 module.exit_json(
419 changed=data.changed,
420 queries=data.executed_queries,
421 src=data.src,
422 dst=data.dst,
423 )
424
425
426 if __name__ == '__main__':
427 main()