Return data to a mysql server
2320
def returner(ret):
    '''
    
    '''
    # if a minion is returning a standalone job, get a jobid
    if ret['jid'] == 'req':
        ret['jid'] = prep_jid(nocache=ret.get('nocache', False))
        save_load(ret['jid'], ret)

    try:
        with _get_serv(ret, commit=True) as cur:
            sql = '''INSERT INTO `salt_returns`
                     (`fun`, `jid`, `return`, `id`, `success`, `full_ret`)
                     VALUES (%s, %s, %s, %s, %s, %s)'''

            cur.execute(sql, (ret['fun'], ret['jid'],
                              salt.utils.json.dumps(ret['return']),
                              ret['id'],
                              ret.get('success', False),
                              salt.utils.json.dumps(ret)))
    except salt.exceptions.SaltMasterError as exc:
        log.critical(exc)
        log.critical('Could not store return with MySQL returner. MySQL server unavailable.')
85985
function query() {
        if(empty($this->sql)) {
            $this->_constructSql();
        }
        list($sql, $param) = $this->_constructSql();
        $this->_reset();
        return $this->execute($sql, $param);
    }
1077310
function queryData($query, $keyField=null, $resultType = MYSQLI_ASSOC)
  {
    $data = [];
    $res = $this->q($query);
    if ($keyField == null)
      $data = $res->fetch_all($resultType);
    else while ($row = $res->fetch_array($resultType))
    {
      if ($keyField)
        $data[$row[$keyField]] = $row;
    }
    $res->close();
    return $data;
  }
135192
def sql(self, stmt, parameters=None, bulk_parameters=None):
        
        if stmt is None:
            return None

        data = _create_sql_payload(stmt, parameters, bulk_parameters)
        logger.debug(
            'Sending request to %s with payload: %s', self.path, data)
        content = self._json_request('POST', self.path, data=data)
        logger.debug("JSON response for stmt(%s): %s", stmt, content)

        return content
898739
def user_info(user, host='localhost', **connection_args):
    '''
    
    '''
    dbc = _connect(**connection_args)
    if dbc is None:
        return False

    cur = dbc.cursor(MySQLdb.cursors.DictCursor)
    qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
           'Host = %(host)s')
    args = {}
    args['user'] = user
    args['host'] = host

    try:
        _execute(cur, qry, args)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return False
    result = cur.fetchone()
    log.debug(result)
    return result
329000
def _osquery(sql, format='json'):
    '''
    
    '''
    ret = {
        'result': True,
    }

    cmd = ['osqueryi'] + ['--json'] + [sql]
    res = __salt__['cmd.run_all'](cmd)
    if res['stderr']:
        ret['result'] = False
        ret['error'] = res['stderr']
    else:
        ret['data'] = salt.utils.json.loads(res['stdout'])
    log.debug('== %s ==', ret)
    return ret
240397
private function returnOutput()
    {
        $collection = new Collection($this->results);

        switch ($this->output) {
            case 'db':
                return $this->saveToDatabase($collection);
                break;
            case 'collection':
                return $collection;
                break;
            case 'json':
                return $collection->toJson();
                break;
            case 'array':
            default:
                return $collection->toArray();
        }
    }
584025
def main():
    """"""
    logger.info('Waiting for database: `%s`', MYSQL_DB)

    connect_mysql(
        host=MYSQL_HOST, port=MYSQL_PORT,
        user=MYSQL_USER, password=MYSQL_PASSWORD,
        database=MYSQL_DB
    )

    logger.info('Database `%s` found', MYSQL_DB)
954877
private function wait()
    {
        do {
            if (empty($this->queries)) {
                break;
            }
            $links = $errors = $reject = [];
            foreach ($this->queries as $link) {
                $links[] = $errors[] = $reject[] = $link['l'];
            }
            if (!mysqli_poll($links, $errors, $reject, self::$sleep, self::$usleep)) {
                continue;
            }
            foreach ($this->queries as $l => $link) {
                $promise = $this->getPromise($link);
                $cnx    = $this->getConnection($link);
                try {
                    $result = $cnx->reap_async_query();
                    if ($result instanceof mysqli_result) {
                        $promise->resolve($result);
                    } else {
                        $errNo = mysqli_errno($cnx);
                        $errStr = mysqli_error($cnx);
                        if (0 !== $errNo || 0 !== strlen($errStr)) {
                            throw new mysqli_sql_exception($errStr, $errNo);
                        } else {
                            $promise->resolve($cnx);
                        }
                    }
                } catch (mysqli_sql_exception $e) {
                    $promise->reject($e);
                }
                $this->processed++;
                unset($this->queries[$l]);
            }
        } while ($this->processed < count($this->queries));
        $this->reset();
    }
