Beispiel #1
0
 def stop_slave(self):
     if not self.is_slave_running():
         raise OperationalError("Slave is not running")
     cursor = self.cursor()
     cursor.execute('STOP SLAVE')
     messages = cursor.messages
     cursor.close()
     if messages:
         raise OperationalError("%s[%d]: %s" % messages[1])
Beispiel #2
0
 def _query(self, query, allow_reconnect=False):
     """
       Send a query to MySQL server.
       It reconnects automatically if needed and the following conditions are
       met:
        - It has not just tried to reconnect (ie, this function will not
          attempt to connect twice per call).
        - This connection is not transactional and has set not MySQL locks,
          because they are bound to the connection. This check can be
          overridden by passing allow_reconnect with True value.
     """
     try:
         self.db.query(query)
     except OperationalError, m:
         if m[0] in query_syntax_error:
             raise OperationalError(m[0], '%s: %s' % (m[1], query))
         if m[0] in lock_error:
             raise ConflictError('%s: %s: %s' % (m[0], m[1], query))
         if m[0] in query_timeout_error:
             raise TimeoutReachedError('%s: %s: %s' % (m[0], m[1], query))
         if (allow_reconnect or not self._use_TM) and \
           m[0] in hosed_connection:
             self._forceReconnection()
             self.db.query(query)
         else:
             LOG('ZMySQLDA', ERROR, 'query failed: %s' % (query, ))
             raise
Beispiel #3
0
    def testExceptionsInImmortalMode(self):
        """
        в бессметрном режиме никакие исключения не рейзятся никогда
        """
        with mock.patch('django.db.models.query.QuerySet.iterator') as \
                patched_iterator:

            patched_iterator.side_effect = OperationalError()
            qs = SphinxQuerySet(model=TagsIndex)
            self.assertEqual(list(qs.all()), [])
Beispiel #4
0
 def server_version(self):
     """
     server_version(self)
     returns a numeric tuple: major, minor, revision versions (respectively)
     """
     version = self.get_server_info()
     m = re.match(r'^(\d+)\.(\d+)\.(\d+)', version)
     if m:
         return tuple(map(int, m.groups()))
     else:
         # TODO: make this prettier
         raise OperationalError("Could not match server version")
Beispiel #5
0
def process_pm():
    df_final = get_pm_merged()

    for chunk in tqdm(np.array_split(df_final, 10_000)):
        i = chunk[['EUtranCellFDD']].head(1).index.values[0]
        try:
            chunk.to_sql('pm_merged',
                         engine_mysql,
                         index=False,
                         if_exists='append')
            if i % 100_000 == 0:
                logger.info(f'{i} completed')
        except OperationalError:
            logger.error(f'{i}')
            logger.error(OperationalError.__repr__(), f'at {i}')
Beispiel #6
0
    def testRepeatOnSecondException(self):
        """
        в случае, если при повторной попытке итерации
        опять возникает также самая ошибка, она всетаки должна срейзиться
        """

        with mock.patch('django.db.models.query.QuerySet.iterator') as \
                patched_iterator:

            patched_iterator.side_effect = OperationalError(
                'Connection reset by peer')

            qs = SphinxQuerySet(model=TagsIndex)

            with self.assertRaises(OperationalError):
                list(qs.all())
Beispiel #7
0
    def testNoRepeatOnUnknownException(self):
        """
        при эксепшне с другим текстом, должны получить ошибку
        """

        with mock.patch('django.db.models.query.QuerySet.iterator') as \
                patched_iterator:

            patched_iterator.side_effect = [
                OperationalError('some other error'), None
            ]

            qs = SphinxQuerySet(model=TagsIndex)

            with self.assertRaises(OperationalError):
                list(qs.all())
Beispiel #8
0
    def test_503_page(self):
        handler500 = self._get_handler500()

        # to make a mock call to the django view functions you need a request
        fake_request = RequestFactory().request(**{'wsgi.input': None})

        # the reason for first causing an exception to be raised is because
        # the handler500 function is only called by django when an exception
        # has been raised which means sys.exc_info() is something.
        try:
            raise OperationalError("unable to connect!")
        except OperationalError:
            # do this inside a frame that has a sys.exc_info()
            response = handler500(fake_request)
            eq_(response.status_code, 503)
            ok_('Temporarily Unavailable' in response.content)
Beispiel #9
0
    def __call__(self, **fileds):
        if len(fileds) < 1:
            raise OperationalError("Must have unless 1 field to update")
        _params = []
        _cols = []

        for i in fileds.keys():
            _cols.append("".join(["`", i, '`', '=%s']))

        for i in fileds.values():
            _params.append(i)

        _sql_slice = ["UPDATE ", self._tablename, " SET ", ",".join(_cols)]
        if self._where:
            _sql_slice.append(" WHERE " + self._where)

        _sql = "".join(_sql_slice)

        return self.db._execute_affected_rows(_sql, *_params)
Beispiel #10
0
    def testRepeatOnKnownException(self):
        """
        проверяем механизм попытки повторения операции
        получения данных QuerySet при определенных ошибках
        """

        tag = TagsIndex.objects.all()[0]


        with mock.patch('django.db.models.query.QuerySet.iterator') as \
                patched_iterator:

            patched_iterator.side_effect = [
                OperationalError('Connection reset by peer'), [tag]
            ]

            qs = SphinxQuerySet(model=TagsIndex)

            # Exception shall not pass!!!
            list(qs.all())
Beispiel #11
0
 def query(*args):
     raise OperationalError(-1, 'this is a test')
Beispiel #12
0
 def query(*args):
     raise OperationalError(SERVER_GONE_ERROR, 'this is a test')
Beispiel #13
0
 def query(self, *args):
     self._p.revert()
     raise OperationalError(SERVER_GONE_ERROR, 'this is a test')
Beispiel #14
0
 def __call__(self, statements, return_rows):
     super(StatementFailer, self).__call__(statements, return_rows)
     from MySQLdb import OperationalError
     raise OperationalError(9999, 'This is a fake error')
Beispiel #15
0
 def _ping_connection(self, connection):
     if connection and connection.connection:
         connection.connection.ping()
     else:
         raise OperationalError((SERVER_GONE_ERROR, 'Connection lost'))