Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Vedit Firat Arig <[email protected]>
4 # Outline and parts are reused from Mark Theunissen's mysql_db module
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: mssql_db
12 short_description: Add or remove MSSQL databases from a remote host
13 description:
14 - Add or remove MSSQL databases from a remote host.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: none
20 diff_mode:
21 support: none
22 options:
23 name:
24 description:
25 - Name of the database to add or remove.
26 required: true
27 aliases: [db]
28 type: str
29 login_user:
30 description:
31 - The username used to authenticate with.
32 type: str
33 default: ''
34 login_password:
35 description:
36 - The password used to authenticate with.
37 type: str
38 default: ''
39 login_host:
40 description:
41 - Host running the database.
42 - For named instances, use the format V(server\\instance). In that case, do not use O(login_port).
43 type: str
44 required: true
45 login_port:
46 description:
47 - Port of the MSSQL server. Requires login_host be defined as other than localhost if login_port is used.
48 - Cannot be used together with a named instance in O(login_host) (that is, V(server\\instance) format).
49 - If O(login_host) is not a named instance and O(login_port) is not specified, it defaults to V(1433).
50 type: str
51 state:
52 description:
53 - The database state.
54 default: present
55 choices: ["present", "absent", "import"]
56 type: str
57 target:
58 description:
59 - Location, on the remote host, of the dump file to read from or write to. Uncompressed SQL files (C(.sql)) files are
60 supported.
61 type: str
62 autocommit:
63 description:
64 - Automatically commit the change only if the import succeed. Sometimes it is necessary to use autocommit=true, since
65 some content can not be changed within a transaction.
66 type: bool
67 default: false
68 notes:
69 - Requires the pymssql Python package on the remote host. For Ubuntu, this is as easy as pip install pymssql (See M(ansible.builtin.pip)).
70 requirements:
71 - pymssql
72 author: Vedit Firat Arig (@vedit)
73 """
74
75 EXAMPLES = r"""
76 - name: Create a new database with name 'jackdata'
77 community.general.mssql_db:
78 name: jackdata
79 state: present
80
81 # Copy database dump file to remote host and restore it to database 'my_db'
82 - name: Copy database dump file to remote host
83 ansible.builtin.copy:
84 src: dump.sql
85 dest: /tmp
86
87 - name: Restore the dump file to database 'my_db'
88 community.general.mssql_db:
89 name: my_db
90 state: import
91 target: /tmp/dump.sql
92 """
93
94 RETURN = r"""
95 #
96 """
97
98 import os
99 import traceback
100
101 PYMSSQL_IMP_ERR = None
102 try:
103 import pymssql
104 except ImportError:
105 PYMSSQL_IMP_ERR = traceback.format_exc()
106 mssql_found = False
107 else:
108 mssql_found = True
109
110 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
111
112
113 def db_exists(conn, cursor, db):
114 cursor.execute("SELECT name FROM master.sys.databases WHERE name = %s", db)
115 conn.commit()
116 return bool(cursor.rowcount)
117
118
119 def db_create(conn, cursor, db):
120 cursor.execute(f"CREATE DATABASE [{db}]")
121 return db_exists(conn, cursor, db)
122
123
124 def db_delete(conn, cursor, db):
125 try:
126 cursor.execute(f"ALTER DATABASE [{db}] SET single_user WITH ROLLBACK IMMEDIATE")
127 except Exception:
128 pass
129 cursor.execute(f"DROP DATABASE [{db}]")
130 return not db_exists(conn, cursor, db)
131
132
133 def db_import(conn, cursor, module, db, target):
134 if os.path.isfile(target):
135 with open(target) as backup:
136 sqlQuery = f"USE [{db}]\n"
137 for line in backup:
138 if line is None:
139 break
140 elif line.startswith("GO"):
141 cursor.execute(sqlQuery)
142 sqlQuery = f"USE [{db}]\n"
143 else:
144 sqlQuery += line
145 cursor.execute(sqlQuery)
146 conn.commit()
147 return 0, "import successful", ""
148 else:
149 return 1, "cannot find target file", "cannot find target file"
150
151
152 def main():
153 module = AnsibleModule(
154 argument_spec=dict(
155 name=dict(required=True, aliases=["db"]),
156 login_user=dict(default=""),
157 login_password=dict(default="", no_log=True),
158 login_host=dict(required=True),
159 login_port=dict(),
160 target=dict(),
161 autocommit=dict(type="bool", default=False),
162 state=dict(default="present", choices=["present", "absent", "import"]),
163 )
164 )
165
166 if not mssql_found:
167 module.fail_json(msg=missing_required_lib("pymssql"), exception=PYMSSQL_IMP_ERR)
168
169 db = module.params["name"]
170 state = module.params["state"]
171 autocommit = module.params["autocommit"]
172 target = module.params["target"]
173
174 login_user = module.params["login_user"]
175 login_password = module.params["login_password"]
176 login_host = module.params["login_host"]
177 login_port = module.params["login_port"]
178
179 if "\\" in login_host and login_port is not None:
180 module.fail_json(
181 msg=r"login_port cannot be used with a named instance in login_host (server\instance format). "
182 "Named instances use the SQL Server Browser service to resolve the port automatically."
183 )
184
185 login_querystring = login_host
186 if "\\" not in login_host and login_port is not None:
187 login_querystring = f"{login_host}:{login_port}"
188
189 if login_user != "" and login_password == "":
190 module.fail_json(msg="when supplying login_user arguments login_password must be provided")
191
192 try:
193 conn = pymssql.connect(user=login_user, password=login_password, host=login_querystring, database="master")
194 cursor = conn.cursor()
195 except Exception as e:
196 if "Unknown database" in str(e):
197 errno, errstr = e.args
198 module.fail_json(msg=f"ERROR: {errno} {errstr}")
199 else:
200 module.fail_json(
201 msg="unable to connect, check login_user and login_password are correct, or alternatively check your "
202 "@sysconfdir@/freetds.conf / ${HOME}/.freetds.conf"
203 )
204
205 conn.autocommit(True)
206 changed = False
207
208 if db_exists(conn, cursor, db):
209 if state == "absent":
210 try:
211 changed = db_delete(conn, cursor, db)
212 except Exception as e:
213 module.fail_json(msg=f"error deleting database: {e}")
214 elif state == "import":
215 conn.autocommit(autocommit)
216 rc, stdout, stderr = db_import(conn, cursor, module, db, target)
217
218 if rc != 0:
219 module.fail_json(msg=stderr)
220 else:
221 module.exit_json(changed=True, db=db, msg=stdout)
222 else:
223 if state == "present":
224 try:
225 changed = db_create(conn, cursor, db)
226 except Exception as e:
227 module.fail_json(msg=f"error creating database: {e}")
228 elif state == "import":
229 try:
230 changed = db_create(conn, cursor, db)
231 except Exception as e:
232 module.fail_json(msg=f"error creating database: {e}")
233
234 conn.autocommit(autocommit)
235 rc, stdout, stderr = db_import(conn, cursor, module, db, target)
236
237 if rc != 0:
238 module.fail_json(msg=stderr)
239 else:
240 module.exit_json(changed=True, db=db, msg=stdout)
241
242 module.exit_json(changed=changed, db=db)
243
244
245 if __name__ == "__main__":
246 main()