Return data to an odbc server
974586
def returner(ret):
    '''
    
    '''
    conn = _get_conn(ret)
    cur = conn.cursor()
    sql = '''INSERT INTO salt_returns
            (fun, jid, retval, id, success, full_ret)
            VALUES (?, ?, ?, ?, ?, ?)'''
    cur.execute(
        sql, (
            ret['fun'],
            ret['jid'],
            salt.utils.json.dumps(ret['return']),
            ret['id'],
            ret['success'],
            salt.utils.json.dumps(ret)
        )
    )
    _close_conn(conn)
738601
def stripe_to_db(self, data):
		""""""
		val = data.get(self.name)

		# Note: 0 is a possible return value, which is 'falseish'
		if val is not None:
			return convert_tstamp(val)
383661
def event_return(events):
    '''
    

    '''
    log.debug('events data is: %s', events)

    options = _get_options()

    # Check to see if the database exists.
    _response = _request("GET", options['url'] + "_all_dbs")
    event_db = '{}-events'.format(options['db'])
    if event_db not in _response:

        # Make a PUT request to create the database.
        log.info('Creating database "%s"', event_db)
        _response = _request("PUT",
                             options['url'] + event_db,
                             user=options['user'],
                             passwd=options['passwd'])

        # Confirm that the response back was simple 'ok': true.
        if 'ok' not in _response or _response['ok'] is not True:
            log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db)
            return
        log.info('Created database "%s"', event_db)

    for event in events:
        # Call _generate_doc to get a dict object of the document we're going to shove into the database.
        log.debug('event data is: %s', event)
        doc = _generate_event_doc(event)

        # Make the actual HTTP PUT request to create the doc.
        _response = _request("PUT",
                             options['url'] + event_db + "/" + doc['_id'],
                             'application/json',
                             salt.utils.json.dumps(doc))
        # Sanity check regarding the response..
        if 'ok' not in _response or _response['ok'] is not True:
            log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response)
566935
def createDatabase( dbname, dbdesc, createapptoken = "1" )

      @dbname, @dbdesc, @createapptoken = dbname, dbdesc, createapptoken

      xmlRequestData = toXML( :dbname, @dbname )
      xmlRequestData << toXML( :dbdesc, @dbdesc )
      xmlRequestData << toXML( :createapptoken, @createapptoken )

      sendRequest( :createDatabase, xmlRequestData )

      @dbid = getResponseValue( :dbid )
      @appdbid = getResponseValue( :appdbid )
      @apptoken = getResponseValue( :apptoken )

      return self if @chainAPIcalls
      return @dbid, @appdbid
   end