625674
def event_return(events):
    '''
    
    '''
    with _get_serv(events, commit=True) as cur:
        for event in events:
            tag = event.get('tag', '')
            data = event.get('data', '')
            sql = '''INSERT INTO `salt_events` (`tag`, `data`, `master_id`)
                     VALUES (%s, %s, %s)'''
            cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))
225157
function _query($sql,$inputarr=false)
  {
  GLOBAL $php_errormsg;
    if (isset($php_errormsg)) $php_errormsg = '';
    $this->_error = '';

                if ($inputarr) {
      if (is_array($sql)) {
        $stmtid = $sql[1];
      } else {
        $stmtid = ads_prepare($this->_connectionID,$sql);

        if ($stmtid == false) {
          $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
          return false;
        }
      }

      if (! ads_execute($stmtid,$inputarr)) {
        //@ads_free_result($stmtid);
        if ($this->_haserrorfunctions) {
          $this->_errorMsg = ads_errormsg();
          $this->_errorCode = ads_error();
        }
        return false;
      }

    } else if (is_array($sql)) {
      $stmtid = $sql[1];
      if (!ads_execute($stmtid)) {
        //@ads_free_result($stmtid);
        if ($this->_haserrorfunctions) {
          $this->_errorMsg = ads_errormsg();
          $this->_errorCode = ads_error();
        }
        return false;
      }
    } else
                        {

      $stmtid = ads_exec($this->_connectionID,$sql);

                        }

                $this->_lastAffectedRows = 0;

    if ($stmtid)
                {

      if (@ads_num_fields($stmtid) == 0) {
        $this->_lastAffectedRows = ads_num_rows($stmtid);
        $stmtid = true;

      } else {

        $this->_lastAffectedRows = 0;
        ads_binmode($stmtid,$this->binmode);
        ads_longreadlen($stmtid,$this->maxblobsize);

      }

      if ($this->_haserrorfunctions)
                        {

        $this->_errorMsg = '';
        $this->_errorCode = 0;
      }
                        else
        $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
    }
                else
                {
      if ($this->_haserrorfunctions) {
        $this->_errorMsg = ads_errormsg();
        $this->_errorCode = ads_error();
      } else
        $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
    }

    return $stmtid;

  }
342091
public function query($sql)
    {
        if (!$queryResource = mysql_query($sql, $this->dbConn)) {
            echo mysql_error();
            $this->handleError();
        } else {
            return new MySqlResult($this, $queryResource);
        }
    }
563508
def fetch(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            return conn.query(sql, *args, **kwargs).fetch()
1011096
def create_database_mysql(database: str,
                          user: str,
                          password: str,
                          server: str = "localhost",
                          port: int = 3306,
                          charset: str = "utf8",
                          collate: str = "utf8_general_ci",
                          use_unicode: bool = True) -> bool:
    """"""
    con = mysql.connect(
        host=server,
        port=port,
        user=user,
        passwd=password,
        charset=charset,
        use_unicode=use_unicode
    )
    sql = ("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET {} "
           "DEFAULT COLLATE {}").format(
        database,
        charset,
        collate
    )
    cursor = con.cursor()
    debug_sql(sql)
    cursor.execute(sql)
    log.info("Created database {}", database)
    return True
380606
def get_mysql_connection(host, user, port, password, database, ssl={}):
    

    return pymysql.connect(host=host,
                           user=user,
                           port=port,
                           password=password,
                           db=database,
                           charset='utf8mb4',
                           cursorclass=pymysql.cursors.DictCursor,
                           client_flag=pymysql.constants.CLIENT.MULTI_STATEMENTS,
                           ssl=ssl
                           )
618048
def _fetch_data_from_server(raw_data_id, mysql_cfg):
    """"""
    import pymysql
    import pymysql.cursors

    # Import configuration file
    cfg = utils.get_database_configuration()
    if cfg is None:
        return None

    # Establish database connection
    connection = pymysql.connect(host=cfg[mysql_cfg]['host'],
                                 user=cfg[mysql_cfg]['user'],
                                 passwd=cfg[mysql_cfg]['passwd'],
                                 db=cfg[mysql_cfg]['db'],
                                 cursorclass=pymysql.cursors.DictCursor)
    logging.info("Connection: %s", str(connection))
    cursor = connection.cursor()

    # Download dataset
    sql = ("SELECT `id`, `data` "
           "FROM `wm_raw_draw_data` WHERE `id`=%i") % raw_data_id
    cursor.execute(sql)
    return cursor.fetchone()
562313
def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)