
    Vh)                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlmZ d dlmZmZmZmZ d dlmZ d	Zd
Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona\  
---
module: mysql_query
short_description: Run MySQL or MariaDB queries
description:
- Runs arbitrary MySQL or MariaDB queries.
- Pay attention, the module does not support check mode!
  All queries will be executed in autocommit mode.
- To run SQL queries from a file, use M(community.mysql.mysql_db) module.
version_added: '0.1.0'
options:
  query:
    description:
    - SQL query to run. Multiple queries can be passed using YAML list syntax.
    - Must be a string or YAML list containing strings.
    - If you use I(named_args) or I(positional_args) any C(%) will be interpreted
      as a formatting character. All literal C(%) characters in the query should be
      escaped as C(%%).
    - Note that if you use the C(IF EXISTS/IF NOT EXISTS) clauses in your query
      and C(mysqlclient) or C(PyMySQL 0.10.0+) connectors, the module will report
      that the state has been changed even if it has not. If it is important in your
      workflow, use the C(PyMySQL 0.9.3) connector instead.
    type: raw
    required: true
  positional_args:
    description:
    - List of values to be passed as positional arguments to the query.
    - Mutually exclusive with I(named_args).
    type: list
    elements: raw
  named_args:
    description:
    - Dictionary of key-value arguments to pass to the query.
    - Mutually exclusive with I(positional_args).
    type: dict
  login_db:
    description:
    - Name of database to connect to and run queries against.
    type: str
  single_transaction:
    description:
    - Where passed queries run in a single transaction (C(yes)) or commit them one-by-one (C(no)).
    type: bool
    default: false
attributes:
  check_mode:
    support: none
seealso:
- module: community.mysql.mysql_db
notes:
- Compatible with MariaDB or MySQL.
author:
- Andrew Klychkov (@Andersson007)
extends_documentation_fragment:
- community.mysql.mysql
a  
# If you encounter the "Please explicitly state intended protocol" error,
# use the login_unix_socket argument
- name: Simple select query to acme db
  community.mysql.mysql_query:
    login_db: acme
    query: SELECT * FROM orders
    login_unix_socket: /run/mysqld/mysqld.sock

- name: Select query to db acme with positional arguments
  community.mysql.mysql_query:
    login_db: acme
    query: SELECT * FROM acme WHERE id = %s AND story = %s
    positional_args:
    - 1
    - test

- name: Select query to test_db with named_args
  community.mysql.mysql_query:
    login_db: test_db
    query: SELECT * FROM test WHERE id = %(id_val)s AND story = %(story_val)s
    named_args:
      id_val: 1
      story_val: test

- name: Run several insert queries against db test_db in single transaction
  community.mysql.mysql_query:
    login_db: test_db
    query:
    - INSERT INTO articles (id, story) VALUES (2, 'my_long_story')
    - INSERT INTO prices (id, price) VALUES (123, '100.00')
    single_transaction: true
ad  
executed_queries:
    description: List of executed queries.
    returned: always
    type: list
    sample: ['SELECT * FROM bar', 'UPDATE bar SET id = 1 WHERE id = 2']
query_result:
    description:
    - List of lists (sublist for each query) containing dictionaries
      in column:value form representing returned rows.
    returned: changed
    type: list
    sample: [[{"Column": "Value1"},{"Column": "Value2"}], [{"ID": 1}, {"ID": 2}]]
rowcount:
    description: Number of affected rows for each subquery.
    returned: changed
    type: list
    sample: [5, 1]
execution_time_ms:
    description:
    - A list containing execution time per query in milliseconds.
    - The measurements are done right before and after passing
      the query to the driver for execution.
    returned: success
    type: list
    sample: [7104, 85]
    version_added: '3.12.0'
N)AnsibleModule)mysql_connectmysql_common_argument_specmysql_drivermysql_driver_fail_msg)	to_native)INSERTUPDATEDELETEREPLACE)CREATEDROPALTERRENAMETRUNCATEc                     t        j                         }| j                  ||       t        t        j                         |z
  dz  d      }| |fS )Ni     )timeperf_counterexecuteround)cursorqueryargs
start_timeexec_time_mss        o/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/mysql/plugins/modules/mysql_query.pyexecute_and_return_timer!      sJ    ""$J
NN5$ $++-
:dBAFL<    c                  	   t               } | j                  t        dd      t        d      t        dd      t        d      t        d	d
             t        | d      }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }	|j                  d   }