585578
static function factory($connection_params) {
		$class = '';
		$dsn = '';
		$user = null;
		$password = null;

		if (!empty($connection_params['user'])) {
			$user = $connection_params['user'];
		}

		if (!empty($connection_params['password'])) {
			$password = $connection_params['password'];
		}

		$options = array(
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
		);

		if (
			isset($connection_params['persistant']) &&
			(
				true === $connection_params['persistant']
				|| 1 === $connection_params['persistant']
				|| 'true' === $connection_params['persistant']
				|| '1' === $connection_params['persistant']
				|| 'on' === strtolower($connection_params['persistant'])
			)
		) {
			$options[PDO::ATTR_PERSISTENT] = true;
		}

		switch ($connection_params['driver']) {
			case 'access':

//				You may need to download the AccessDatabaseEngine.exe from Microsoft.
//
//				http://www.microsoft.com/en-us/download/details.aspx?id=23734 (2007)
//				http://www.microsoft.com/en-us/download/details.aspx?id=13255 (2010)
//
//				After the download finishes, and installs for your architecture (32 or 64 bit), You will need to create an ODBC connection.
//
//				Instead of creating an ODBC connection through your Administrative Tools, Data Sources (ODBC) interface, you will need to run
//				the 64-bit instance of Data Sources (ODBC). Run "c:\windows\sysWOW64\odbcad32.exe" -- without quotes. Then create the
//				connection to the database as you would on a 32 bit machine.

				$parts = array();
				if (!empty($connection_params['dbname'])) {
					if (!file_exists($connection_params['dbname'])) {
						throw new RuntimeException("Could not find database file: {$connection_params['dbname']}");
					}
					$parts[] = 'Dbq=' . addslashes($connection_params['dbname']);
				}
				if (!empty($connection_params['user'])) {
					$parts[] = 'Uid=' . $connection_params['user'];
					$user = null;
				}
				if (!empty($connection_params['password'])) {
					$parts[] = 'Pwd=' . $connection_params['password'];
					$password = null;
				}
				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = 'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' . implode(';', $parts);
				$class = 'DBAccess';
				break;

			case 'sqlite':
			case 'sqlite2':
				$dsn = $connection_params['driver'] . ':' . $connection_params['dbname'];
				$class = 'DBSQLite';
				break;

			case 'mysql':
				$parts = array();
				if (!empty($connection_params['host'])) {
					$parts[] = 'host=' . $connection_params['host'];
				}
				if (!empty($connection_params['port'])) {
					$parts[] = 'port=' . $connection_params['port'];
				}
				if (!empty($connection_params['unix_socket'])) {
					$parts[] = 'unix_socket=' . $connection_params['unix_socket'];
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = 'mysql:' . implode(';', $parts);
				$class = 'DBMySQL';
				break;

			case 'oracle':
			case 'oci':
				$parts = array();
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['charset'])) {
					$parts[] = 'charset=' . $connection_params['charset'];
				}
				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = 'oci:' . implode(';', $parts);
				$class = 'DBOracle';
				break;

			case 'pgsql':
				$parts = array();
				if (!empty($connection_params['host'])) {
					$parts[] = 'host=' . $connection_params['host'];
				}
				if (!empty($connection_params['port'])) {
					$parts[] = 'port=' . $connection_params['port'];
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['user'])) {
					$parts[] = 'user=' . $connection_params['user'];
				}
				if (!empty($connection_params['password'])) {
					$parts[] = 'password=' . $connection_params['password'];
				}
				foreach ($parts as &$v) {
					$v = str_replace(' ', '\ ', $v);
				}
				$dsn = 'pgsql:' . implode(' ', $parts);
				$user = null;
				$password = null;
				$class = 'DBPostgres';
				break;

			case 'sqlsrv':
				if (!empty($connection_params['host'])) {
					$parts[] = 'server=' . $connection_params['host'];
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'database=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['charset'])) {
					$parts[] = 'charset=' . $connection_params['charset'];
				}
				if (!empty($connection_params['appname'])) {
					$parts[] = 'appname=' . $connection_params['appname'];
				}

				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = $connection_params['driver'] . ':' . implode(';', $parts);
				$class = 'DBMSSQL';
				break;
			case 'mssql':
			case 'sybase':
			case 'dblib':
				if (!empty($connection_params['host'])) {
					$host = 'host=' . $connection_params['host'];
					if (!empty($connection_params['port'])) {
						$host .= ':' . $connection_params['port'];
					}
					$parts[] = $host;
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['charset'])) {
					$parts[] = 'charset=' . $connection_params['charset'];
				}
				if (!empty($connection_params['appname'])) {
					$parts[] = 'appname=' . $connection_params['appname'];
				}

				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = $connection_params['driver'] . ':' . implode(';', $parts);
				$class = 'DBMSSQL';
				break;

			default:
				throw new RuntimeException("Unsupported database driver: " . $connection_params['driver'] . ": Check your configuration file");
		}

		try {
			$conn = new $class($dsn, $user, $password, $options);
		} catch (Exception $e) {
			throw new RuntimeException($e->getMessage() . ' DSN: ' . $dsn);
		}

		if (!empty($connection_params['dbname'])) {
			$conn->dbName = $connection_params['dbname'];
		}
		$conn->driver = $connection_params['driver'];

		return $conn;
	}
