Get a cursor and run a query. Reconnect up to ``retries`` times if needed. Returns: cursor, affected rows counter Raises: SaltCacheError, AttributeError, OperationalError, InterfaceError
(conn, query, args=None, retries=3)
| 114 | |
| 115 | |
| 116 | def run_query(conn, query, args=None, retries=3): |
| 117 | """ |
| 118 | Get a cursor and run a query. Reconnect up to ``retries`` times if |
| 119 | needed. |
| 120 | Returns: cursor, affected rows counter |
| 121 | Raises: SaltCacheError, AttributeError, OperationalError, InterfaceError |
| 122 | """ |
| 123 | if __context__.get("mysql_fresh_connection"): |
| 124 | # Create a new connection if configured |
| 125 | conn = MySQLdb.connect(**__context__["mysql_kwargs"]) |
| 126 | __context__["mysql_client"] = conn |
| 127 | if conn is None: |
| 128 | conn = __context__.get("mysql_client") |
| 129 | try: |
| 130 | cur = conn.cursor() |
| 131 | |
| 132 | if not args: |
| 133 | log.debug("Doing query: %s", query) |
| 134 | out = cur.execute(query) |
| 135 | else: |
| 136 | log.debug("Doing query: %s args: %s ", query, repr(args)) |
| 137 | out = cur.execute(query, args) |
| 138 | |
| 139 | return cur, out |
| 140 | except (AttributeError, OperationalError, InterfaceError) as e: |
| 141 | if retries == 0: |
| 142 | raise |
| 143 | # reconnect creating new client |
| 144 | time.sleep(_RECONNECT_INTERVAL_SEC) |
| 145 | if conn is None: |
| 146 | log.debug("mysql_cache: creating db connection") |
| 147 | else: |
| 148 | log.info("mysql_cache: recreating db connection due to: %r", e) |
| 149 | __context__["mysql_client"] = MySQLdb.connect(**__context__["mysql_kwargs"]) |
| 150 | return run_query( |
| 151 | conn=__context__.get("mysql_client"), |
| 152 | query=query, |
| 153 | args=args, |
| 154 | retries=(retries - 1), |
| 155 | ) |
| 156 | except Exception as e: # pylint: disable=broad-except |
| 157 | if len(query) > 150: |
| 158 | query = query[:150] + "<...>" |
| 159 | raise SaltCacheError( |
| 160 | "Error running {}{}: {}".format(query, f"- args: {args}" if args else "", e) |
| 161 | ) |
| 162 | |
| 163 | |
| 164 | def _create_table(): |
no test coverage detected