Exemplo n.º 1
0
    def executemany(self, statement, seq_of_args):
        """Prepares and executes a database operation for given parameter sequences.

    Args:
      statement: A string, a SQL statement.
      seq_of_args: A sequence, each entry of which is a sequence or mapping of
        arguments matching the statement's bind variables, if any.

    Raises:
      InterfaceError: Unknown type used as a bind variable.
      DatabaseError: A SQL exception occurred.
      OperationalError: RPC problem.
    """
        self._CheckOpen()

        request = sql_pb2.ExecRequest()
        request.options.include_generated_keys = True

        args = None
        for args in seq_of_args:

            if not hasattr(args, '__iter__'):
                args = [args]
            bbv = request.batch.batch_bind_variable.add()
            self._AddBindVariablesToRequest(statement, args,
                                            bbv.bind_variable.add)
        request.statement = _ConvertFormatToQmark(statement, args)
        result = self._DoExec(request)
        self._rowcount = sum(result.batch_rows_updated)
Exemplo n.º 2
0
    def execute(self, statement, args=None):
        """Prepares and executes a database operation (query or command).

    Args:
      statement: A string, a SQL statement.
      args: A sequence or mapping of arguments matching the statement's bind
        variables, if any.

    Raises:
      InterfaceError: Unknown type used as a bind variable.
      DatabaseError: A SQL exception occurred.
      OperationalError: RPC problem.
    """
        self._CheckOpen()

        request = sql_pb2.ExecRequest()
        request.options.include_generated_keys = True
        if args is not None:

            if not hasattr(args, '__iter__'):
                args = [args]
            self._AddBindVariablesToRequest(statement, args,
                                            request.bind_variable.add)
        request.statement = _ConvertFormatToQmark(statement, args)
        self._DoExec(request)
Exemplo n.º 3
0
    def execute(self, statement, args=()):
        """Prepares and executes a database operation (query or command).

    Args:
      statement: A string, a SQL statement.
      args: A sequence of arguments matching the statement's bind variables,
        if any.

    Raises:
      InterfaceError: Unknown type used as a bind variable.
      DatabaseError: A SQL exception occurred.
      OperationalError: RPC problem.
    """
        self._CheckOpen()

        request = sql_pb2.ExecRequest()
        request.statement = statement
        for i, arg in enumerate(args):
            bv = request.bind_variable.add()
            bv.position = i + 1
            if arg is None:
                bv.type = jdbc_type.NULL
            else:
                try:
                    bv.type, bv.value = self._EncodeVariable(arg)
                except TypeError:
                    raise InterfaceError('unknown type %s for arg %d' %
                                         (type(arg), i))

        response = self._conn.MakeRequest('Exec', request)
        result = response.result
        if result.HasField('sql_exception'):
            raise DatabaseError(result.sql_exception.message)

        self._rows = collections.deque()
        if result.rows.tuples:
            self._rowcount = len(result.rows.tuples)
            self._description = []
            for column in result.rows.columns:
                self._description.append(
                    (column.name, column.type, column.display_size, None,
                     column.precision, column.scale, column.nullable))
            for tuple_proto in result.rows.tuples:
                row = []
                nulls = set(tuple_proto.nulls)
                value_index = 0
                for i, column_descr in enumerate(self._description):
                    if i in nulls:
                        row.append(None)
                    else:
                        row.append(
                            self._DecodeVariable(
                                column_descr[1],
                                tuple_proto.values[value_index]))
                        value_index += 1
                self._rows.append(row)
        else:
            self._rowcount = result.rows_updated
            self._description = None
Exemplo n.º 4
0
    def callproc(self, procname, args=()):
        """Calls a stored database procedure with the given name.

    Args:
      procname: A string, the name of the stored procedure.
      args: A sequence of parameters to use with the procedure.

    Returns:
      A modified copy of the given input args. Input parameters are left
      untouched, output and input/output parameters replaced with possibly new
      values.

    Raises:
      InternalError: The cursor has been closed, or no statement has been
        executed yet.
      DatabaseError: A SQL exception occurred.
      OperationalError: RPC problem.
    """
        self._CheckOpen()
        self._Reset()

        request = sql_pb2.ExecRequest()
        request.statement_type = sql_pb2.ExecRequest.CALLABLE_STATEMENT
        request.statement = 'CALL %s(%s)' % (procname, ','.join(
            '?' * len(args)))

        self._AddBindVariablesToRequest(
            request.statement,
            args,
            request.bind_variable.add,
            direction=client_pb2.BindVariableProto.INOUT)
        result = self._DoExec(request)
        self._executed = request.statement

        return_args = list(args[:])
        for var in result.output_variable:
            return_args[var.position - 1] = self._DecodeVariable(
                var.type, var.value)
        return tuple(return_args)
Exemplo n.º 5
0
 def _FetchMoreRows(self):
     """Fetches more rows from the server for a previously executed statement."""
     request = sql_pb2.ExecRequest()
     request.statement_id = self._statement_id
     self._DoExec(request)
Exemplo n.º 6
0
    def execute(self, statement, args=None):
        """Prepares and executes a database operation (query or command).

    Args:
      statement: A string, a SQL statement.
      args: A sequence of arguments matching the statement's bind variables,
        if any.

    Raises:
      InterfaceError: Unknown type used as a bind variable.
      DatabaseError: A SQL exception occurred.
      OperationalError: RPC problem.
    """
        self._CheckOpen()

        request = sql_pb2.ExecRequest()
        request.options.include_generated_keys = True
        if args is not None:

            if not hasattr(args, '__iter__'):
                args = [args]
            for i, arg in enumerate(args):
                bv = request.bind_variable.add()
                bv.position = i + 1
                if arg is None:
                    bv.type = jdbc_type.NULL
                else:
                    try:
                        bv.type, bv.value = self._EncodeVariable(arg)
                    except TypeError:
                        raise InterfaceError('unknown type %s for arg %d' %
                                             (type(arg), i))
        request.statement = _ConvertFormatToQmark(statement, args)

        response = self._conn.MakeRequest('Exec', request)
        result = response.result
        if result.HasField('sql_exception'):
            raise DatabaseError(
                '%d: %s' %
                (result.sql_exception.code, result.sql_exception.message))

        self._rows = collections.deque()
        if result.rows.columns:
            self._description = []
            for column in result.rows.columns:
                self._description.append(
                    (column.label, column.type, column.display_size, None,
                     column.precision, column.scale, column.nullable))
        else:
            self._description = None

        if result.rows.tuples:
            assert self._description, 'Column descriptions do not exist.'
            column_names = [col[0] for col in self._description]
            self._rowcount = len(result.rows.tuples)
            for tuple_proto in result.rows.tuples:
                row = []
                nulls = set(tuple_proto.nulls)
                value_index = 0
                for i, column_descr in enumerate(self._description):
                    if i in nulls:
                        row.append(None)
                    else:
                        row.append(
                            self._DecodeVariable(
                                column_descr[1],
                                tuple_proto.values[value_index]))
                        value_index += 1
                if self._use_dict_cursor:
                    assert len(column_names) == len(row)
                    row = dict(zip(column_names, row))
                else:
                    row = tuple(row)
                self._rows.append(row)
        else:
            self._rowcount = result.rows_updated

        if result.generated_keys:
            self.lastrowid = long(result.generated_keys[-1])