338267
async def execute(
        self,
        db_name,
        sql,
        params=None,
        truncate=False,
        custom_time_limit=None,
        page_size=None,
    ):
        """"""
        page_size = page_size or self.page_size

        def sql_operation_in_thread(conn):
            time_limit_ms = self.sql_time_limit_ms
            if custom_time_limit and custom_time_limit < time_limit_ms:
                time_limit_ms = custom_time_limit

            with sqlite_timelimit(conn, time_limit_ms):
                try:
                    cursor = conn.cursor()
                    cursor.execute(sql, params or {})
                    max_returned_rows = self.max_returned_rows
                    if max_returned_rows == page_size:
                        max_returned_rows += 1
                    if max_returned_rows and truncate:
                        rows = cursor.fetchmany(max_returned_rows + 1)
                        truncated = len(rows) > max_returned_rows
                        rows = rows[:max_returned_rows]
                    else:
                        rows = cursor.fetchall()
                        truncated = False
                except sqlite3.OperationalError as e:
                    if e.args == ('interrupted',):
                        raise InterruptedError(e)
                    print(
                        "ERROR: conn={}, sql = {}, params = {}: {}".format(
                            conn, repr(sql), params, e
                        )
                    )
                    raise

            if truncate:
                return Results(rows, truncated, cursor.description)

            else:
                return Results(rows, False, cursor.description)

        with trace("sql", (db_name, sql.strip(), params)):
            results = await self.execute_against_connection_in_thread(
                db_name, sql_operation_in_thread
            )
        return results
444625
def _serialize(self, value, *args, **kwargs):
        """"""
        if value is not None:
            value = super(MSTimestamp, self)._serialize(value, *args) * 1e3
        return value
892660
def _get_conn(ret=None):
    '''
    
    '''
    _options = _get_options(ret)
    dsn = _options.get('dsn')
    user = _options.get('user')
    passwd = _options.get('passwd')

    return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format(
            dsn,
            user,
            passwd))
805152
def db_list(user=None, host=None, port=None, maintenance_db=None,
            password=None, runas=None):
    '''
    
    '''

    ret = {}

    query = (
        'SELECT datname as "Name", pga.rolname as "Owner", '
        'pg_encoding_to_char(encoding) as "Encoding", '
        'datcollate as "Collate", datctype as "Ctype", '
        'datacl as "Access privileges", spcname as "Tablespace" '
        'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts '
        'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace'
    )

    rows = psql_query(query, runas=runas, host=host, user=user,
                      port=port, maintenance_db=maintenance_db,
                      password=password)

    for row in rows:
        ret[row['Name']] = row
        ret[row['Name']].pop('Name')

    return ret
843212
def _handle_dbproc_call(self, parts, parameters_metadata):
        """"""
        for part in parts:
            if part.kind == part_kinds.ROWSAFFECTED:
                self.rowcount = part.values[0]
            elif part.kind == part_kinds.TRANSACTIONFLAGS:
                pass
            elif part.kind == part_kinds.STATEMENTCONTEXT:
                pass
            elif part.kind == part_kinds.OUTPUTPARAMETERS:
                self._buffer = part.unpack_rows(parameters_metadata, self.connection)
                self._received_last_resultset_part = True
                self._executed = True
            elif part.kind == part_kinds.RESULTSETMETADATA:
                self.description, self._column_types = self._handle_result_metadata(part)
            elif part.kind == part_kinds.RESULTSETID:
                self._resultset_id = part.value
            elif part.kind == part_kinds.RESULTSET:
                self._buffer = part.unpack_rows(self._column_types, self.connection)
                self._received_last_resultset_part = part.attribute & 1
                self._executed = True
            else:
                raise InterfaceError("Stored procedure call, unexpected part kind %d." % part.kind)
        self._executed = True
