Debian Codegraph @

ansible_collections/community/general/plugins/modules/odbc.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019, John Westcott <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: odbc
11 author: "John Westcott IV (@john-westcott-iv)"
12 version_added: "1.0.0"
13 short_description: Execute SQL using ODBC
14 description:
15 - Read/Write info using ODBC drivers.
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: none
21 diff_mode:
22 support: none
23 options:
24 dsn:
25 description:
26 - The connection string passed into ODBC.
27 required: true
28 type: str
29 query:
30 description:
31 - The SQL query to perform.
32 required: true
33 type: str
34 params:
35 description:
36 - Parameters to pass to the SQL query.
37 type: list
38 elements: str
39 commit:
40 description:
41 - Perform a commit after the execution of the SQL query.
42 - Some databases allow a commit after a select whereas others raise an exception.
43 - Default is V(true) to support legacy module behavior.
44 type: bool
45 default: true
46 version_added: 1.3.0
47 requirements:
48 - "pyodbc"
49
50 notes:
51 - Like the command module, this module always returns V(changed=true) whether or not the query would change the database.
52 - 'To alter this behavior you can use C(changed_when): [true or false].'
53 - For details about return values (RV(description) and RV(row_count)) see U(https://github.com/mkleehammer/pyodbc/wiki/Cursor).
54 """
55
56 EXAMPLES = r"""
57 - name: Set some values in the test db
58 community.general.odbc:
59 dsn: "DRIVER={ODBC Driver 13 for SQL Server};Server=db.ansible.com;Database=my_db;UID=admin;PWD=password;"
60 query: "Select * from table_a where column1 = ?"
61 params:
62 - "value1"
63 commit: false
64 changed_when: false
65 """
66
67 # @FIXME RV 'results' is meant to be used when 'loop:' was used with the module.
68 RETURN = r"""
69 results:
70 description: List of lists of strings containing selected rows, likely empty for DDL statements.
71 returned: success
72 type: list
73 elements: list
74 description:
75 description: "List of dicts about the columns selected from the cursors, likely empty for DDL statements. See notes."
76 returned: success
77 type: list
78 elements: dict
79 row_count:
80 description: "The number of rows selected or modified according to the cursor defaults to V(-1). See notes."
81 returned: success
82 type: str
83 """
84
85 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
86
87 HAS_PYODBC = None
88 try:
89 import pyodbc
90
91 HAS_PYODBC = True
92 except ImportError:
93 HAS_PYODBC = False
94
95
96 def main():
97 module = AnsibleModule(
98 argument_spec=dict(
99 dsn=dict(type="str", required=True, no_log=True),
100 query=dict(type="str", required=True),
101 params=dict(type="list", elements="str"),
102 commit=dict(type="bool", default=True),
103 ),
104 )
105
106 dsn = module.params.get("dsn")
107 query = module.params.get("query")
108 params = module.params.get("params")
109 commit = module.params.get("commit")
110
111 if not HAS_PYODBC:
112 module.fail_json(msg=missing_required_lib("pyodbc"))
113
114 # Try to make a connection with the DSN
115 connection = None
116 try:
117 connection = pyodbc.connect(dsn)
118 except Exception as e:
119 module.fail_json(msg=f"Failed to connect to DSN: {e}")
120
121 result = dict(
122 changed=True,
123 description=[],
124 row_count=-1,
125 results=[],
126 )
127
128 try:
129 cursor = connection.cursor()
130
131 if params:
132 cursor.execute(query, params)
133 else:
134 cursor.execute(query)
135 try:
136 # Get the rows out into an 2d array
137 for row in cursor.fetchall():
138 new_row = [f"{column}" for column in row]
139 result["results"].append(new_row)
140
141 # Return additional information from the cursor
142 for row_description in cursor.description:
143 description = {}
144 description["name"] = row_description[0]
145 description["type"] = row_description[1].__name__
146 description["display_size"] = row_description[2]
147 description["internal_size"] = row_description[3]
148 description["precision"] = row_description[4]
149 description["scale"] = row_description[5]
150 description["nullable"] = row_description[6]
151 result["description"].append(description)
152
153 result["row_count"] = cursor.rowcount
154 except pyodbc.ProgrammingError:
155 pass
156 except Exception as e:
157 module.fail_json(msg=f"Exception while reading rows: {e}")
158
159 if commit:
160 cursor.commit()
161 cursor.close()
162 except Exception as e:
163 module.fail_json(msg=f"Failed to execute query: {e}")
164 finally:
165 connection.close()
166
167 module.exit_json(**result)
168
169
170 if __name__ == "__main__":
171 main()