def query(self, *query_params) -> DatabaseResult: """Run the query, return instance of DatabaseResult for accessing the result. Accepts either (preferred) psycopg2-style query and parameters: # Dictionary parameters (preferred): db.query('SELECT * FROM foo WHERE bar = %(bar)s AND baz = %(baz)s', {'bar': bar, 'baz': baz}) # Dictionary parameters with tuple: db.query('SELECT * FROM foo WHERE bar IN %(bar)s, {'bar': tuple(['a', 'b', 'c'])}) # Tuple parameters: db.query('SELECT * FROM foo WHERE bar = %s AND baz = %s', (bar, baz,)) ...or DBD::Pg (DBIx::Simple) form of query and parameters: db.query('SELECT * FROM foo WHERE bar = ? AND baz = ?', bar, baz) """ # MC_REWRITE_TO_PYTHON: remove after porting queries to named parameter style query_params = convert_dbd_pg_arguments_to_psycopg2_format( *query_params) if len(query_params) == 0: raise McQueryException("Query is unset.") if len(query_params) > 2: raise McQueryException( "psycopg2's execute() accepts at most 2 parameters.") return DatabaseResult( cursor=self.__db, query_args=query_params, double_percentage_sign_marker=self.__double_percentage_sign_marker, print_warnings=self.__print_warnings)
def __execute(self, cursor: DictCursor, query: str, page: int, rows_per_page: int, double_percentage_sign_marker: str) -> None: query = decode_object_from_bytes_if_needed(query) if page < 1: raise McQueryPagedHashesException('Page must be 1 or bigger.') offset = (page - 1) * rows_per_page query = "%(original_query)s LIMIT ( %(rows_per_page)d + 1 ) OFFSET %(offset)s" % { 'original_query': query, 'rows_per_page': rows_per_page, 'offset': offset, } query_args = [query] query_args = convert_dbd_pg_arguments_to_psycopg2_format(*query_args) # Query rs = DatabaseResult(cursor=cursor, query_args=query_args, double_percentage_sign_marker=double_percentage_sign_marker) hashes = rs.hashes() # Truncate one_more_page = False if len(hashes) > rows_per_page: one_more_page = True del hashes[rows_per_page:] hashes_size = offset + len(hashes) if one_more_page: hashes_size += 1 pager = Pages(total_entries=hashes_size, entries_per_page=rows_per_page, current_page=page) self.__list = hashes self.__pager = pager
def execute(self) -> DatabaseResult: """Execute prepared statement.""" query_args = [self.__sql] expected_param_num = 1 for param_num, param_value in self.__arguments.items(): query_args.append(param_value) if param_num != expected_param_num: raise McPrepareException("Invalid parameter number %d" % param_num) expected_param_num += 1 query_args = convert_dbd_pg_arguments_to_psycopg2_format( *query_args, skip_decoding=True) return DatabaseResult( cursor=self.__cursor, query_args=query_args, double_percentage_sign_marker=self.__double_percentage_sign_marker)