Python pymysql.err() Examples

The following are 9 code examples of pymysql.err(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pymysql , or try the search function .
Example #1
Source File: database.py    From ACE with Apache License 2.0 6 votes vote down vote up
def use_db(method=None, name=None):
    """Utility decorator to pass an opened database connection and cursor object as keyword
       parameters db and c respectively. Execute is wrapped in a try/catch for database errors.
       Returns None on error and logs error message and stack trace."""

    if method is None:
        return functools.partial(use_db, name=name)

    @functools.wraps(method)
    def wrapper(*args, **kwargs):
        try:
            with get_db_connection(name=name) as db:
                c = db.cursor()
                return method(db=db, c=c, *args, **kwargs)
        except pymysql.err.MySQLError as e:
            logging.error("database error: {}".format(e))
            report_exception()
            et, ei, tb = sys.exc_info()
            raise e.with_traceback(tb)

    return wrapper 
Example #2
Source File: database.py    From ACE with Apache License 2.0 6 votes vote down vote up
def add_delayed_analysis_request(root, observable, analysis_module, next_analysis, exclusive_uuid=None, db=None, c=None):
    try:
        #logging.info("adding delayed analysis uuid {} observable_uuid {} analysis_module {} delayed_until {} node {} exclusive_uuid {} storage_dir {}".format(
                     #root.uuid, observable.id, analysis_module.config_section, next_analysis, saq.SAQ_NODE_ID, exclusive_uuid, root.storage_dir))

        execute_with_retry(db, c, """
                           INSERT INTO delayed_analysis ( uuid, observable_uuid, analysis_module, delayed_until, node_id, exclusive_uuid, storage_dir, insert_date ) 
                           VALUES ( %s, %s, %s, %s, %s, %s, %s, NOW() )""", 
                          ( root.uuid, observable.id, analysis_module.config_section, next_analysis, saq.SAQ_NODE_ID, exclusive_uuid, root.storage_dir ))
        db.commit()

        logging.info("added delayed analysis uuid {} observable_uuid {} analysis_module {} delayed_until {} node {} exclusive_uuid {} storage_dir {}".format(
                     root.uuid, observable.id, analysis_module.config_section, next_analysis, saq.SAQ_NODE_ID, exclusive_uuid, root.storage_dir))

    except pymysql.err.IntegrityError as ie:
        logging.warning(str(ie))
        logging.warning("already waiting for delayed analysis on {} by {} for {}".format(
                         root, analysis_module.config_section, observable))
        return True
    except Exception as e:
        logging.error("unable to insert delayed analysis on {} by {} for {}: {}".format(
                         root, analysis_module.config_section, observable, e))
        report_exception()
        return False 
Example #3
Source File: test_sql.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #4
Source File: test_sql.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #5
Source File: test_sql.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #6
Source File: test_sql.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #7
Source File: test_sql.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #8
Source File: database.py    From ACE with Apache License 2.0 4 votes vote down vote up
def sync_tag_mapping(self, tag):
        tag_id = None

        with get_db_connection() as db:
            cursor = db.cursor()
            for _ in range(3): # make sure we don't enter an infinite loop here
                cursor.execute("SELECT id FROM tags WHERE name = %s", ( tag.name, ))
                result = cursor.fetchone()
                if result:
                    tag_id = result[0]
                    break
                else:
                    try:
                        execute_with_retry(db, cursor, "INSERT IGNORE INTO tags ( name ) VALUES ( %s )""", ( tag.name, ))
                        db.commit()
                        continue
                    except pymysql.err.InternalError as e:
                        if e.args[0] == 1062:

                            # another process added it just before we did
                            try:
                                db.rollback()
                            except:
                                pass

                            break
                        else:
                            raise e

            if not tag_id:
                logging.error("unable to find tag_id for tag {}".format(tag.name))
                return

            try:
                execute_with_retry(db, cursor, "INSERT IGNORE INTO tag_mapping ( alert_id, tag_id ) VALUES ( %s, %s )", ( self.id, tag_id ))
                db.commit()
                logging.debug("mapped tag {} to {}".format(tag, self))
            except pymysql.err.InternalError as e:
                if e.args[0] == 1062: # already mapped
                    return
                else:
                    raise e 
Example #9
Source File: database.py    From ACE with Apache License 2.0 4 votes vote down vote up
def acquire_lock(_uuid, lock_uuid=None, lock_owner=None, db=None, c=None):
    """Attempts to acquire a lock on a workitem by inserting the uuid into the locks database table.
       Returns False if a lock already exists or the lock_uuid if the lock was acquired.
       If a lock_uuid is not given, then a random one is generated and used and returned on success."""

    try:
        if lock_uuid is None:
            lock_uuid = str(uuid.uuid4())

        execute_with_retry(db, c, "INSERT INTO locks ( uuid, lock_uuid, lock_owner, lock_time ) VALUES ( %s, %s, %s, NOW() )", 
                          ( _uuid, lock_uuid, lock_owner ), commit=True)

        logging.debug("locked {} with {}".format(_uuid, lock_uuid))
        return lock_uuid

    except pymysql.err.IntegrityError as e:
        # if a lock already exists -- make sure it's owned by someone else
        try:
            db.rollback()
            # assume we already own the lock -- this will be true in subsequent calls
            # to acquire the lock
            execute_with_retry(db, c, """
UPDATE locks 
SET 
    lock_time = NOW(),
    lock_uuid = %s,
    lock_owner = %s
WHERE 
    uuid = %s 
    AND ( lock_uuid = %s OR TIMESTAMPDIFF(SECOND, lock_time, NOW()) >= %s )
""", (lock_uuid, lock_owner, _uuid, lock_uuid, saq.LOCK_TIMEOUT_SECONDS))
            db.commit()

            c.execute("SELECT lock_uuid, lock_owner FROM locks WHERE uuid = %s", (_uuid,))
            row = c.fetchone()
            if row:
                current_lock_uuid, current_lock_owner = row
                if current_lock_uuid == lock_uuid:
                    logging.debug("locked {} with {}".format(_uuid, lock_uuid))
                    return lock_uuid

                # lock was acquired by someone else
                logging.debug("attempt to acquire lock {} failed (already locked by {}: {})".format(
                             _uuid, current_lock_uuid, current_lock_owner))

            else:
                # lock was acquired by someone else
                logging.info("attempt to acquire lock {} failed".format(_uuid))

            return False

        except Exception as e:
            logging.error("attempt to acquire lock failed: {}".format(e))
            report_exception()
            return False

    except Exception as e:
        logging.error("attempt to acquire lock failed: {}".format(e))
        report_exception()
        return False