|j                  d   }t        |t        t        f      s|j                  dt        |      z         t        |t              r|g}|D ]4  }t        |t              r|j                  d|dt        |             6 |j                  d   rd
}nd}|j                  j                  d      r|j                  d   }n-|j                  j                  d      r|j                  d   }nd }t        |j                  t               	 t        ||||
|||||	|d |!      \  }}d
}t!        t#        t$        t&        z   t         $            }g }g }g }g }d
}|D ]5  }	 t)        j*                         5  t)        j,                  d%d&t        j.                  '       	 t1        ||      \  }}|j3                  |       d d d        	 |s6|j3                  j9                         D cg c]  }t        |       c}       |j;                         d,| j=                         }t$        D ]  }||v sj>                  d,kD  sd} t&        D ]  }||v s|rd
}d
}d} 	 |j3                  j@                         |j3                  |j>                         8 |sjG                          |||||d-} |jH                  d.i | y # t        $ r,}|j                  d"|
d#t        |             Y d }~d }~ww xY w# t        j.                  $ r d}Y Tw xY w# 1 sw Y   ZxY w# t        $ rQ}|sj5                          j7                          |j                  d(|d)|d*t        |             Y d }~d }~ww xY wc c}w # t        $ r;}|sj5                          |j                  d+t        |      z         Y d }~d }~ww xY w# tB        $ r |j3                  jD                         Y |w xY w)/NrawT)typerequiredstr)r%   list)r%   elementsdictboolF)r%   default)r   login_dbpositional_args
named_argssingle_transaction))r.   r/   )argument_specmutually_exclusiver-   connect_timeout
login_userlogin_passwordclient_cert
client_keyca_certcheck_hostnameconfig_filer   z:the query option value must be a string or list, passed %s)msgz4the elements in query list must be strings, passed 'z' r0   r.   r/   
DictCursor)r9   r3   cursor_class
autocommitzRunable to connect to database, check login_user and login_password are correct or z) has the credentials. Exception message: )keyerrorz.*already exists*)actionmessagecategoryzCannot execute SQL 'z' args [z]: z!Cannot fetch rows from cursor: %sr   )changedexecuted_queriesquery_resultrowcountexecution_time_ms )%r   updater*   r   params
isinstancer'   r(   	fail_jsonr%   getr	   r
   r   	Exceptionr   lenmaxDML_QUERY_KEYWORDSDDL_QUERY_KEYWORDSwarningscatch_warningsfilterwarningsWarningr!   appendrollbackclosefetchalllstripupperrG   _last_executedAttributeError	_executedcommit	exit_json)r1   moduledbr3   r4   r5   ssl_certssl_keyssl_car9   r:   r   elemr>   	argumentsr   db_connectionerD   max_keyword_lenrF   rE   rG   rH   already_existsqr   rowkeywordkws                                 r    mainrr      s   .0M-5!&59V$VU;   #
F 
z	"Bmm$56O|,J]]#34N}}]+HmmL)G]]9%F]]#34N--.KMM'"Eec4[)Y\`af\ggh% t$$aegklpgq!rst }})*

}}*+MM"34				<	(MM,/		23	T -fj..98WfVX=K>M;GT^	!` G#03EE3OPO LHN 6)	i((* *''w0C1=1E1EG	*+B61i+X(FL%,,\:*.	U!##&//:K$L3T#Y$LM HHJq)//1) 	G!|! 3	 * 	#G!|!#G%*N"G	#	6##F$9$9: 	(m6)r  ,$.
B Fro  T8CYq\S 	T 	TT6 $++ * &*N** *   	i&&(LLNAyZcdeZf!ghh	i %M 	U&&(!DyQR|!STT		U,  	6##F$4$45	6s   N5 P('P	!O-1P:Q8Q3
+Q8R?5	O*>!O%%O*-PP	PP		P	P	Q0AQ++Q03Q88	R<0R77R<?$S'&S'__main__)
__future__r   r   r   r%   __metaclass__DOCUMENTATIONEXAMPLESRETURNr   rT   ansible.module_utils.basicr   >ansible_collections.community.mysql.plugins.module_utils.mysqlr   r   r	   r
   ansible.module_utils._textr   rR   rS   r!   rr   __name__rI   r"   r    <module>r}      sp    C B7r D
:   4  1> F  Sl zF r"   