1129935
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, alter_time)
                     VALUES (%s, %s, %s, to_timestamp(%s))'''
            cur.execute(sql, (tag, psycopg2.extras.Json(data),
                              __opts__['id'], time.time()))
776875
def execute(self, conn, app, release_version, pset_hash, output_label, global_tag, transaction = False):
        
        binds = {}
        binds["app_name"]=app
        binds["release_version"]=release_version
        binds["pset_hash"]=pset_hash
        binds["output_module_label"]=output_label
        binds["global_tag"]=global_tag

        result = self.dbi.processData(self.sql, binds, conn, transaction)

        plist = self.formatDict(result)

	if len(plist) < 1: return -1
        return plist[0]["output_mod_config_id"]
561980
function _query($sql,$inputarr=false)
	{

		$dbc = $this->_connectionID;
		$false = false;

	//	return rs
		if ($inputarr) {

			if (!empty($this->charPage))
				$oCmd = new COM('ADODB.Command',null,$this->charPage);
			else
				$oCmd = new COM('ADODB.Command');
			$oCmd->ActiveConnection = $dbc;
			$oCmd->CommandText = $sql;
			$oCmd->CommandType = 1;

      // Map by http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthcreateparam.asp
      // Check issue http://bugs.php.net/bug.php?id=40664 !!!
			foreach ($inputarr as $val) {
				$type = gettype($val);
				$len=strlen($val);
				if ($type == 'boolean')
					$this->adoParameterType = 11;
				else if ($type == 'integer')
					$this->adoParameterType = 3;
				else if ($type == 'double')
					$this->adoParameterType = 5;
				elseif ($type == 'string')
					$this->adoParameterType = 202;
				else if (($val === null) || (!defined($val)))
					$len=1;
				else
					$this->adoParameterType = 130;

				// name, type, direction 1 = input, len,
        		$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,$len,$val);

				$oCmd->Parameters->Append($p);
			}
			$p = false;
			$rs = $oCmd->Execute();
			$e = $dbc->Errors;
			if ($dbc->Errors->Count > 0) return $false;
			return $rs;
		}

		$rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);

		if ($dbc->Errors->Count > 0) return $false;
		if (! $rs) return $false;

		if ($rs->State == 0) {
			$true = true;
			return $true; // 0 = adStateClosed means no records returned
		}
		return $rs;
	}
670573
def post(self):
        '''
        '''
        ## format sql

        data = request.get_json()
        options, sql_raw = data.get('options'), data.get('sql_raw')

        if options == 'format':
            sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True)
            return build_response(dict(data=sql_formmated, code=200))

        elif options in ('all', 'selected'):
            conn = SQL(config.sql_host, config.sql_port, config.sql_user,
                       config.sql_pwd, config.sql_db)

            result = conn.run(sql_raw)
            return build_response(dict(data=result, code=200))
        else:

            pass







        pass
1011018
def db_get(self, db_number):
        
        logger.debug("db_get db_number: %s" % db_number)
        _buffer = buffer_type()
        result = self.library.Cli_DBGet(
            self.pointer, db_number, byref(_buffer),
            byref(c_int(buffer_size)))
        check_error(result, context="client")
        return bytearray(_buffer)
301427
def returner(ret):
    '''
    
    '''
    query = '''INSERT INTO {keyspace}.salt_returns (
                 jid, minion_id, fun, alter_time, full_ret, return, success
               ) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace())

    statement_arguments = ['{0}'.format(ret['jid']),
                           '{0}'.format(ret['id']),
                           '{0}'.format(ret['fun']),
                           int(time.time() * 1000),
                           salt.utils.json.dumps(ret).replace("'", "''"),
                           salt.utils.json.dumps(ret['return']).replace("'", "''"),
                           ret.get('success', False)]

    # cassandra_cql.cql_query may raise a CommandExecutionError
    try:
        __salt__['cassandra_cql.cql_query_with_prepare'](query,
                                                         'returner_return',
                                                         tuple(statement_arguments),
                                                         asynchronous=True)
    except CommandExecutionError:
        log.critical('Could not insert into salt_returns with Cassandra returner.')
        raise
    except Exception as e:
        log.critical('Unexpected error while inserting into salt_returns: %s', e)
        raise

    # Store the last function called by the minion
    # The data in salt.minions will be used by get_fun and get_minions
    query = '''INSERT INTO {keyspace}.minions (
                 minion_id, last_fun
               ) VALUES (?, ?)'''.format(keyspace=_get_keyspace())

    statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])]

    # cassandra_cql.cql_query may raise a CommandExecutionError
    try:
        __salt__['cassandra_cql.cql_query_with_prepare'](query,
                                                         'returner_minion',
                                                         tuple(statement_arguments),
                                                         asynchronous=True)
    except CommandExecutionError:
        log.critical('Could not store minion ID with Cassandra returner.')
        raise
    except Exception as e:
        log.critical(
            'Unexpected error while inserting minion ID into the minions '
            'table: %s', e
        )
        raise
658784
function getDatabase(database, options, callback) {
    getDatabaseConnector(database, options, returnDatabase)

    function returnDatabase(err, databaseConnector) {
        if (err) {
            return callback(err)
        }

        var db = databaseConnector.db(database)

        callback(null, db)
    }
}