From e4f94c15c6ef9dcee26d98c977744331b51db4a1 Mon Sep 17 00:00:00 2001 From: Gareth Andrew Lloyd Date: Wed, 22 Nov 2023 13:05:02 +0000 Subject: [PATCH] Fixes for clang-tidy / sonar issues (#1536) --- include/mgp.hpp | 292 +++++++++--------- query_modules/schema.cpp | 2 - src/audit/log.cpp | 5 +- src/audit/log.hpp | 2 +- src/auth/models.cpp | 13 +- src/auth/models.hpp | 26 +- src/communication/bolt/client.hpp | 5 +- .../v1/decoder/chunked_decoder_buffer.hpp | 4 +- src/communication/bolt/v1/decoder/decoder.hpp | 6 +- .../bolt/v1/encoder/base_encoder.hpp | 10 +- .../v1/encoder/chunked_encoder_buffer.hpp | 4 +- .../bolt/v1/encoder/client_encoder.hpp | 2 +- src/communication/bolt/v1/encoder/encoder.hpp | 2 +- src/communication/bolt/v1/states/handlers.hpp | 6 +- src/communication/bolt/v1/states/init.hpp | 8 +- src/communication/bolt/v1/value.hpp | 2 +- src/communication/client.hpp | 4 +- src/communication/context.cpp | 6 +- src/communication/helpers.cpp | 4 +- src/communication/helpers.hpp | 4 +- src/communication/http/listener.hpp | 2 +- src/communication/listener.hpp | 5 +- src/communication/result_stream_faker.hpp | 4 +- src/communication/session.hpp | 4 +- src/communication/v2/listener.hpp | 2 +- src/communication/v2/session.hpp | 2 +- src/communication/websocket/server.hpp | 5 +- src/dbms/dbms_handler.hpp | 2 +- src/dbms/handler.hpp | 2 +- src/glue/SessionHL.cpp | 5 +- src/glue/SessionHL.hpp | 2 +- src/glue/communication.cpp | 4 +- src/helpers.hpp | 2 +- src/http_handlers/metrics.hpp | 1 - src/integrations/kafka/consumer.hpp | 4 +- src/integrations/pulsar/consumer.cpp | 4 +- src/io/network/endpoint.hpp | 10 +- src/io/network/epoll.hpp | 4 +- src/io/network/socket.hpp | 3 +- src/kvstore/kvstore.cpp | 2 +- src/query/common.hpp | 6 +- src/query/cypher_query_interpreter.hpp | 6 +- src/query/db_accessor.hpp | 2 - src/query/dump.cpp | 4 +- src/query/frame_change.hpp | 4 +- src/query/frontend/ast/ast.hpp | 15 +- src/query/frontend/ast/pretty_print.cpp | 2 +- src/query/frontend/opencypher/parser.hpp | 4 +- src/query/frontend/semantic/symbol.hpp | 19 +- .../frontend/semantic/symbol_generator.hpp | 2 +- src/query/frontend/semantic/symbol_table.hpp | 2 +- src/query/frontend/stripped.cpp | 37 +-- src/query/frontend/stripped.hpp | 4 +- .../frontend/stripped_lexer_constants.hpp | 8 +- src/query/interpret/eval.hpp | 4 +- src/query/interpreter.cpp | 31 +- src/query/interpreter.hpp | 2 +- src/query/plan/operator.cpp | 81 ++--- src/query/plan/operator.hpp | 111 ++++--- src/query/plan/planner.hpp | 8 +- src/query/plan/preprocess.cpp | 13 +- src/query/plan/preprocess.hpp | 48 +-- src/query/plan/profile.hpp | 7 +- src/query/plan/rewrite/index_lookup.hpp | 7 +- src/query/plan/variable_start_planner.cpp | 18 +- src/query/plan/variable_start_planner.hpp | 38 +-- src/query/plan/vertex_count_cache.hpp | 9 +- .../include/replication/config.hpp | 4 +- .../replication/replication_server.hpp | 4 +- src/requests/requests.cpp | 2 +- src/rpc/client.hpp | 2 +- src/rpc/client_pool.hpp | 7 +- src/rpc/exceptions.hpp | 2 +- src/rpc/protocol.cpp | 6 +- src/rpc/protocol.hpp | 2 +- src/slk/serialization.hpp | 20 +- src/slk/streams.cpp | 5 +- src/storage/v2/disk/label_property_index.cpp | 3 +- src/storage/v2/disk/rocksdb_storage.hpp | 2 +- src/storage/v2/disk/unique_constraints.cpp | 2 +- src/storage/v2/durability/serialization.hpp | 6 +- src/storage/v2/durability/snapshot.cpp | 4 +- src/storage/v2/durability/wal.hpp | 2 +- src/storage/v2/edge_accessor.hpp | 2 +- src/storage/v2/id_types.hpp | 2 +- src/storage/v2/modified_edge.hpp | 3 +- src/storage/v2/property_store.cpp | 8 +- .../v2/replication/replication_client.hpp | 2 +- src/storage/v2/replication/rpc.cpp | 7 +- src/storage/v2/replication/rpc.hpp | 38 +-- src/storage/v2/storage.hpp | 2 +- src/storage/v2/vertex_accessor.hpp | 2 +- src/telemetry/telemetry.cpp | 5 +- src/utils/cast.hpp | 10 +- src/utils/event_histogram.hpp | 7 +- src/utils/exceptions.hpp | 4 +- src/utils/logging.hpp | 22 +- src/utils/lru_cache.hpp | 2 +- src/utils/memory.hpp | 4 +- src/utils/scheduler.hpp | 2 +- src/utils/skip_list.hpp | 4 +- src/utils/small_vector.hpp | 42 +-- src/utils/stacktrace.hpp | 11 +- src/utils/variant_helpers.hpp | 2 +- tests/benchmark/query/profile.cpp | 14 +- tests/benchmark/rpc.cpp | 5 +- .../e2e/isolation_levels/isolation_levels.cpp | 2 +- .../memory/memory_limit_global_alloc_proc.cpp | 2 +- ..._limit_global_multi_thread_proc_create.cpp | 2 +- .../memory_limit_global_thread_alloc_proc.cpp | 2 +- tests/e2e/memory/procedure_memory_limit.cpp | 2 +- tests/e2e/memory/query_memory_limit_proc.cpp | 2 +- .../query_memory_limit_proc_multi_thread.cpp | 2 +- tests/e2e/replication/common.hpp | 4 +- tests/e2e/replication/constraints.cpp | 4 +- .../e2e/replication/read_write_benchmark.cpp | 4 +- tests/e2e/triggers/common.hpp | 4 +- tests/manual/antlr_tree_pretty_print.cpp | 4 +- tests/stress/long_running.cpp | 4 +- tests/unit/CMakeLists.txt | 17 +- tests/unit/auth.cpp | 20 +- tests/unit/auth_handler.cpp | 4 +- tests/unit/bfs_common.hpp | 2 +- tests/unit/bolt_chunked_encoder_buffer.cpp | 6 +- tests/unit/cpp_api.cpp | 2 +- tests/unit/cypher_main_visitor.cpp | 6 +- tests/unit/integrations_kafka_consumer.cpp | 6 +- tests/unit/interpreter.cpp | 4 +- tests/unit/kvstore.cpp | 6 +- tests/unit/mgp_kafka_c_api.cpp | 4 +- tests/unit/plan_pretty_print.cpp | 2 +- tests/unit/query_common.hpp | 22 +- tests/unit/query_cost_estimator.cpp | 12 +- tests/unit/query_dump.cpp | 8 +- tests/unit/query_expression_evaluator.cpp | 8 +- tests/unit/query_plan_checker.hpp | 17 +- tests/unit/query_plan_common.hpp | 14 +- tests/unit/query_plan_edge_cases.cpp | 4 +- tests/unit/query_plan_operator_to_string.cpp | 2 +- tests/unit/query_required_privileges.cpp | 2 +- tests/unit/query_semantic.cpp | 54 ++-- tests/unit/rpc_messages.hpp | 12 +- tests/unit/slk_core.cpp | 6 +- tests/unit/slk_streams.cpp | 4 +- tests/unit/storage_rocks.cpp | 2 +- tests/unit/storage_v2_property_store.cpp | 2 +- tests/unit/storage_v2_wal_file.cpp | 6 +- tests/unit/utils_file.cpp | 4 +- tests/unit/utils_string.cpp | 4 +- 149 files changed, 778 insertions(+), 763 deletions(-) diff --git a/include/mgp.hpp b/include/mgp.hpp index 25e365e53..6296d2e5c 100644 --- a/include/mgp.hpp +++ b/include/mgp.hpp @@ -34,7 +34,7 @@ namespace mgp { class IndexException : public std::exception { public: - explicit IndexException(const std::string &message) : message_(message) {} + explicit IndexException(std::string message) : message_(std::move(message)) {} const char *what() const noexcept override { return message_.c_str(); } private: @@ -43,7 +43,7 @@ class IndexException : public std::exception { class ValueException : public std::exception { public: - explicit ValueException(const std::string &message) : message_(message) {} + explicit ValueException(std::string message) : message_(std::move(message)) {} const char *what() const noexcept override { return message_.c_str(); } private: @@ -52,7 +52,7 @@ class ValueException : public std::exception { class NotFoundException : public std::exception { public: - explicit NotFoundException(const std::string &message) : message_(message) {} + explicit NotFoundException(std::string message) : message_(std::move(message)) {} const char *what() const noexcept override { return message_.c_str(); } private: @@ -61,7 +61,7 @@ class NotFoundException : public std::exception { class MustAbortException : public std::exception { public: - explicit MustAbortException(const std::string &message) : message_(message) {} + explicit MustAbortException(std::string message) : message_(std::move(message)) {} const char *what() const noexcept override { return message_.c_str(); } private: @@ -233,14 +233,14 @@ class Graph { GraphRelationships Relationships() const; /// @brief Returns the graph node with the given ID. - Node GetNodeById(const Id node_id) const; + Node GetNodeById(Id node_id) const; /// @brief Returns whether the graph contains a node with the given ID. - bool ContainsNode(const Id node_id) const; + bool ContainsNode(Id node_id) const; /// @brief Returns whether the graph contains the given node. bool ContainsNode(const Node &node) const; /// @brief Returns whether the graph contains a relationship with the given ID. - bool ContainsRelationship(const Id relationship_id) const; + bool ContainsRelationship(Id relationship_id) const; /// @brief Returns whether the graph contains the given relationship. bool ContainsRelationship(const Relationship &relationship) const; @@ -253,7 +253,7 @@ class Graph { /// @brief Deletes a node and all its incident edges from the graph. void DetachDeleteNode(const Node &node); /// @brief Creates a relationship of type `type` between nodes `from` and `to` and adds it to the graph. - Relationship CreateRelationship(const Node &from, const Node &to, const std::string_view type); + Relationship CreateRelationship(const Node &from, const Node &to, std::string_view type); /// @brief Changes a relationship from node. void SetFrom(Relationship &relationship, const Node &new_from); /// @brief Changes a relationship to node. @@ -305,7 +305,7 @@ class Nodes { bool operator==(Iterator other) const; bool operator!=(Iterator other) const; - const Node operator*() const; + Node operator*() const; private: mgp_vertices_iterator *nodes_iterator_ = nullptr; @@ -352,7 +352,7 @@ class GraphRelationships { bool operator==(Iterator other) const; bool operator!=(Iterator other) const; - const Relationship operator*() const; + Relationship operator*() const; private: mgp_vertices_iterator *nodes_iterator_ = nullptr; @@ -398,7 +398,7 @@ class Relationships { bool operator==(Iterator other) const; bool operator!=(Iterator other) const; - const Relationship operator*() const; + Relationship operator*() const; private: mgp_edges_iterator *relationships_iterator_ = nullptr; @@ -451,7 +451,7 @@ class Labels { Iterator &operator++(); - const std::string_view operator*() const; + std::string_view operator*() const; private: Iterator(const Labels *iterable, size_t index); @@ -502,7 +502,7 @@ class List { explicit List(std::vector &&values); /// @brief Creates a List from the given initializer_list. - explicit List(const std::initializer_list list); + explicit List(std::initializer_list list); List(const List &other) noexcept; List(List &&other) noexcept; @@ -518,7 +518,7 @@ class List { bool Empty() const; /// @brief Returns the value at the given `index`. - const Value operator[](size_t index) const; + Value operator[](size_t index) const; ///@brief Same as above, but non const value Value operator[](size_t index); @@ -540,7 +540,7 @@ class List { Iterator &operator++(); - const Value operator*() const; + Value operator*() const; private: Iterator(const List *iterable, size_t index); @@ -577,7 +577,7 @@ class List { bool operator!=(const List &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_list *ptr_; @@ -608,7 +608,7 @@ class Map { explicit Map(std::map &&items); /// @brief Creates a Map from the given initializer_list (map items correspond to initializer list pairs). - Map(const std::initializer_list> items); + Map(std::initializer_list> items); Map(const Map &other) noexcept; Map(Map &&other) noexcept; @@ -625,10 +625,10 @@ class Map { bool Empty() const; /// @brief Returns the value at the given `key`. - Value const operator[](std::string_view key) const; + Value operator[](std::string_view key) const; /// @brief Returns the value at the given `key`. - Value const At(std::string_view key) const; + Value At(std::string_view key) const; /// @brief Returns true if the given `key` exists. bool KeyExists(std::string_view key) const; @@ -656,7 +656,7 @@ class Map { bool operator==(Iterator other) const; bool operator!=(Iterator other) const; - const MapItem operator*() const; + MapItem operator*() const; private: mgp_map_items_iterator *map_items_iterator_ = nullptr; @@ -698,7 +698,7 @@ class Map { bool operator!=(const Map &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_map *ptr_; @@ -761,10 +761,10 @@ class Node { Relationships OutRelationships() const; /// @brief Adds a label to the node. - void AddLabel(const std::string_view label); + void AddLabel(std::string_view label); /// @brief Removes a label from the node. - void RemoveLabel(const std::string_view label); + void RemoveLabel(std::string_view label); bool operator<(const Node &other) const; @@ -775,7 +775,7 @@ class Node { bool operator!=(const Node &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; /// @brief returns the in degree of a node inline size_t InDegree() const; @@ -845,7 +845,7 @@ class Relationship { bool operator!=(const Relationship &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_edge *ptr_; @@ -898,7 +898,7 @@ class Path { bool operator!=(const Path &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_path *ptr_; @@ -958,7 +958,7 @@ class Date { bool operator<(const Date &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_date *ptr_; @@ -1020,7 +1020,7 @@ class LocalTime { bool operator<(const LocalTime &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_local_time *ptr_; @@ -1088,7 +1088,7 @@ class LocalDateTime { bool operator<(const LocalDateTime &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_local_date_time *ptr_; @@ -1142,7 +1142,7 @@ class Duration { bool operator<(const Duration &other) const; /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_duration *ptr_; @@ -1190,13 +1190,13 @@ class Value { explicit Value(); // Primitive type constructors: - explicit Value(const bool value); - explicit Value(const int64_t value); - explicit Value(const double value); + explicit Value(bool value); + explicit Value(int64_t value); + explicit Value(double value); // String constructors: explicit Value(const char *value); - explicit Value(const std::string_view value); + explicit Value(std::string_view value); // Container constructors: /// @brief Constructs a List value from the copy of the given `list`. @@ -1290,28 +1290,28 @@ class Value { List ValueList() const; List ValueList(); /// @pre Value type needs to be Type::Map. - const Map ValueMap() const; + Map ValueMap() const; Map ValueMap(); /// @pre Value type needs to be Type::Node. - const Node ValueNode() const; + Node ValueNode() const; Node ValueNode(); /// @pre Value type needs to be Type::Relationship. - const Relationship ValueRelationship() const; + Relationship ValueRelationship() const; Relationship ValueRelationship(); /// @pre Value type needs to be Type::Path. - const Path ValuePath() const; + Path ValuePath() const; Path ValuePath(); /// @pre Value type needs to be Type::Date. - const Date ValueDate() const; + Date ValueDate() const; Date ValueDate(); /// @pre Value type needs to be Type::LocalTime. - const LocalTime ValueLocalTime() const; + LocalTime ValueLocalTime() const; LocalTime ValueLocalTime(); /// @pre Value type needs to be Type::LocalDateTime. - const LocalDateTime ValueLocalDateTime() const; + LocalDateTime ValueLocalDateTime() const; LocalDateTime ValueLocalDateTime(); /// @pre Value type needs to be Type::Duration. - const Duration ValueDuration() const; + Duration ValueDuration() const; Duration ValueDuration(); /// @brief Returns whether the value is null. @@ -1355,7 +1355,7 @@ class Value { friend std::ostream &operator<<(std::ostream &os, const mgp::Value &value); /// @brief returns the string representation - const std::string ToString() const; + std::string ToString() const; private: mgp_value *ptr_; @@ -1421,9 +1421,9 @@ class RecordFactory { public: explicit RecordFactory(mgp_result *result); - const Record NewRecord() const; + Record NewRecord() const; - void SetErrorMessage(const std::string_view error_msg) const; + void SetErrorMessage(std::string_view error_msg) const; void SetErrorMessage(const char *error_msg) const; @@ -1465,7 +1465,7 @@ class Result { /// @brief Sets a @ref Duration value to be returned. inline void SetValue(const Duration &duration); - void SetErrorMessage(const std::string_view error_msg) const; + void SetErrorMessage(std::string_view error_msg) const; void SetErrorMessage(const char *error_msg) const; @@ -1644,8 +1644,8 @@ template TDest MemcpyCast(TSrc src) { TDest dest; static_assert(sizeof(dest) == sizeof(src), "MemcpyCast expects source and destination to be of the same size"); - static_assert(std::is_arithmetic::value, "MemcpyCast expects source to be an arithmetic type"); - static_assert(std::is_arithmetic::value, "MemcpyCast expects destination to be an arithmetic type"); + static_assert(std::is_arithmetic_v, "MemcpyCast expects source to be an arithmetic type"); + static_assert(std::is_arithmetic_v, "MemcpyCast expects destination to be an arithmetic type"); std::memcpy(&dest, &src, sizeof(src)); return dest; } @@ -1678,8 +1678,8 @@ inline bool MapsEqual(mgp_map *map1, mgp_map *map2) { if (mgp::map_size(map1) != mgp::map_size(map2)) { return false; } - auto items_it = mgp::MemHandlerCallback(map_iter_items, map1); - for (auto item = mgp::map_items_iterator_get(items_it); item; item = mgp::map_items_iterator_next(items_it)) { + auto *items_it = mgp::MemHandlerCallback(map_iter_items, map1); + for (auto *item = mgp::map_items_iterator_get(items_it); item; item = mgp::map_items_iterator_next(items_it)) { if (mgp::map_item_key(item) == mgp::map_item_key(item)) { return false; } @@ -1943,7 +1943,7 @@ inline int64_t Graph::Size() const { } inline GraphNodes Graph::Nodes() const { - auto nodes_it = mgp::MemHandlerCallback(graph_iter_vertices, graph_); + auto *nodes_it = mgp::MemHandlerCallback(graph_iter_vertices, graph_); if (nodes_it == nullptr) { throw mg_exception::NotEnoughMemoryException(); } @@ -1953,7 +1953,7 @@ inline GraphNodes Graph::Nodes() const { inline GraphRelationships Graph::Relationships() const { return GraphRelationships(graph_); } inline Node Graph::GetNodeById(const Id node_id) const { - auto mgp_node = mgp::MemHandlerCallback(graph_get_vertex_by_id, graph_, mgp_vertex_id{.as_int = node_id.AsInt()}); + auto *mgp_node = mgp::MemHandlerCallback(graph_get_vertex_by_id, graph_, mgp_vertex_id{.as_int = node_id.AsInt()}); if (mgp_node == nullptr) { mgp::vertex_destroy(mgp_node); throw NotFoundException("Node with ID " + std::to_string(node_id.AsUint()) + " not found!"); @@ -1964,7 +1964,7 @@ inline Node Graph::GetNodeById(const Id node_id) const { } inline bool Graph::ContainsNode(const Id node_id) const { - auto mgp_node = mgp::MemHandlerCallback(graph_get_vertex_by_id, graph_, mgp_vertex_id{.as_int = node_id.AsInt()}); + auto *mgp_node = mgp::MemHandlerCallback(graph_get_vertex_by_id, graph_, mgp_vertex_id{.as_int = node_id.AsInt()}); if (mgp_node == nullptr) { return false; } @@ -2066,7 +2066,7 @@ inline Nodes::Iterator::~Iterator() { inline Nodes::Iterator &Nodes::Iterator::operator++() { if (nodes_iterator_ != nullptr) { - auto next = mgp::vertices_iterator_next(nodes_iterator_); + auto *next = mgp::vertices_iterator_next(nodes_iterator_); if (next == nullptr) { mgp::vertices_iterator_destroy(nodes_iterator_); @@ -2098,7 +2098,7 @@ inline bool Nodes::Iterator::operator==(Iterator other) const { inline bool Nodes::Iterator::operator!=(Iterator other) const { return !(*this == other); } -inline const Node Nodes::Iterator::operator*() const { +inline Node Nodes::Iterator::operator*() const { if (nodes_iterator_ == nullptr) { return Node((const mgp_vertex *)nullptr); } @@ -2126,7 +2126,7 @@ inline GraphRelationships::Iterator::Iterator(mgp_vertices_iterator *nodes_itera } // Go through each graph node’s adjacent nodes - for (auto node = mgp::vertices_iterator_get(nodes_iterator_); node; + for (auto *node = mgp::vertices_iterator_get(nodes_iterator_); node; node = mgp::vertices_iterator_next(nodes_iterator_)) { // Check if node exists if (node == nullptr) { @@ -2137,7 +2137,7 @@ inline GraphRelationships::Iterator::Iterator(mgp_vertices_iterator *nodes_itera // Check if node has out-relationships out_relationships_iterator_ = mgp::MemHandlerCallback(vertex_iter_out_edges, node); - auto relationship = mgp::edges_iterator_get(out_relationships_iterator_); + auto *relationship = mgp::edges_iterator_get(out_relationships_iterator_); if (relationship != nullptr) { return; } @@ -2164,7 +2164,7 @@ inline GraphRelationships::Iterator &GraphRelationships::Iterator::operator++() // 1. Check if the current node has remaining relationships to iterate over if (out_relationships_iterator_ != nullptr) { - auto next = mgp::edges_iterator_next(out_relationships_iterator_); + auto *next = mgp::edges_iterator_next(out_relationships_iterator_); if (next != nullptr) { return *this; @@ -2177,7 +2177,7 @@ inline GraphRelationships::Iterator &GraphRelationships::Iterator::operator++() // 2. Move onto the next nodes if (nodes_iterator_ != nullptr) { - for (auto node = mgp::vertices_iterator_next(nodes_iterator_); node; + for (auto *node = mgp::vertices_iterator_next(nodes_iterator_); node; node = mgp::vertices_iterator_next(nodes_iterator_)) { // Check if node exists - if it doesn’t, we’ve reached the end of the iterator if (node == nullptr) { @@ -2188,7 +2188,7 @@ inline GraphRelationships::Iterator &GraphRelationships::Iterator::operator++() // Check if node has out-relationships out_relationships_iterator_ = mgp::MemHandlerCallback(vertex_iter_out_edges, node); - auto relationship = mgp::edges_iterator_get(out_relationships_iterator_); + auto *relationship = mgp::edges_iterator_get(out_relationships_iterator_); if (relationship != nullptr) { return *this; } @@ -2222,7 +2222,7 @@ inline bool GraphRelationships::Iterator::operator==(Iterator other) const { inline bool GraphRelationships::Iterator::operator!=(Iterator other) const { return !(*this == other); } -inline const Relationship GraphRelationships::Iterator::operator*() const { +inline Relationship GraphRelationships::Iterator::operator*() const { if (out_relationships_iterator_ != nullptr) { return Relationship(mgp::edges_iterator_get(out_relationships_iterator_)); } @@ -2268,7 +2268,7 @@ inline Relationships::Iterator::~Iterator() { inline Relationships::Iterator &Relationships::Iterator::operator++() { if (relationships_iterator_ != nullptr) { - auto next = mgp::edges_iterator_next(relationships_iterator_); + auto *next = mgp::edges_iterator_next(relationships_iterator_); if (next == nullptr) { mgp::edges_iterator_destroy(relationships_iterator_); @@ -2300,7 +2300,7 @@ inline bool Relationships::Iterator::operator==(Iterator other) const { inline bool Relationships::Iterator::operator!=(Iterator other) const { return !(*this == other); } -inline const Relationship Relationships::Iterator::operator*() const { +inline Relationship Relationships::Iterator::operator*() const { if (relationships_iterator_ == nullptr) { return Relationship((mgp_edge *)nullptr); } @@ -2361,7 +2361,7 @@ inline Labels::Iterator &Labels::Iterator::operator++() { return *this; } -inline const std::string_view Labels::Iterator::operator*() const { return (*iterable_)[index_]; } +inline std::string_view Labels::Iterator::operator*() const { return (*iterable_)[index_]; } inline Labels::Iterator::Iterator(const Labels *iterable, size_t index) : iterable_(iterable), index_(index) {} @@ -2446,7 +2446,7 @@ inline size_t List::Size() const { return mgp::list_size(ptr_); } inline bool List::Empty() const { return Size() == 0; } -inline const Value List::operator[](size_t index) const { return Value(mgp::list_at(ptr_, index)); } +inline Value List::operator[](size_t index) const { return Value(mgp::list_at(ptr_, index)); } inline Value List::operator[](size_t index) { return Value(mgp::list_at(ptr_, index)); } @@ -2461,7 +2461,7 @@ inline List::Iterator &List::Iterator::operator++() { return *this; } -inline const Value List::Iterator::operator*() const { return (*iterable_)[index_]; } +inline Value List::Iterator::operator*() const { return (*iterable_)[index_]; } inline List::Iterator::Iterator(const List *iterable, size_t index) : iterable_(iterable), index_(index) {} @@ -2488,7 +2488,7 @@ inline bool List::operator==(const List &other) const { return util::ListsEqual( inline bool List::operator!=(const List &other) const { return !(*this == other); } -inline const std::string List::ToString() const { +inline std::string List::ToString() const { const size_t size = Size(); if (size == 0) { return "[]"; @@ -2572,9 +2572,9 @@ inline size_t Map::Size() const { return mgp::map_size(ptr_); } inline bool Map::Empty() const { return Size() == 0; } -inline const Value Map::operator[](std::string_view key) const { return Value(mgp::map_at(ptr_, key.data())); } +inline Value Map::operator[](std::string_view key) const { return Value(mgp::map_at(ptr_, key.data())); } -inline const Value Map::At(std::string_view key) const { +inline Value Map::At(std::string_view key) const { auto *ptr = mgp::map_at(ptr_, key.data()); if (ptr) { return Value(ptr); @@ -2603,7 +2603,7 @@ inline Map::Iterator::~Iterator() { inline Map::Iterator &Map::Iterator::operator++() { if (map_items_iterator_ != nullptr) { - auto next = mgp::map_items_iterator_next(map_items_iterator_); + auto *next = mgp::map_items_iterator_next(map_items_iterator_); if (next == nullptr) { mgp::map_items_iterator_destroy(map_items_iterator_); @@ -2632,14 +2632,14 @@ inline bool Map::Iterator::operator==(Iterator other) const { inline bool Map::Iterator::operator!=(Iterator other) const { return !(*this == other); } -inline const MapItem Map::Iterator::operator*() const { +inline MapItem Map::Iterator::operator*() const { if (map_items_iterator_ == nullptr) { throw ValueException("Empty map item!"); } - auto raw_map_item = mgp::map_items_iterator_get(map_items_iterator_); + auto *raw_map_item = mgp::map_items_iterator_get(map_items_iterator_); - auto map_key = mgp::map_item_key(raw_map_item); + const auto *map_key = mgp::map_item_key(raw_map_item); auto map_value = Value(mgp::map_item_value(raw_map_item)); return MapItem{.key = map_key, .value = map_value}; @@ -2675,7 +2675,7 @@ inline bool Map::operator==(const Map &other) const { return util::MapsEqual(ptr inline bool Map::operator!=(const Map &other) const { return !(*this == other); } -inline const std::string Map::ToString() const { +inline std::string Map::ToString() const { const size_t map_size = Size(); if (map_size == 0) { return "{}"; @@ -2747,7 +2747,7 @@ inline bool Node::HasLabel(std::string_view label) const { } inline Relationships Node::InRelationships() const { - auto relationship_iterator = mgp::MemHandlerCallback(vertex_iter_in_edges, ptr_); + auto *relationship_iterator = mgp::MemHandlerCallback(vertex_iter_in_edges, ptr_); if (relationship_iterator == nullptr) { throw mg_exception::NotEnoughMemoryException(); } @@ -2755,7 +2755,7 @@ inline Relationships Node::InRelationships() const { } inline Relationships Node::OutRelationships() const { - auto relationship_iterator = mgp::MemHandlerCallback(vertex_iter_out_edges, ptr_); + auto *relationship_iterator = mgp::MemHandlerCallback(vertex_iter_out_edges, ptr_); if (relationship_iterator == nullptr) { throw mg_exception::NotEnoughMemoryException(); } @@ -2825,7 +2825,7 @@ inline std::string PropertiesToString(const std::map &proper return properties; } -inline const std::string Node::ToString() const { +inline std::string Node::ToString() const { std::string labels{", "}; for (auto label : Labels()) { labels.append(":" + std::string(label)); @@ -2933,7 +2933,7 @@ inline bool Relationship::operator==(const Relationship &other) const { inline bool Relationship::operator!=(const Relationship &other) const { return !(*this == other); } -inline const std::string Relationship::ToString() const { +inline std::string Relationship::ToString() const { const auto from = From(); const auto to = To(); @@ -2992,7 +2992,7 @@ inline Path::~Path() { inline size_t Path::Length() const { return mgp::path_size(ptr_); } inline Node Path::GetNodeAt(size_t index) const { - auto node_ptr = mgp::path_vertex_at(ptr_, index); + auto *node_ptr = mgp::path_vertex_at(ptr_, index); if (node_ptr == nullptr) { throw IndexException("Index value out of bounds."); } @@ -3000,7 +3000,7 @@ inline Node Path::GetNodeAt(size_t index) const { } inline Relationship Path::GetRelationshipAt(size_t index) const { - auto relationship_ptr = mgp::path_edge_at(ptr_, index); + auto *relationship_ptr = mgp::path_edge_at(ptr_, index); if (relationship_ptr == nullptr) { throw IndexException("Index value out of bounds."); } @@ -3015,10 +3015,10 @@ inline bool Path::operator==(const Path &other) const { return util::PathsEqual( inline bool Path::operator!=(const Path &other) const { return !(*this == other); } -inline const std::string Path::ToString() const { +inline std::string Path::ToString() const { const auto length = Length(); size_t i = 0; - std::string return_string{""}; + std::string return_string; for (i = 0; i < length; i++) { const auto node = GetNodeAt(i); return_string.append(node.ToString() + "-"); @@ -3089,7 +3089,7 @@ inline Date::~Date() { } inline Date Date::Now() { - auto mgp_date = mgp::MemHandlerCallback(date_now); + auto *mgp_date = mgp::MemHandlerCallback(date_now); auto date = Date(mgp_date); mgp::date_destroy(mgp_date); @@ -3107,7 +3107,7 @@ inline int64_t Date::Timestamp() const { return mgp::date_timestamp(ptr_); } inline bool Date::operator==(const Date &other) const { return util::DatesEqual(ptr_, other.ptr_); } inline Date Date::operator+(const Duration &dur) const { - auto mgp_sum = mgp::MemHandlerCallback(date_add_duration, ptr_, dur.ptr_); + auto *mgp_sum = mgp::MemHandlerCallback(date_add_duration, ptr_, dur.ptr_); auto sum = Date(mgp_sum); mgp::date_destroy(mgp_sum); @@ -3115,7 +3115,7 @@ inline Date Date::operator+(const Duration &dur) const { } inline Date Date::operator-(const Duration &dur) const { - auto mgp_difference = mgp::MemHandlerCallback(date_add_duration, ptr_, dur.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(date_add_duration, ptr_, dur.ptr_); auto difference = Date(mgp_difference); mgp::date_destroy(mgp_difference); @@ -3123,7 +3123,7 @@ inline Date Date::operator-(const Duration &dur) const { } inline Duration Date::operator-(const Date &other) const { - auto mgp_difference = mgp::MemHandlerCallback(date_diff, ptr_, other.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(date_diff, ptr_, other.ptr_); auto difference = Duration(mgp_difference); mgp::duration_destroy(mgp_difference); @@ -3131,14 +3131,14 @@ inline Duration Date::operator-(const Date &other) const { } inline bool Date::operator<(const Date &other) const { - auto difference = mgp::MemHandlerCallback(date_diff, ptr_, other.ptr_); + auto *difference = mgp::MemHandlerCallback(date_diff, ptr_, other.ptr_); auto is_less = (mgp::duration_get_microseconds(difference) < 0); mgp::duration_destroy(difference); return is_less; } -inline const std::string Date::ToString() const { +inline std::string Date::ToString() const { return std::to_string(Year()) + "-" + std::to_string(Month()) + "-" + std::to_string(Day()); } @@ -3188,7 +3188,7 @@ inline LocalTime::~LocalTime() { } inline LocalTime LocalTime::Now() { - auto mgp_local_time = mgp::MemHandlerCallback(local_time_now); + auto *mgp_local_time = mgp::MemHandlerCallback(local_time_now); auto local_time = LocalTime(mgp_local_time); mgp::local_time_destroy(mgp_local_time); @@ -3210,7 +3210,7 @@ inline int64_t LocalTime::Timestamp() const { return mgp::local_time_timestamp(p inline bool LocalTime::operator==(const LocalTime &other) const { return util::LocalTimesEqual(ptr_, other.ptr_); } inline LocalTime LocalTime::operator+(const Duration &dur) const { - auto mgp_sum = mgp::MemHandlerCallback(local_time_add_duration, ptr_, dur.ptr_); + auto *mgp_sum = mgp::MemHandlerCallback(local_time_add_duration, ptr_, dur.ptr_); auto sum = LocalTime(mgp_sum); mgp::local_time_destroy(mgp_sum); @@ -3218,7 +3218,7 @@ inline LocalTime LocalTime::operator+(const Duration &dur) const { } inline LocalTime LocalTime::operator-(const Duration &dur) const { - auto mgp_difference = mgp::MemHandlerCallback(local_time_sub_duration, ptr_, dur.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(local_time_sub_duration, ptr_, dur.ptr_); auto difference = LocalTime(mgp_difference); mgp::local_time_destroy(mgp_difference); @@ -3226,7 +3226,7 @@ inline LocalTime LocalTime::operator-(const Duration &dur) const { } inline Duration LocalTime::operator-(const LocalTime &other) const { - auto mgp_difference = mgp::MemHandlerCallback(local_time_diff, ptr_, other.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(local_time_diff, ptr_, other.ptr_); auto difference = Duration(mgp_difference); mgp::duration_destroy(mgp_difference); @@ -3234,14 +3234,14 @@ inline Duration LocalTime::operator-(const LocalTime &other) const { } inline bool LocalTime::operator<(const LocalTime &other) const { - auto difference = mgp::MemHandlerCallback(local_time_diff, ptr_, other.ptr_); + auto *difference = mgp::MemHandlerCallback(local_time_diff, ptr_, other.ptr_); auto is_less = (mgp::duration_get_microseconds(difference) < 0); mgp::duration_destroy(difference); return is_less; } -inline const std::string LocalTime::ToString() const { +inline std::string LocalTime::ToString() const { return std::to_string(Hour()) + ":" + std::to_string(Minute()) + ":" + std::to_string(Second()) + "," + std::to_string(Millisecond()) + std::to_string(Microsecond()); } @@ -3299,7 +3299,7 @@ inline LocalDateTime::~LocalDateTime() { } inline LocalDateTime LocalDateTime::Now() { - auto mgp_local_date_time = mgp::MemHandlerCallback(local_date_time_now); + auto *mgp_local_date_time = mgp::MemHandlerCallback(local_date_time_now); auto local_date_time = LocalDateTime(mgp_local_date_time); mgp::local_date_time_destroy(mgp_local_date_time); @@ -3329,7 +3329,7 @@ inline bool LocalDateTime::operator==(const LocalDateTime &other) const { } inline LocalDateTime LocalDateTime::operator+(const Duration &dur) const { - auto mgp_sum = mgp::MemHandlerCallback(local_date_time_add_duration, ptr_, dur.ptr_); + auto *mgp_sum = mgp::MemHandlerCallback(local_date_time_add_duration, ptr_, dur.ptr_); auto sum = LocalDateTime(mgp_sum); mgp::local_date_time_destroy(mgp_sum); @@ -3337,7 +3337,7 @@ inline LocalDateTime LocalDateTime::operator+(const Duration &dur) const { } inline LocalDateTime LocalDateTime::operator-(const Duration &dur) const { - auto mgp_difference = mgp::MemHandlerCallback(local_date_time_sub_duration, ptr_, dur.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(local_date_time_sub_duration, ptr_, dur.ptr_); auto difference = LocalDateTime(mgp_difference); mgp::local_date_time_destroy(mgp_difference); @@ -3345,7 +3345,7 @@ inline LocalDateTime LocalDateTime::operator-(const Duration &dur) const { } inline Duration LocalDateTime::operator-(const LocalDateTime &other) const { - auto mgp_difference = mgp::MemHandlerCallback(local_date_time_diff, ptr_, other.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(local_date_time_diff, ptr_, other.ptr_); auto difference = Duration(mgp_difference); mgp::duration_destroy(mgp_difference); @@ -3353,14 +3353,14 @@ inline Duration LocalDateTime::operator-(const LocalDateTime &other) const { } inline bool LocalDateTime::operator<(const LocalDateTime &other) const { - auto difference = mgp::MemHandlerCallback(local_date_time_diff, ptr_, other.ptr_); + auto *difference = mgp::MemHandlerCallback(local_date_time_diff, ptr_, other.ptr_); auto is_less = (mgp::duration_get_microseconds(difference) < 0); mgp::duration_destroy(difference); return is_less; } -inline const std::string LocalDateTime::ToString() const { +inline std::string LocalDateTime::ToString() const { return std::to_string(Year()) + "-" + std::to_string(Month()) + "-" + std::to_string(Day()) + "T" + std::to_string(Hour()) + ":" + std::to_string(Minute()) + ":" + std::to_string(Second()) + "," + std::to_string(Millisecond()) + std::to_string(Microsecond()); @@ -3424,7 +3424,7 @@ inline int64_t Duration::Microseconds() const { return mgp::duration_get_microse inline bool Duration::operator==(const Duration &other) const { return util::DurationsEqual(ptr_, other.ptr_); } inline Duration Duration::operator+(const Duration &other) const { - auto mgp_sum = mgp::MemHandlerCallback(duration_add, ptr_, other.ptr_); + auto *mgp_sum = mgp::MemHandlerCallback(duration_add, ptr_, other.ptr_); auto sum = Duration(mgp_sum); mgp::duration_destroy(mgp_sum); @@ -3432,7 +3432,7 @@ inline Duration Duration::operator+(const Duration &other) const { } inline Duration Duration::operator-(const Duration &other) const { - auto mgp_difference = mgp::MemHandlerCallback(duration_sub, ptr_, other.ptr_); + auto *mgp_difference = mgp::MemHandlerCallback(duration_sub, ptr_, other.ptr_); auto difference = Duration(mgp_difference); mgp::duration_destroy(mgp_difference); @@ -3440,7 +3440,7 @@ inline Duration Duration::operator-(const Duration &other) const { } inline Duration Duration::operator-() const { - auto mgp_neg = mgp::MemHandlerCallback(duration_neg, ptr_); + auto *mgp_neg = mgp::MemHandlerCallback(duration_neg, ptr_); auto neg = Duration(mgp_neg); mgp::duration_destroy(mgp_neg); @@ -3448,14 +3448,14 @@ inline Duration Duration::operator-() const { } inline bool Duration::operator<(const Duration &other) const { - auto difference = mgp::MemHandlerCallback(duration_sub, ptr_, other.ptr_); + auto *difference = mgp::MemHandlerCallback(duration_sub, ptr_, other.ptr_); auto is_less = (mgp::duration_get_microseconds(difference) < 0); mgp::duration_destroy(difference); return is_less; } -inline const std::string Duration::ToString() const { return std::to_string(Microseconds()) + "ms"; } +inline std::string Duration::ToString() const { return std::to_string(Microseconds()) + "ms"; } /* #endregion */ @@ -3662,7 +3662,7 @@ inline List Value::ValueList() { return List(mgp::value_get_list(ptr_)); } -inline const Map Value::ValueMap() const { +inline Map Value::ValueMap() const { if (Type() != Type::Map) { throw ValueException("Type of value is wrong: expected Map."); } @@ -3675,7 +3675,7 @@ inline Map Value::ValueMap() { return Map(mgp::value_get_map(ptr_)); } -inline const Node Value::ValueNode() const { +inline Node Value::ValueNode() const { if (Type() != Type::Node) { throw ValueException("Type of value is wrong: expected Node."); } @@ -3688,7 +3688,7 @@ inline Node Value::ValueNode() { return Node(mgp::value_get_vertex(ptr_)); } -inline const Relationship Value::ValueRelationship() const { +inline Relationship Value::ValueRelationship() const { if (Type() != Type::Relationship) { throw ValueException("Type of value is wrong: expected Relationship."); } @@ -3701,7 +3701,7 @@ inline Relationship Value::ValueRelationship() { return Relationship(mgp::value_get_edge(ptr_)); } -inline const Path Value::ValuePath() const { +inline Path Value::ValuePath() const { if (Type() != Type::Path) { throw ValueException("Type of value is wrong: expected Path."); } @@ -3714,7 +3714,7 @@ inline Path Value::ValuePath() { return Path(mgp::value_get_path(ptr_)); } -inline const Date Value::ValueDate() const { +inline Date Value::ValueDate() const { if (Type() != Type::Date) { throw ValueException("Type of value is wrong: expected Date."); } @@ -3727,7 +3727,7 @@ inline Date Value::ValueDate() { return Date(mgp::value_get_date(ptr_)); } -inline const LocalTime Value::ValueLocalTime() const { +inline LocalTime Value::ValueLocalTime() const { if (Type() != Type::LocalTime) { throw ValueException("Type of value is wrong: expected LocalTime."); } @@ -3740,7 +3740,7 @@ inline LocalTime Value::ValueLocalTime() { return LocalTime(mgp::value_get_local_time(ptr_)); } -inline const LocalDateTime Value::ValueLocalDateTime() const { +inline LocalDateTime Value::ValueLocalDateTime() const { if (Type() != Type::LocalDateTime) { throw ValueException("Type of value is wrong: expected LocalDateTime."); } @@ -3753,7 +3753,7 @@ inline LocalDateTime Value::ValueLocalDateTime() { return LocalDateTime(mgp::value_get_local_date_time(ptr_)); } -inline const Duration Value::ValueDuration() const { +inline Duration Value::ValueDuration() const { if (Type() != Type::Duration) { throw ValueException("Type of value is wrong: expected Duration."); } @@ -3921,7 +3921,7 @@ inline std::ostream &operator<<(std::ostream &os, const mgp::Type &type) { } } -inline const std::string Value::ToString() const { +inline std::string Value::ToString() const { const mgp::Type &type = Type(); switch (type) { case Type::Null: @@ -3965,85 +3965,85 @@ inline const std::string Value::ToString() const { inline Record::Record(mgp_result_record *record) : record_(record) {} inline void Record::Insert(const char *field_name, bool value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_bool, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_bool, value); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, std::int64_t value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_int, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_int, value); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, double value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_double, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_double, value); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, std::string_view value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_string, value.data()); + auto *mgp_val = mgp::MemHandlerCallback(value_make_string, value.data()); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const char *value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_string, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_string, value); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const List &list) { - auto mgp_val = mgp::value_make_list(mgp::MemHandlerCallback(list_copy, list.ptr_)); + auto *mgp_val = mgp::value_make_list(mgp::MemHandlerCallback(list_copy, list.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const Map &map) { - auto mgp_val = mgp::value_make_map(mgp::MemHandlerCallback(map_copy, map.ptr_)); + auto *mgp_val = mgp::value_make_map(mgp::MemHandlerCallback(map_copy, map.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const Node &node) { - auto mgp_val = mgp::value_make_vertex(mgp::MemHandlerCallback(vertex_copy, node.ptr_)); + auto *mgp_val = mgp::value_make_vertex(mgp::MemHandlerCallback(vertex_copy, node.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const Relationship &relationship) { - auto mgp_val = mgp::value_make_edge(mgp::MemHandlerCallback(edge_copy, relationship.ptr_)); + auto *mgp_val = mgp::value_make_edge(mgp::MemHandlerCallback(edge_copy, relationship.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const Path &path) { - auto mgp_val = mgp::value_make_path(mgp::MemHandlerCallback(path_copy, path.ptr_)); + auto *mgp_val = mgp::value_make_path(mgp::MemHandlerCallback(path_copy, path.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const Date &date) { - auto mgp_val = mgp::value_make_date(mgp::MemHandlerCallback(date_copy, date.ptr_)); + auto *mgp_val = mgp::value_make_date(mgp::MemHandlerCallback(date_copy, date.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const LocalTime &local_time) { - auto mgp_val = mgp::value_make_local_time(mgp::MemHandlerCallback(local_time_copy, local_time.ptr_)); + auto *mgp_val = mgp::value_make_local_time(mgp::MemHandlerCallback(local_time_copy, local_time.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const LocalDateTime &local_date_time) { - auto mgp_val = mgp::value_make_local_date_time(mgp::MemHandlerCallback(local_date_time_copy, local_date_time.ptr_)); + auto *mgp_val = mgp::value_make_local_date_time(mgp::MemHandlerCallback(local_date_time_copy, local_date_time.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } inline void Record::Insert(const char *field_name, const Duration &duration) { - auto mgp_val = mgp::value_make_duration(mgp::MemHandlerCallback(duration_copy, duration.ptr_)); + auto *mgp_val = mgp::value_make_duration(mgp::MemHandlerCallback(duration_copy, duration.ptr_)); { mgp::result_record_insert(record_, field_name, mgp_val); } mgp::value_destroy(mgp_val); } @@ -4086,8 +4086,8 @@ inline void Record::Insert(const char *field_name, const Value &value) { inline RecordFactory::RecordFactory(mgp_result *result) : result_(result) {} -inline const Record RecordFactory::NewRecord() const { - auto record = mgp::result_new_record(result_); +inline Record RecordFactory::NewRecord() const { + auto *record = mgp::result_new_record(result_); if (record == nullptr) { throw mg_exception::NotEnoughMemoryException(); } @@ -4107,85 +4107,85 @@ inline void RecordFactory::SetErrorMessage(const char *error_msg) const { inline Result::Result(mgp_func_result *result) : result_(result) {} inline void Result::SetValue(bool value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_bool, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_bool, value); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(std::int64_t value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_int, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_int, value); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(double value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_double, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_double, value); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(std::string_view value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_string, value.data()); + auto *mgp_val = mgp::MemHandlerCallback(value_make_string, value.data()); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const char *value) { - auto mgp_val = mgp::MemHandlerCallback(value_make_string, value); + auto *mgp_val = mgp::MemHandlerCallback(value_make_string, value); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const List &list) { - auto mgp_val = mgp::value_make_list(mgp::MemHandlerCallback(list_copy, list.ptr_)); + auto *mgp_val = mgp::value_make_list(mgp::MemHandlerCallback(list_copy, list.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const Map &map) { - auto mgp_val = mgp::value_make_map(mgp::MemHandlerCallback(map_copy, map.ptr_)); + auto *mgp_val = mgp::value_make_map(mgp::MemHandlerCallback(map_copy, map.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const Node &node) { - auto mgp_val = mgp::value_make_vertex(mgp::MemHandlerCallback(vertex_copy, node.ptr_)); + auto *mgp_val = mgp::value_make_vertex(mgp::MemHandlerCallback(vertex_copy, node.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const Relationship &relationship) { - auto mgp_val = mgp::value_make_edge(mgp::MemHandlerCallback(edge_copy, relationship.ptr_)); + auto *mgp_val = mgp::value_make_edge(mgp::MemHandlerCallback(edge_copy, relationship.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const Path &path) { - auto mgp_val = mgp::value_make_path(mgp::MemHandlerCallback(path_copy, path.ptr_)); + auto *mgp_val = mgp::value_make_path(mgp::MemHandlerCallback(path_copy, path.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const Date &date) { - auto mgp_val = mgp::value_make_date(mgp::MemHandlerCallback(date_copy, date.ptr_)); + auto *mgp_val = mgp::value_make_date(mgp::MemHandlerCallback(date_copy, date.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const LocalTime &local_time) { - auto mgp_val = mgp::value_make_local_time(mgp::MemHandlerCallback(local_time_copy, local_time.ptr_)); + auto *mgp_val = mgp::value_make_local_time(mgp::MemHandlerCallback(local_time_copy, local_time.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const LocalDateTime &local_date_time) { - auto mgp_val = mgp::value_make_local_date_time(mgp::MemHandlerCallback(local_date_time_copy, local_date_time.ptr_)); + auto *mgp_val = mgp::value_make_local_date_time(mgp::MemHandlerCallback(local_date_time_copy, local_date_time.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } inline void Result::SetValue(const Duration &duration) { - auto mgp_val = mgp::value_make_duration(mgp::MemHandlerCallback(duration_copy, duration.ptr_)); + auto *mgp_val = mgp::value_make_duration(mgp::MemHandlerCallback(duration_copy, duration.ptr_)); { mgp::MemHandlerCallback(func_result_set_value, result_, mgp_val); } mgp::value_destroy(mgp_val); } @@ -4222,7 +4222,7 @@ inline Parameter::Parameter(std::string_view name, Type type, const char *defaul : name(name), type_(type), optional(true), default_value(Value(default_value)) {} inline Parameter::Parameter(std::string_view name, Type type, Value default_value) - : name(name), type_(type), optional(true), default_value(default_value) {} + : name(name), type_(type), optional(true), default_value(std::move(default_value)) {} inline Parameter::Parameter(std::string_view name, std::pair list_type) : name(name), type_(list_type.first), list_item_type_(list_type.second) {} @@ -4232,7 +4232,7 @@ inline Parameter::Parameter(std::string_view name, std::pair list_ty type_(list_type.first), list_item_type_(list_type.second), optional(true), - default_value(default_value) {} + default_value(std::move(default_value)) {} inline mgp_type *Parameter::GetMGPType() const { if (type_ == Type::List) { diff --git a/query_modules/schema.cpp b/query_modules/schema.cpp index d5a657e98..1b3035bab 100644 --- a/query_modules/schema.cpp +++ b/query_modules/schema.cpp @@ -111,7 +111,6 @@ void Schema::ProcessPropertiesRel(mgp::Record &record, const std::string_view &t void Schema::NodeTypeProperties(mgp_list * /*args*/, mgp_graph *memgraph_graph, mgp_result *result, mgp_memory *memory) { mgp::MemoryDispatcherGuard guard{memory}; - ; const auto record_factory = mgp::RecordFactory(result); try { const mgp::Graph graph = mgp::Graph(memgraph_graph); @@ -570,7 +569,6 @@ void Schema::Assert(mgp_list *args, mgp_graph *memgraph_graph, mgp_result *resul extern "C" int mgp_init_module(struct mgp_module *module, struct mgp_memory *memory) { try { mgp::MemoryDispatcherGuard guard{memory}; - ; AddProcedure(Schema::NodeTypeProperties, Schema::kProcedureNodeType, mgp::ProcedureType::Read, {}, {mgp::Return(Schema::kReturnNodeType, mgp::Type::String), diff --git a/src/audit/log.cpp b/src/audit/log.cpp index 635898a16..4222ebb28 100644 --- a/src/audit/log.cpp +++ b/src/audit/log.cpp @@ -13,6 +13,7 @@ #include #include +#include #include "storage/v2/temporal.hpp" #include "utils/logging.hpp" @@ -87,8 +88,8 @@ inline nlohmann::json PropertyValueToJson(const storage::PropertyValue &pv) { return ret; } -Log::Log(const std::filesystem::path &storage_directory, int32_t buffer_size, int32_t buffer_flush_interval_millis) - : storage_directory_(storage_directory), +Log::Log(std::filesystem::path storage_directory, int32_t buffer_size, int32_t buffer_flush_interval_millis) + : storage_directory_(std::move(storage_directory)), buffer_size_(buffer_size), buffer_flush_interval_millis_(buffer_flush_interval_millis), started_(false) {} diff --git a/src/audit/log.hpp b/src/audit/log.hpp index 8def3ede5..accf41fe8 100644 --- a/src/audit/log.hpp +++ b/src/audit/log.hpp @@ -36,7 +36,7 @@ class Log { }; public: - Log(const std::filesystem::path &storage_directory, int32_t buffer_size, int32_t buffer_flush_interval_millis); + Log(std::filesystem::path storage_directory, int32_t buffer_size, int32_t buffer_flush_interval_millis); ~Log(); diff --git a/src/auth/models.cpp b/src/auth/models.cpp index 263131df3..5415dc08d 100644 --- a/src/auth/models.cpp +++ b/src/auth/models.cpp @@ -10,6 +10,7 @@ #include #include +#include #include @@ -560,20 +561,20 @@ Databases Databases::Deserialize(const nlohmann::json &data) { } #endif -User::User() {} +User::User() = default; User::User(const std::string &username) : username_(utils::ToLowerCase(username)) {} -User::User(const std::string &username, const std::string &password_hash, const Permissions &permissions) - : username_(utils::ToLowerCase(username)), password_hash_(password_hash), permissions_(permissions) {} +User::User(const std::string &username, std::string password_hash, const Permissions &permissions) + : username_(utils::ToLowerCase(username)), password_hash_(std::move(password_hash)), permissions_(permissions) {} #ifdef MG_ENTERPRISE -User::User(const std::string &username, const std::string &password_hash, const Permissions &permissions, +User::User(const std::string &username, std::string password_hash, const Permissions &permissions, FineGrainedAccessHandler fine_grained_access_handler, Databases db_access) : username_(utils::ToLowerCase(username)), - password_hash_(password_hash), + password_hash_(std::move(password_hash)), permissions_(permissions), fine_grained_access_handler_(std::move(fine_grained_access_handler)), - database_access_(db_access) {} + database_access_(std::move(db_access)) {} #endif bool User::CheckPassword(const std::string &password) { diff --git a/src/auth/models.hpp b/src/auth/models.hpp index 33ba28f80..9f66d3119 100644 --- a/src/auth/models.hpp +++ b/src/auth/models.hpp @@ -14,6 +14,7 @@ #include #include +#include #include "dbms/constants.hpp" #include "utils/logging.hpp" @@ -301,8 +302,8 @@ class Databases final { bool Contains(const std::string &db) const; bool GetAllowAll() const { return allow_all_; } - const std::set &GetGrants() const { return grants_dbs_; } - const std::set &GetDenies() const { return denies_dbs_; } + const std::set> &GetGrants() const { return grants_dbs_; } + const std::set> &GetDenies() const { return denies_dbs_; } const std::string &GetDefault() const; nlohmann::json Serialize() const; @@ -310,14 +311,17 @@ class Databases final { static Databases Deserialize(const nlohmann::json &data); private: - Databases(bool allow_all, std::set grant, std::set deny, - const std::string &default_db = dbms::kDefaultDB) - : grants_dbs_(grant), denies_dbs_(deny), allow_all_(allow_all), default_db_(default_db) {} + Databases(bool allow_all, std::set> grant, std::set> deny, + std::string default_db = dbms::kDefaultDB) + : grants_dbs_(std::move(grant)), + denies_dbs_(std::move(deny)), + allow_all_(allow_all), + default_db_(std::move(default_db)) {} - std::set grants_dbs_; //!< set of databases with granted access - std::set denies_dbs_; //!< set of databases with denied access - bool allow_all_; //!< flag to allow access to everything (denied overrides this) - std::string default_db_; //!< user's default database + std::set> grants_dbs_; //!< set of databases with granted access + std::set> denies_dbs_; //!< set of databases with denied access + bool allow_all_; //!< flag to allow access to everything (denied overrides this) + std::string default_db_; //!< user's default database }; #endif @@ -327,9 +331,9 @@ class User final { User(); explicit User(const std::string &username); - User(const std::string &username, const std::string &password_hash, const Permissions &permissions); + User(const std::string &username, std::string password_hash, const Permissions &permissions); #ifdef MG_ENTERPRISE - User(const std::string &username, const std::string &password_hash, const Permissions &permissions, + User(const std::string &username, std::string password_hash, const Permissions &permissions, FineGrainedAccessHandler fine_grained_access_handler, Databases db_access = {}); #endif User(const User &) = default; diff --git a/src/communication/bolt/client.hpp b/src/communication/bolt/client.hpp index 35be997d0..008fca907 100644 --- a/src/communication/bolt/client.hpp +++ b/src/communication/bolt/client.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "communication/bolt/v1/codes.hpp" @@ -34,8 +35,8 @@ class FailureResponseException : public utils::BasicException { explicit FailureResponseException(const std::string &message) : utils::BasicException{message} {} - FailureResponseException(const std::string &code, const std::string &message) - : utils::BasicException{message}, code_{code} {} + FailureResponseException(std::string code, const std::string &message) + : utils::BasicException{message}, code_{std::move(code)} {} const std::string &code() const { return code_; } SPECIALIZE_GET_EXCEPTION_NAME(FailureResponseException) diff --git a/src/communication/bolt/v1/decoder/chunked_decoder_buffer.hpp b/src/communication/bolt/v1/decoder/chunked_decoder_buffer.hpp index 0d096352b..e82019d09 100644 --- a/src/communication/bolt/v1/decoder/chunked_decoder_buffer.hpp +++ b/src/communication/bolt/v1/decoder/chunked_decoder_buffer.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -51,7 +51,7 @@ enum class ChunkState : uint8_t { template class ChunkedDecoderBuffer { public: - ChunkedDecoderBuffer(TBuffer &buffer) : buffer_(buffer) { data_.reserve(kChunkMaxDataSize); } + explicit ChunkedDecoderBuffer(TBuffer &buffer) : buffer_(buffer) { data_.reserve(kChunkMaxDataSize); } /** * Reads data from the internal buffer. diff --git a/src/communication/bolt/v1/decoder/decoder.hpp b/src/communication/bolt/v1/decoder/decoder.hpp index 593f514f5..8a8821708 100644 --- a/src/communication/bolt/v1/decoder/decoder.hpp +++ b/src/communication/bolt/v1/decoder/decoder.hpp @@ -401,11 +401,11 @@ class Decoder { } auto &labels = dv.ValueList(); vertex.labels.reserve(labels.size()); - for (size_t i = 0; i < labels.size(); ++i) { - if (labels[i].type() != Value::Type::String) { + for (auto &label : labels) { + if (label.type() != Value::Type::String) { return false; } - vertex.labels.emplace_back(std::move(labels[i].ValueString())); + vertex.labels.emplace_back(std::move(label.ValueString())); } // read properties diff --git a/src/communication/bolt/v1/encoder/base_encoder.hpp b/src/communication/bolt/v1/encoder/base_encoder.hpp index ee34ec085..8ce802b82 100644 --- a/src/communication/bolt/v1/encoder/base_encoder.hpp +++ b/src/communication/bolt/v1/encoder/base_encoder.hpp @@ -111,12 +111,12 @@ class BaseEncoder { void WriteList(const std::vector &value) { WriteTypeSize(value.size(), MarkerList); - for (auto &x : value) WriteValue(x); + for (const auto &x : value) WriteValue(x); } void WriteMap(const std::map &value) { WriteTypeSize(value.size(), MarkerMap); - for (auto &x : value) { + for (const auto &x : value) { WriteString(x.first); WriteValue(x.second); } @@ -205,11 +205,11 @@ class BaseEncoder { WriteRAW(utils::UnderlyingCast(Marker::TinyStruct) + 3); WriteRAW(utils::UnderlyingCast(Signature::Path)); WriteTypeSize(path.vertices.size(), MarkerList); - for (auto &v : path.vertices) WriteVertex(v); + for (const auto &v : path.vertices) WriteVertex(v); WriteTypeSize(path.edges.size(), MarkerList); - for (auto &e : path.edges) WriteEdge(e); + for (const auto &e : path.edges) WriteEdge(e); WriteTypeSize(path.indices.size(), MarkerList); - for (auto &i : path.indices) WriteInt(i); + for (const auto &i : path.indices) WriteInt(i); } void WriteDate(const utils::Date &date) { diff --git a/src/communication/bolt/v1/encoder/chunked_encoder_buffer.hpp b/src/communication/bolt/v1/encoder/chunked_encoder_buffer.hpp index 6751ce48b..9e481d0f7 100644 --- a/src/communication/bolt/v1/encoder/chunked_encoder_buffer.hpp +++ b/src/communication/bolt/v1/encoder/chunked_encoder_buffer.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -48,7 +48,7 @@ namespace memgraph::communication::bolt { template class ChunkedEncoderBuffer { public: - ChunkedEncoderBuffer(TOutputStream &output_stream) : output_stream_(output_stream) {} + explicit ChunkedEncoderBuffer(TOutputStream &output_stream) : output_stream_(output_stream) {} /** * Writes n values into the buffer. If n is bigger than whole chunk size diff --git a/src/communication/bolt/v1/encoder/client_encoder.hpp b/src/communication/bolt/v1/encoder/client_encoder.hpp index 49f3f0c16..34a5a9b50 100644 --- a/src/communication/bolt/v1/encoder/client_encoder.hpp +++ b/src/communication/bolt/v1/encoder/client_encoder.hpp @@ -39,7 +39,7 @@ class ClientEncoder : private BaseEncoder { using BaseEncoder::buffer_; public: - ClientEncoder(Buffer &buffer) : BaseEncoder(buffer) {} + explicit ClientEncoder(Buffer &buffer) : BaseEncoder(buffer) {} using BaseEncoder::UpdateVersion; diff --git a/src/communication/bolt/v1/encoder/encoder.hpp b/src/communication/bolt/v1/encoder/encoder.hpp index bc3203d90..028c4bf37 100644 --- a/src/communication/bolt/v1/encoder/encoder.hpp +++ b/src/communication/bolt/v1/encoder/encoder.hpp @@ -32,7 +32,7 @@ class Encoder : private BaseEncoder { using BaseEncoder::buffer_; public: - Encoder(Buffer &buffer) : BaseEncoder(buffer) {} + explicit Encoder(Buffer &buffer) : BaseEncoder(buffer) {} using BaseEncoder::UpdateVersion; diff --git a/src/communication/bolt/v1/states/handlers.hpp b/src/communication/bolt/v1/states/handlers.hpp index 26c995719..f873f0e6e 100644 --- a/src/communication/bolt/v1/states/handlers.hpp +++ b/src/communication/bolt/v1/states/handlers.hpp @@ -93,7 +93,7 @@ State HandlePullDiscard(TSession &session, std::optional n, std::optional AuthenticateUser(TSession &session, Value &metadata) { std::string username; std::string password; if (data["scheme"].ValueString() == "basic") { - if (!data.count("principal")) { // Special case principal = "" + if (!data.contains("principal")) { // Special case principal = "" spdlog::warn("The client didn't supply the principal field! Trying with \"\"..."); data["principal"] = ""; } - if (!data.count("credentials")) { // Special case credentials = "" + if (!data.contains("credentials")) { // Special case credentials = "" spdlog::warn("The client didn't supply the credentials field! Trying with \"\"..."); data["credentials"] = ""; } @@ -118,7 +118,7 @@ std::optional GetMetadataV4(TSession &session, const Marker marker) { } auto &data = metadata.ValueMap(); - if (!data.count("user_agent")) { + if (!data.contains("user_agent")) { spdlog::warn("The client didn't supply the user agent!"); return std::nullopt; } @@ -142,7 +142,7 @@ std::optional GetInitDataV5(TSession &session, const Marker marker) { } const auto &data = metadata.ValueMap(); - if (!data.count("user_agent")) { + if (!data.contains("user_agent")) { spdlog::warn("The client didn't supply the user agent!"); return std::nullopt; } diff --git a/src/communication/bolt/v1/value.hpp b/src/communication/bolt/v1/value.hpp index f17e4e2a6..9f189b1f7 100644 --- a/src/communication/bolt/v1/value.hpp +++ b/src/communication/bolt/v1/value.hpp @@ -91,7 +91,7 @@ struct UnboundedEdge { * The decoder writes data into this structure. */ struct Path { - Path() {} + Path() = default; Path(const std::vector &vertices, const std::vector &edges) { // Helper function. Looks for the given element in the collection. If found, diff --git a/src/communication/client.hpp b/src/communication/client.hpp index c0f7cfad8..64507a321 100644 --- a/src/communication/client.hpp +++ b/src/communication/client.hpp @@ -132,7 +132,7 @@ class Client final { */ class ClientInputStream final { public: - ClientInputStream(Client &client); + explicit ClientInputStream(Client &client); ClientInputStream(const ClientInputStream &) = delete; ClientInputStream(ClientInputStream &&) = delete; @@ -156,7 +156,7 @@ class ClientInputStream final { */ class ClientOutputStream final { public: - ClientOutputStream(Client &client); + explicit ClientOutputStream(Client &client); ClientOutputStream(const ClientOutputStream &) = delete; ClientOutputStream(ClientOutputStream &&) = delete; diff --git a/src/communication/context.cpp b/src/communication/context.cpp index 53cb4586b..18794a4cd 100644 --- a/src/communication/context.cpp +++ b/src/communication/context.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -34,7 +34,7 @@ ClientContext::ClientContext(bool use_ssl) : use_ssl_(use_ssl), ctx_(nullptr) { } ClientContext::ClientContext(const std::string &key_file, const std::string &cert_file) : ClientContext(true) { - if (key_file != "" && cert_file != "") { + if (!key_file.empty() && !cert_file.empty()) { MG_ASSERT(SSL_CTX_use_certificate_file(ctx_, cert_file.c_str(), SSL_FILETYPE_PEM) == 1, "Couldn't load client certificate from file: {}", cert_file); MG_ASSERT(SSL_CTX_use_PrivateKey_file(ctx_, key_file.c_str(), SSL_FILETYPE_PEM) == 1, @@ -124,7 +124,7 @@ ServerContext &ServerContext::operator=(ServerContext &&other) noexcept { return *this; } -ServerContext::~ServerContext() {} +ServerContext::~ServerContext() = default; SSL_CTX *ServerContext::context() { MG_ASSERT(ctx_); diff --git a/src/communication/helpers.cpp b/src/communication/helpers.cpp index 0f91c0ff6..2374e110a 100644 --- a/src/communication/helpers.cpp +++ b/src/communication/helpers.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -15,7 +15,7 @@ namespace memgraph::communication { -const std::string SslGetLastError() { +std::string SslGetLastError() { char buff[2048]; auto err = ERR_get_error(); ERR_error_string_n(err, buff, sizeof(buff)); diff --git a/src/communication/helpers.hpp b/src/communication/helpers.hpp index b82b68a38..f50697162 100644 --- a/src/communication/helpers.hpp +++ b/src/communication/helpers.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -18,6 +18,6 @@ namespace memgraph::communication { /** * This function reads and returns a string describing the last OpenSSL error. */ -const std::string SslGetLastError(); +std::string SslGetLastError(); } // namespace memgraph::communication diff --git a/src/communication/http/listener.hpp b/src/communication/http/listener.hpp index 029bf5ca1..fac4cfaf3 100644 --- a/src/communication/http/listener.hpp +++ b/src/communication/http/listener.hpp @@ -38,7 +38,7 @@ class Listener final : public std::enable_shared_from_this static std::shared_ptr Create(Args &&...args) { diff --git a/src/communication/listener.hpp b/src/communication/listener.hpp index cbb6c0b2f..066d3c53c 100644 --- a/src/communication/listener.hpp +++ b/src/communication/listener.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include @@ -51,13 +52,13 @@ class Listener final { using SessionHandler = Session; public: - Listener(TSessionContext *data, ServerContext *context, int inactivity_timeout_sec, const std::string &service_name, + Listener(TSessionContext *data, ServerContext *context, int inactivity_timeout_sec, std::string service_name, size_t workers_count) : data_(data), alive_(false), context_(context), inactivity_timeout_sec_(inactivity_timeout_sec), - service_name_(service_name), + service_name_(std::move(service_name)), workers_count_(workers_count) {} ~Listener() { diff --git a/src/communication/result_stream_faker.hpp b/src/communication/result_stream_faker.hpp index 1c899b31b..f8786dd43 100644 --- a/src/communication/result_stream_faker.hpp +++ b/src/communication/result_stream_faker.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -80,7 +80,7 @@ class ResultStreamFaker { std::transform(header.begin(), header.end(), column_widths.begin(), [](const auto &s) { return s.size(); }); // convert all the results into strings, and track max column width - auto &results_data = results.GetResults(); + const auto &results_data = results.GetResults(); std::vector> result_strings(results_data.size(), std::vector(column_widths.size())); for (int row_ind = 0; row_ind < static_cast(results_data.size()); ++row_ind) { diff --git a/src/communication/session.hpp b/src/communication/session.hpp index e44bf9532..a6c439ced 100644 --- a/src/communication/session.hpp +++ b/src/communication/session.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -51,7 +52,8 @@ using InputStream = Buffer::ReadEnd; */ class OutputStream final { public: - OutputStream(std::function write_function) : write_function_(write_function) {} + explicit OutputStream(std::function write_function) + : write_function_(std::move(write_function)) {} OutputStream(const OutputStream &) = delete; OutputStream(OutputStream &&) = delete; diff --git a/src/communication/v2/listener.hpp b/src/communication/v2/listener.hpp index 82d6fc2cb..1061f8c09 100644 --- a/src/communication/v2/listener.hpp +++ b/src/communication/v2/listener.hpp @@ -47,7 +47,7 @@ class Listener final : public std::enable_shared_from_this static std::shared_ptr Create(Args &&...args) { diff --git a/src/communication/v2/session.hpp b/src/communication/v2/session.hpp index 37e55e112..b54607729 100644 --- a/src/communication/v2/session.hpp +++ b/src/communication/v2/session.hpp @@ -76,7 +76,7 @@ using tcp = boost::asio::ip::tcp; class OutputStream final { public: explicit OutputStream(std::function write_function) - : write_function_(write_function) {} + : write_function_(std::move(write_function)) {} OutputStream(const OutputStream &) = delete; OutputStream(OutputStream &&) = delete; diff --git a/src/communication/websocket/server.hpp b/src/communication/websocket/server.hpp index 0853d3ebc..31a592932 100644 --- a/src/communication/websocket/server.hpp +++ b/src/communication/websocket/server.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -16,6 +16,7 @@ #include #include #include +#include #include "communication/websocket/listener.hpp" #include "io/network/endpoint.hpp" @@ -45,7 +46,7 @@ class Server final { class LoggingSink : public spdlog::sinks::base_sink { public: - explicit LoggingSink(std::weak_ptr listener) : listener_(listener) {} + explicit LoggingSink(std::weak_ptr listener) : listener_(std::move(listener)) {} private: void sink_it_(const spdlog::details::log_msg &msg) override; diff --git a/src/dbms/dbms_handler.hpp b/src/dbms/dbms_handler.hpp index 990420bf8..27ab963d4 100644 --- a/src/dbms/dbms_handler.hpp +++ b/src/dbms/dbms_handler.hpp @@ -542,7 +542,7 @@ class DbmsHandler { DatabaseHandler db_handler_; //!< multi-tenancy storage handler std::unique_ptr durability_; //!< list of active dbs (pointer so we can postpone its creation) bool delete_on_drop_; //!< Flag defining if dropping storage also deletes its directory - std::set defunct_dbs_; //!< Databases that are in an unknown state due to various failures + std::set> defunct_dbs_; //!< Databases that are in an unknown state due to various failures #else mutable utils::Gatekeeper db_gatekeeper_; //!< Single databases gatekeeper #endif diff --git a/src/dbms/handler.hpp b/src/dbms/handler.hpp index a7622e6b2..568b2fc7c 100644 --- a/src/dbms/handler.hpp +++ b/src/dbms/handler.hpp @@ -38,7 +38,7 @@ class Handler { * @brief Empty Handler constructor. * */ - Handler() {} + Handler() = default; /** * @brief Generate a new context and corresponding configuration. diff --git a/src/glue/SessionHL.cpp b/src/glue/SessionHL.cpp index a84f44974..cc7910d1c 100644 --- a/src/glue/SessionHL.cpp +++ b/src/glue/SessionHL.cpp @@ -10,6 +10,7 @@ // licenses/APL.txt. #include +#include #include "gflags/gflags.h" #include "audit/log.hpp" @@ -272,7 +273,7 @@ void SessionHL::Configure(const std::map *auth @@ -289,7 +290,7 @@ SessionHL::SessionHL(memgraph::query::InterpreterContext *interpreter_context, audit_log_(audit_log), #endif auth_(auth), - endpoint_(endpoint), + endpoint_(std::move(endpoint)), implicit_db_(dbms::kDefaultDB) { // Metrics update memgraph::metrics::IncrementCounter(memgraph::metrics::ActiveBoltSessions); diff --git a/src/glue/SessionHL.hpp b/src/glue/SessionHL.hpp index cc53ae08a..374d2464e 100644 --- a/src/glue/SessionHL.hpp +++ b/src/glue/SessionHL.hpp @@ -23,7 +23,7 @@ class SessionHL final : public memgraph::communication::bolt::Session { public: SessionHL(memgraph::query::InterpreterContext *interpreter_context, - const memgraph::communication::v2::ServerEndpoint &endpoint, + memgraph::communication::v2::ServerEndpoint endpoint, memgraph::communication::v2::InputStream *input_stream, memgraph::communication::v2::OutputStream *output_stream, memgraph::utils::Synchronized *auth diff --git a/src/glue/communication.cpp b/src/glue/communication.cpp index 5db3e2726..fdf5129f6 100644 --- a/src/glue/communication.cpp +++ b/src/glue/communication.cpp @@ -202,7 +202,7 @@ storage::Result> ToBoltGraph(const query::Graph &gr for (const auto &v : graph.vertices()) { auto maybe_vertex = ToBoltVertex(v, db, view); if (maybe_vertex.HasError()) return maybe_vertex.GetError(); - vertices.emplace_back(Value(std::move(*maybe_vertex))); + vertices.emplace_back(std::move(*maybe_vertex)); } map.emplace("nodes", Value(vertices)); @@ -211,7 +211,7 @@ storage::Result> ToBoltGraph(const query::Graph &gr for (const auto &e : graph.edges()) { auto maybe_edge = ToBoltEdge(e, db, view); if (maybe_edge.HasError()) return maybe_edge.GetError(); - edges.emplace_back(Value(std::move(*maybe_edge))); + edges.emplace_back(std::move(*maybe_edge)); } map.emplace("edges", Value(edges)); diff --git a/src/helpers.hpp b/src/helpers.hpp index 1cf4e0ec0..67c1906e7 100644 --- a/src/helpers.hpp +++ b/src/helpers.hpp @@ -31,7 +31,7 @@ inline void LoadConfig(const std::string &product_name) { std::vector configs = {fs::path("/etc/memgraph/memgraph.conf")}; if (getenv("HOME") != nullptr) configs.emplace_back(fs::path(getenv("HOME")) / fs::path(".memgraph/config")); { - auto memgraph_config = getenv("MEMGRAPH_CONFIG"); + auto *memgraph_config = getenv("MEMGRAPH_CONFIG"); if (memgraph_config != nullptr) { auto path = fs::path(memgraph_config); MG_ASSERT(fs::exists(path), "MEMGRAPH_CONFIG environment variable set to nonexisting path: {}", diff --git a/src/http_handlers/metrics.hpp b/src/http_handlers/metrics.hpp index d4620b774..82131d311 100644 --- a/src/http_handlers/metrics.hpp +++ b/src/http_handlers/metrics.hpp @@ -23,7 +23,6 @@ #include #include #include "storage/v2/storage.hpp" -#include "utils/event_gauge.hpp" #include "utils/event_histogram.hpp" namespace memgraph::http { diff --git a/src/integrations/kafka/consumer.hpp b/src/integrations/kafka/consumer.hpp index 34e8b1bdb..5f698a4d1 100644 --- a/src/integrations/kafka/consumer.hpp +++ b/src/integrations/kafka/consumer.hpp @@ -171,10 +171,10 @@ class Consumer final : public RdKafka::EventCb { class ConsumerRebalanceCb : public RdKafka::RebalanceCb { public: - ConsumerRebalanceCb(std::string consumer_name); + explicit ConsumerRebalanceCb(std::string consumer_name); void rebalance_cb(RdKafka::KafkaConsumer *consumer, RdKafka::ErrorCode err, - std::vector &partitions) override final; + std::vector &partitions) final; void set_offset(int64_t offset); diff --git a/src/integrations/pulsar/consumer.cpp b/src/integrations/pulsar/consumer.cpp index b3a65050b..f004cf6dc 100644 --- a/src/integrations/pulsar/consumer.cpp +++ b/src/integrations/pulsar/consumer.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -67,7 +67,7 @@ utils::BasicResult> GetBatch(TConsumer &consum return std::move(batch); case pulsar_client::Result::ResultOk: if (message.getMessageId() != last_message_id) { - batch.emplace_back(Message{std::move(message)}); + batch.emplace_back(std::move(message)); } break; default: diff --git a/src/io/network/endpoint.hpp b/src/io/network/endpoint.hpp index e10c80657..281be2162 100644 --- a/src/io/network/endpoint.hpp +++ b/src/io/network/endpoint.hpp @@ -48,8 +48,8 @@ struct Endpoint { uint16_t port{0}; IpFamily family{IpFamily::NONE}; - static std::optional> ParseSocketOrAddress( - const std::string &address, const std::optional default_port); + static std::optional> ParseSocketOrAddress(const std::string &address, + std::optional default_port); /** * Tries to parse the given string as either a socket address or ip address. @@ -61,8 +61,8 @@ struct Endpoint { * it into an ip address and a port number; even if a default port is given, * it won't be used, as we expect that it is given in the address string. */ - static std::optional> ParseSocketOrIpAddress( - const std::string &address, const std::optional default_port); + static std::optional> ParseSocketOrIpAddress(const std::string &address, + std::optional default_port); /** * Tries to parse given string as either socket address or hostname. @@ -72,7 +72,7 @@ struct Endpoint { * After we parse hostname and port we try to resolve the hostname into an ip_address. */ static std::optional> ParseHostname(const std::string &address, - const std::optional default_port); + std::optional default_port); static IpFamily GetIpFamily(const std::string &address); diff --git a/src/io/network/epoll.hpp b/src/io/network/epoll.hpp index 09c485eb5..2f0d0dfd1 100644 --- a/src/io/network/epoll.hpp +++ b/src/io/network/epoll.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -32,7 +32,7 @@ class Epoll { public: using Event = struct epoll_event; - Epoll(bool set_cloexec = false) : epoll_fd_(epoll_create1(set_cloexec ? EPOLL_CLOEXEC : 0)) { + explicit Epoll(bool set_cloexec = false) : epoll_fd_(epoll_create1(set_cloexec ? EPOLL_CLOEXEC : 0)) { // epoll_create1 returns an error if there is a logical error in our code // (for example invalid flags) or if there is irrecoverable error. In both // cases it is best to terminate. diff --git a/src/io/network/socket.hpp b/src/io/network/socket.hpp index 22e787611..c2b6354af 100644 --- a/src/io/network/socket.hpp +++ b/src/io/network/socket.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include "io/network/endpoint.hpp" @@ -201,7 +202,7 @@ class Socket { bool WaitForReadyWrite(); private: - Socket(int fd, const Endpoint &endpoint) : socket_(fd), endpoint_(endpoint) {} + Socket(int fd, Endpoint endpoint) : socket_(fd), endpoint_(std::move(endpoint)) {} int socket_ = -1; Endpoint endpoint_; diff --git a/src/kvstore/kvstore.cpp b/src/kvstore/kvstore.cpp index 383324238..877d6f9bd 100644 --- a/src/kvstore/kvstore.cpp +++ b/src/kvstore/kvstore.cpp @@ -128,7 +128,7 @@ KVStore::iterator::iterator(const KVStore *kvstore, const std::string &prefix, b KVStore::iterator::iterator(KVStore::iterator &&other) { pimpl_ = std::move(other.pimpl_); } -KVStore::iterator::~iterator() {} +KVStore::iterator::~iterator() = default; KVStore::iterator &KVStore::iterator::operator=(KVStore::iterator &&other) { pimpl_ = std::move(other.pimpl_); diff --git a/src/query/common.hpp b/src/query/common.hpp index 8f1b0a94c..6f45760fe 100644 --- a/src/query/common.hpp +++ b/src/query/common.hpp @@ -41,7 +41,7 @@ bool TypedValueCompare(const TypedValue &a, const TypedValue &b); /// the define how respective elements compare. class TypedValueVectorCompare final { public: - TypedValueVectorCompare() {} + TypedValueVectorCompare() = default; explicit TypedValueVectorCompare(const std::vector &ordering) : ordering_(ordering) {} template @@ -147,8 +147,8 @@ concept AccessorWithUpdateProperties = requires(T accessor, /// /// @throw QueryRuntimeException if value cannot be set as a property value template -auto UpdatePropertiesChecked(T *record, std::map &properties) -> - typename std::remove_referenceUpdateProperties(properties).GetValue())>::type { +auto UpdatePropertiesChecked(T *record, std::map &properties) + -> std::remove_reference_tUpdateProperties(properties).GetValue())> { try { auto maybe_values = record->UpdateProperties(properties); if (maybe_values.HasError()) { diff --git a/src/query/cypher_query_interpreter.hpp b/src/query/cypher_query_interpreter.hpp index f33fa61e2..f1e9113a3 100644 --- a/src/query/cypher_query_interpreter.hpp +++ b/src/query/cypher_query_interpreter.hpp @@ -11,6 +11,8 @@ #pragma once +#include + #include "query/config.hpp" #include "query/frontend/semantic/required_privileges.hpp" #include "query/frontend/semantic/symbol_generator.hpp" @@ -98,8 +100,8 @@ ParsedQuery ParseQuery(const std::string &query_string, const std::map root, double cost, AstStorage storage, - const SymbolTable &symbol_table) - : root_(std::move(root)), cost_(cost), storage_(std::move(storage)), symbol_table_(symbol_table) {} + SymbolTable symbol_table) + : root_(std::move(root)), cost_(cost), storage_(std::move(storage)), symbol_table_(std::move(symbol_table)) {} const plan::LogicalOperator &GetRoot() const override { return *root_; } double GetCost() const override { return cost_; } diff --git a/src/query/db_accessor.hpp b/src/query/db_accessor.hpp index 75ec1e9ae..f616dc5a2 100644 --- a/src/query/db_accessor.hpp +++ b/src/query/db_accessor.hpp @@ -40,7 +40,6 @@ class EdgeAccessor final { public: storage::EdgeAccessor impl_; - public: explicit EdgeAccessor(storage::EdgeAccessor impl) : impl_(std::move(impl)) {} bool IsVisible(storage::View view) const { return impl_.IsVisible(view); } @@ -108,7 +107,6 @@ class VertexAccessor final { static EdgeAccessor MakeEdgeAccessor(const storage::EdgeAccessor impl) { return EdgeAccessor(impl); } - public: explicit VertexAccessor(storage::VertexAccessor impl) : impl_(impl) {} bool IsVisible(storage::View view) const { return impl_.IsVisible(view); } diff --git a/src/query/dump.cpp b/src/query/dump.cpp index dd99f0f63..a1421cbf9 100644 --- a/src/query/dump.cpp +++ b/src/query/dump.cpp @@ -159,7 +159,7 @@ void DumpProperties(std::ostream *os, query::DbAccessor *dba, *os << "{"; if (property_id) { *os << kInternalPropertyId << ": " << *property_id; - if (store.size() > 0) *os << ", "; + if (!store.empty()) *os << ", "; } utils::PrintIterable(*os, store, ", ", [&dba](auto &os, const auto &kv) { os << EscapeName(dba->PropertyToName(kv.first)) << ": "; @@ -228,7 +228,7 @@ void DumpEdge(std::ostream *os, query::DbAccessor *dba, const query::EdgeAccesso throw query::QueryRuntimeException("Unexpected error when getting properties."); } } - if (maybe_props->size() > 0) { + if (!maybe_props->empty()) { *os << " "; DumpProperties(os, dba, *maybe_props); } diff --git a/src/query/frame_change.hpp b/src/query/frame_change.hpp index 1d9ebc70c..32fe1f36e 100644 --- a/src/query/frame_change.hpp +++ b/src/query/frame_change.hpp @@ -47,9 +47,9 @@ struct CachedValue { if (!maybe_list.IsList()) { return false; } - auto &list = maybe_list.ValueList(); + const auto &list = maybe_list.ValueList(); TypedValue::Hash hash{}; - for (auto &element : list) { + for (const auto &element : list) { const auto key = hash(element); auto &vector_values = cache_[key]; if (!IsValueInVec(vector_values, element)) { diff --git a/src/query/frontend/ast/ast.hpp b/src/query/frontend/ast/ast.hpp index 6b7fdb2c6..dc11c3887 100644 --- a/src/query/frontend/ast/ast.hpp +++ b/src/query/frontend/ast/ast.hpp @@ -23,9 +23,7 @@ #include "storage/v2/property_value.hpp" #include "utils/typeinfo.hpp" -namespace memgraph { - -namespace query { +namespace memgraph::query { struct LabelIx { static const utils::TypeInfo kType; @@ -62,8 +60,8 @@ inline bool operator!=(const PropertyIx &a, const PropertyIx &b) { return !(a == inline bool operator==(const EdgeTypeIx &a, const EdgeTypeIx &b) { return a.ix == b.ix && a.name == b.name; } inline bool operator!=(const EdgeTypeIx &a, const EdgeTypeIx &b) { return !(a == b); } -} // namespace query -} // namespace memgraph +} // namespace memgraph::query + namespace std { template <> @@ -83,9 +81,7 @@ struct hash { } // namespace std -namespace memgraph { - -namespace query { +namespace memgraph::query { class Tree; @@ -3577,5 +3573,4 @@ class ShowDatabasesQuery : public memgraph::query::Query { } }; -} // namespace query -} // namespace memgraph +} // namespace memgraph::query diff --git a/src/query/frontend/ast/pretty_print.cpp b/src/query/frontend/ast/pretty_print.cpp index 8275f1cb5..ef45afd7d 100644 --- a/src/query/frontend/ast/pretty_print.cpp +++ b/src/query/frontend/ast/pretty_print.cpp @@ -105,7 +105,7 @@ void PrintObject(std::ostream *out, const std::map &map); template void PrintObject(std::ostream *out, const T &arg) { - static_assert(!std::is_convertible::value, + static_assert(!std::is_convertible_v, "This overload shouldn't be called with pointers convertible " "to Expression *. This means your other PrintObject overloads aren't " "being called for certain AST nodes when they should (or perhaps such " diff --git a/src/query/frontend/opencypher/parser.hpp b/src/query/frontend/opencypher/parser.hpp index 3a17d27a8..f25d6e5e9 100644 --- a/src/query/frontend/opencypher/parser.hpp +++ b/src/query/frontend/opencypher/parser.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -31,7 +31,7 @@ class Parser { * @param query incoming query that has to be compiled into query plan * the first step is to generate AST */ - Parser(const std::string query) : query_(std::move(query)) { + explicit Parser(const std::string query) : query_(std::move(query)) { parser_.removeErrorListeners(); parser_.addErrorListener(&error_listener_); tree_ = parser_.cypher(); diff --git a/src/query/frontend/semantic/symbol.hpp b/src/query/frontend/semantic/symbol.hpp index 5381cb48d..77557b6fe 100644 --- a/src/query/frontend/semantic/symbol.hpp +++ b/src/query/frontend/semantic/symbol.hpp @@ -12,12 +12,11 @@ #pragma once #include +#include #include "utils/typeinfo.hpp" -namespace memgraph { - -namespace query { +namespace memgraph::query { class Symbol { public: @@ -34,9 +33,13 @@ class Symbol { return enum_string[static_cast(type)]; } - Symbol() {} - Symbol(const std::string &name, int position, bool user_declared, Type type = Type::ANY, int token_position = -1) - : name_(name), position_(position), user_declared_(user_declared), type_(type), token_position_(token_position) {} + Symbol() = default; + Symbol(std::string name, int position, bool user_declared, Type type = Type::ANY, int token_position = -1) + : name_(std::move(name)), + position_(position), + user_declared_(user_declared), + type_(type), + token_position_(token_position) {} bool operator==(const Symbol &other) const { return position_ == other.position_ && name_ == other.name_ && type_ == other.type_; @@ -57,8 +60,8 @@ class Symbol { int64_t token_position_{-1}; }; -} // namespace query -} // namespace memgraph +} // namespace memgraph::query + namespace std { template <> diff --git a/src/query/frontend/semantic/symbol_generator.hpp b/src/query/frontend/semantic/symbol_generator.hpp index c69d8729e..207bbddbd 100644 --- a/src/query/frontend/semantic/symbol_generator.hpp +++ b/src/query/frontend/semantic/symbol_generator.hpp @@ -183,7 +183,7 @@ class SymbolGenerator : public HierarchicalTreeVisitor { /// If property lookup for one symbol is visited more times, it is better to fetch all properties class PropertyLookupEvaluationModeVisitor : public ExpressionVisitor { public: - explicit PropertyLookupEvaluationModeVisitor() {} + explicit PropertyLookupEvaluationModeVisitor() = default; using ExpressionVisitor::Visit; diff --git a/src/query/frontend/semantic/symbol_table.hpp b/src/query/frontend/semantic/symbol_table.hpp index 23b4965c5..0b521356c 100644 --- a/src/query/frontend/semantic/symbol_table.hpp +++ b/src/query/frontend/semantic/symbol_table.hpp @@ -22,7 +22,7 @@ namespace memgraph::query { class SymbolTable final { public: - SymbolTable() {} + SymbolTable() = default; const Symbol &CreateSymbol(const std::string &name, bool user_declared, Symbol::Type type = Symbol::Type::ANY, int32_t token_position = -1) { MG_ASSERT(table_.size() <= std::numeric_limits::max(), diff --git a/src/query/frontend/stripped.cpp b/src/query/frontend/stripped.cpp index 56d29032c..9740cd463 100644 --- a/src/query/frontend/stripped.cpp +++ b/src/query/frontend/stripped.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -16,6 +16,7 @@ #include #include #include +#include #include #include "query/exceptions.hpp" @@ -32,7 +33,7 @@ namespace memgraph::query::frontend { using namespace lexer_constants; -StrippedQuery::StrippedQuery(const std::string &query) : original_(query) { +StrippedQuery::StrippedQuery(std::string query) : original_(std::move(query)) { enum class Token { UNMATCHED, KEYWORD, // Including true, false and null. @@ -255,29 +256,29 @@ std::string GetFirstUtf8Symbol(const char *_s) { // According to // https://stackoverflow.com/questions/16260033/reinterpret-cast-between-char-and-stduint8-t-safe // this checks if casting from const char * to uint8_t is undefined behaviour. - static_assert(std::is_same::value, + static_assert(std::is_same_v, "This library requires std::uint8_t to be implemented as " "unsigned char."); const uint8_t *s = reinterpret_cast(_s); if ((*s >> 7) == 0x00) return std::string(_s, _s + 1); if ((*s >> 5) == 0x06) { - auto *s1 = s + 1; + const auto *s1 = s + 1; if ((*s1 >> 6) != 0x02) throw LexingException("Invalid character."); return std::string(_s, _s + 2); } if ((*s >> 4) == 0x0e) { - auto *s1 = s + 1; + const auto *s1 = s + 1; if ((*s1 >> 6) != 0x02) throw LexingException("Invalid character."); - auto *s2 = s + 2; + const auto *s2 = s + 2; if ((*s2 >> 6) != 0x02) throw LexingException("Invalid character."); return std::string(_s, _s + 3); } if ((*s >> 3) == 0x1e) { - auto *s1 = s + 1; + const auto *s1 = s + 1; if ((*s1 >> 6) != 0x02) throw LexingException("Invalid character."); - auto *s2 = s + 2; + const auto *s2 = s + 2; if ((*s2 >> 6) != 0x02) throw LexingException("Invalid character."); - auto *s3 = s + 3; + const auto *s3 = s + 3; if ((*s3 >> 6) != 0x02) throw LexingException("Invalid character."); return std::string(_s, _s + 4); } @@ -286,29 +287,29 @@ std::string GetFirstUtf8Symbol(const char *_s) { // Return codepoint of first utf8 symbol and its encoded length. std::pair GetFirstUtf8SymbolCodepoint(const char *_s) { - static_assert(std::is_same::value, + static_assert(std::is_same_v, "This library requires std::uint8_t to be implemented as " "unsigned char."); const uint8_t *s = reinterpret_cast(_s); if ((*s >> 7) == 0x00) return {*s & 0x7f, 1}; if ((*s >> 5) == 0x06) { - auto *s1 = s + 1; + const auto *s1 = s + 1; if ((*s1 >> 6) != 0x02) throw LexingException("Invalid character."); return {((*s & 0x1f) << 6) | (*s1 & 0x3f), 2}; } if ((*s >> 4) == 0x0e) { - auto *s1 = s + 1; + const auto *s1 = s + 1; if ((*s1 >> 6) != 0x02) throw LexingException("Invalid character."); - auto *s2 = s + 2; + const auto *s2 = s + 2; if ((*s2 >> 6) != 0x02) throw LexingException("Invalid character."); return {((*s & 0x0f) << 12) | ((*s1 & 0x3f) << 6) | (*s2 & 0x3f), 3}; } if ((*s >> 3) == 0x1e) { - auto *s1 = s + 1; + const auto *s1 = s + 1; if ((*s1 >> 6) != 0x02) throw LexingException("Invalid character."); - auto *s2 = s + 2; + const auto *s2 = s + 2; if ((*s2 >> 6) != 0x02) throw LexingException("Invalid character."); - auto *s3 = s + 3; + const auto *s3 = s + 3; if ((*s3 >> 6) != 0x02) throw LexingException("Invalid character."); return {((*s & 0x07) << 18) | ((*s1 & 0x3f) << 12) | ((*s2 & 0x3f) << 6) | (*s3 & 0x3f), 4}; } @@ -336,7 +337,7 @@ int StrippedQuery::MatchSpecial(int start) const { return kSpecialTokens.Match(o int StrippedQuery::MatchString(int start) const { if (original_[start] != '"' && original_[start] != '\'') return 0; char start_char = original_[start]; - for (auto *p = original_.data() + start + 1; *p; ++p) { + for (const auto *p = original_.data() + start + 1; *p; ++p) { if (*p == start_char) return p - (original_.data() + start) + 1; if (*p == '\\') { ++p; @@ -346,7 +347,7 @@ int StrippedQuery::MatchString(int start) const { continue; } else if (*p == 'U' || *p == 'u') { int cnt = 0; - auto *r = p + 1; + const auto *r = p + 1; while (isxdigit(*r) && cnt < 8) { ++cnt; ++r; diff --git a/src/query/frontend/stripped.hpp b/src/query/frontend/stripped.hpp index 006fb1dd6..a20e28474 100644 --- a/src/query/frontend/stripped.hpp +++ b/src/query/frontend/stripped.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -40,7 +40,7 @@ class StrippedQuery { * * @param query Input query. */ - explicit StrippedQuery(const std::string &query); + explicit StrippedQuery(std::string query); /** * Copy constructor is deleted because we don't want to make unnecessary diff --git a/src/query/frontend/stripped_lexer_constants.hpp b/src/query/frontend/stripped_lexer_constants.hpp index 9ad95e6f5..21a14ae83 100644 --- a/src/query/frontend/stripped_lexer_constants.hpp +++ b/src/query/frontend/stripped_lexer_constants.hpp @@ -17,8 +17,7 @@ #include #include -namespace memgraph::query { -namespace lexer_constants { +namespace memgraph::query::lexer_constants { namespace trie { @@ -33,7 +32,7 @@ inline int Noop(int x) { return x; } class Trie { public: - Trie() {} + Trie() = default; Trie(std::initializer_list l) { for (const auto &s : l) { Insert(s); @@ -2934,5 +2933,4 @@ const trie::Trie kSpecialTokens = {";", "\xEF\xB9\x98", // u8"\ufe58" "\xEF\xB9\xA3", // u8"\ufe63" "\xEF\xBC\x8D"}; // u8"\uff0d" -} // namespace lexer_constants -} // namespace memgraph::query +} // namespace memgraph::query::lexer_constants diff --git a/src/query/interpret/eval.hpp b/src/query/interpret/eval.hpp index 333a7b1fa..916082bb2 100644 --- a/src/query/interpret/eval.hpp +++ b/src/query/interpret/eval.hpp @@ -825,8 +825,8 @@ class ExpressionEvaluator : public ExpressionVisitor { throw QueryRuntimeException("'coalesce' requires at least one argument."); } - for (int64_t i = 0; i < exprs.size(); ++i) { - TypedValue val(exprs[i]->Accept(*this), ctx_->memory); + for (auto &expr : exprs) { + TypedValue val(expr->Accept(*this), ctx_->memory); if (!val.IsNull()) { return val; } diff --git a/src/query/interpreter.cpp b/src/query/interpreter.cpp index 5aad0ff07..354f13dc3 100644 --- a/src/query/interpreter.cpp +++ b/src/query/interpreter.cpp @@ -797,34 +797,33 @@ Callback HandleReplicationQuery(ReplicationQuery *repl_query, const Parameters & std::vector typed_replica; typed_replica.reserve(replica_nfields); - typed_replica.emplace_back(TypedValue(replica.name)); - typed_replica.emplace_back(TypedValue(replica.socket_address)); + typed_replica.emplace_back(replica.name); + typed_replica.emplace_back(replica.socket_address); switch (replica.sync_mode) { case ReplicationQuery::SyncMode::SYNC: - typed_replica.emplace_back(TypedValue("sync")); + typed_replica.emplace_back("sync"); break; case ReplicationQuery::SyncMode::ASYNC: - typed_replica.emplace_back(TypedValue("async")); + typed_replica.emplace_back("async"); break; } - typed_replica.emplace_back(TypedValue(static_cast(replica.current_timestamp_of_replica))); - typed_replica.emplace_back( - TypedValue(static_cast(replica.current_number_of_timestamp_behind_master))); + typed_replica.emplace_back(static_cast(replica.current_timestamp_of_replica)); + typed_replica.emplace_back(static_cast(replica.current_number_of_timestamp_behind_master)); switch (replica.state) { case ReplicationQuery::ReplicaState::READY: - typed_replica.emplace_back(TypedValue("ready")); + typed_replica.emplace_back("ready"); break; case ReplicationQuery::ReplicaState::REPLICATING: - typed_replica.emplace_back(TypedValue("replicating")); + typed_replica.emplace_back("replicating"); break; case ReplicationQuery::ReplicaState::RECOVERY: - typed_replica.emplace_back(TypedValue("recovery")); + typed_replica.emplace_back("recovery"); break; case ReplicationQuery::ReplicaState::INVALID: - typed_replica.emplace_back(TypedValue("invalid")); + typed_replica.emplace_back("invalid"); break; } @@ -1962,11 +1961,11 @@ std::vector> AnalyzeGraphQueryHandler::AnalyzeGraphCreat result.reserve(kComputeStatisticsNumResults); result.emplace_back(execution_db_accessor->LabelToName(stat_entry.first)); - result.emplace_back(TypedValue()); + result.emplace_back(); result.emplace_back(static_cast(stat_entry.second.count)); - result.emplace_back(TypedValue()); - result.emplace_back(TypedValue()); - result.emplace_back(TypedValue()); + result.emplace_back(); + result.emplace_back(); + result.emplace_back(); result.emplace_back(stat_entry.second.avg_degree); results.push_back(std::move(result)); }); @@ -2883,7 +2882,7 @@ auto ShowTransactions(const std::unordered_set &interpreters, con metadata_tv.emplace(md.first, TypedValue(md.second)); } } - results.back().push_back(TypedValue(metadata_tv)); + results.back().emplace_back(metadata_tv); } } return results; diff --git a/src/query/interpreter.hpp b/src/query/interpreter.hpp index 66231059d..5cb73cb07 100644 --- a/src/query/interpreter.hpp +++ b/src/query/interpreter.hpp @@ -174,7 +174,7 @@ struct CurrentDB { class Interpreter final { public: - Interpreter(InterpreterContext *interpreter_context); + explicit Interpreter(InterpreterContext *interpreter_context); Interpreter(InterpreterContext *interpreter_context, memgraph::dbms::DatabaseAccess db); Interpreter(const Interpreter &) = delete; Interpreter &operator=(const Interpreter &) = delete; diff --git a/src/query/plan/operator.cpp b/src/query/plan/operator.cpp index b68810ad7..1c8d021c7 100644 --- a/src/query/plan/operator.cpp +++ b/src/query/plan/operator.cpp @@ -207,8 +207,8 @@ void Once::OnceCursor::Shutdown() {} void Once::OnceCursor::Reset() { did_pull_ = false; } -CreateNode::CreateNode(const std::shared_ptr &input, const NodeCreationInfo &node_info) - : input_(input ? input : std::make_shared()), node_info_(node_info) {} +CreateNode::CreateNode(const std::shared_ptr &input, NodeCreationInfo node_info) + : input_(input ? input : std::make_shared()), node_info_(std::move(node_info)) {} // Creates a vertex on this GraphDb. Returns a reference to vertex placed on the // frame. @@ -298,12 +298,12 @@ void CreateNode::CreateNodeCursor::Shutdown() { input_cursor_->Shutdown(); } void CreateNode::CreateNodeCursor::Reset() { input_cursor_->Reset(); } -CreateExpand::CreateExpand(const NodeCreationInfo &node_info, const EdgeCreationInfo &edge_info, +CreateExpand::CreateExpand(NodeCreationInfo node_info, EdgeCreationInfo edge_info, const std::shared_ptr &input, Symbol input_symbol, bool existing_node) - : node_info_(node_info), - edge_info_(edge_info), + : node_info_(std::move(node_info)), + edge_info_(std::move(edge_info)), input_(input ? input : std::make_shared()), - input_symbol_(input_symbol), + input_symbol_(std::move(input_symbol)), existing_node_(existing_node) {} ACCEPT_WITH_INPUT(CreateExpand) @@ -447,7 +447,7 @@ class ScanAllCursor : public Cursor { explicit ScanAllCursor(const ScanAll &self, Symbol output_symbol, UniqueCursorPtr input_cursor, storage::View view, TVerticesFun get_vertices, const char *op_name) : self_(self), - output_symbol_(output_symbol), + output_symbol_(std::move(output_symbol)), input_cursor_(std::move(input_cursor)), view_(view), get_vertices_(std::move(get_vertices)), @@ -518,7 +518,7 @@ class ScanAllCursor : public Cursor { }; ScanAll::ScanAll(const std::shared_ptr &input, Symbol output_symbol, storage::View view) - : input_(input ? input : std::make_shared()), output_symbol_(output_symbol), view_(view) {} + : input_(input ? input : std::make_shared()), output_symbol_(std::move(output_symbol)), view_(view) {} ACCEPT_WITH_INPUT(ScanAll) @@ -561,13 +561,13 @@ UniqueCursorPtr ScanAllByLabel::MakeCursor(utils::MemoryResource *mem) const { ScanAllByLabelPropertyRange::ScanAllByLabelPropertyRange(const std::shared_ptr &input, Symbol output_symbol, storage::LabelId label, - storage::PropertyId property, const std::string &property_name, + storage::PropertyId property, std::string property_name, std::optional lower_bound, std::optional upper_bound, storage::View view) : ScanAll(input, output_symbol, view), label_(label), property_(property), - property_name_(property_name), + property_name_(std::move(property_name)), lower_bound_(lower_bound), upper_bound_(upper_bound) { MG_ASSERT(lower_bound_ || upper_bound_, "Only one bound can be left out"); @@ -623,12 +623,12 @@ UniqueCursorPtr ScanAllByLabelPropertyRange::MakeCursor(utils::MemoryResource *m ScanAllByLabelPropertyValue::ScanAllByLabelPropertyValue(const std::shared_ptr &input, Symbol output_symbol, storage::LabelId label, - storage::PropertyId property, const std::string &property_name, + storage::PropertyId property, std::string property_name, Expression *expression, storage::View view) : ScanAll(input, output_symbol, view), label_(label), property_(property), - property_name_(property_name), + property_name_(std::move(property_name)), expression_(expression) { DMG_ASSERT(expression, "Expression is not optional."); } @@ -655,8 +655,11 @@ UniqueCursorPtr ScanAllByLabelPropertyValue::MakeCursor(utils::MemoryResource *m ScanAllByLabelProperty::ScanAllByLabelProperty(const std::shared_ptr &input, Symbol output_symbol, storage::LabelId label, storage::PropertyId property, - const std::string &property_name, storage::View view) - : ScanAll(input, output_symbol, view), label_(label), property_(property), property_name_(property_name) {} + std::string property_name, storage::View view) + : ScanAll(input, output_symbol, view), + label_(label), + property_(property), + property_name_(std::move(property_name)) {} ACCEPT_WITH_INPUT(ScanAllByLabelProperty) @@ -728,7 +731,7 @@ Expand::Expand(const std::shared_ptr &input, Symbol input_symbo Symbol edge_symbol, EdgeAtom::Direction direction, const std::vector &edge_types, bool existing_node, storage::View view) : input_(input ? input : std::make_shared()), - input_symbol_(input_symbol), + input_symbol_(std::move(input_symbol)), common_{node_symbol, edge_symbol, direction, edge_types, existing_node}, view_(view) {} @@ -962,15 +965,15 @@ ExpandVariable::ExpandVariable(const std::shared_ptr &input, Sy ExpansionLambda filter_lambda, std::optional weight_lambda, std::optional total_weight) : input_(input ? input : std::make_shared()), - input_symbol_(input_symbol), + input_symbol_(std::move(input_symbol)), common_{node_symbol, edge_symbol, direction, edge_types, existing_node}, type_(type), is_reverse_(is_reverse), lower_bound_(lower_bound), upper_bound_(upper_bound), - filter_lambda_(filter_lambda), - weight_lambda_(weight_lambda), - total_weight_(total_weight) { + filter_lambda_(std::move(filter_lambda)), + weight_lambda_(std::move(weight_lambda)), + total_weight_(std::move(total_weight)) { DMG_ASSERT(type_ == EdgeAtom::Type::DEPTH_FIRST || type_ == EdgeAtom::Type::BREADTH_FIRST || type_ == EdgeAtom::Type::WEIGHTED_SHORTEST_PATH || type_ == EdgeAtom::Type::ALL_SHORTEST_PATHS, "ExpandVariable can only be used with breadth first, depth first, " @@ -1758,7 +1761,7 @@ class ExpandWeightedShortestPathCursor : public query::plan::Cursor { if (found_it != total_cost_.end() && (found_it->second.IsNull() || (found_it->second <= next_weight).ValueBool())) return; - pq_.push({next_weight, depth + 1, vertex, edge}); + pq_.emplace(next_weight, depth + 1, vertex, edge); }; // Populates the priority queue structure with expansions @@ -1810,7 +1813,7 @@ class ExpandWeightedShortestPathCursor : public query::plan::Cursor { total_cost_.clear(); yielded_vertices_.clear(); - pq_.push({TypedValue(), 0, vertex, std::nullopt}); + pq_.emplace(TypedValue(), 0, vertex, std::nullopt); // We are adding the starting vertex to the set of yielded vertices // because we don't want to yield paths that end with the starting // vertex. @@ -2023,7 +2026,7 @@ class ExpandAllShortestPathsCursor : public query::plan::Cursor { } DirectedEdge directed_edge = {edge, direction, next_weight}; - pq_.push({next_weight, depth + 1, next_vertex, directed_edge}); + pq_.emplace(next_weight, depth + 1, next_vertex, directed_edge); }; // Populates the priority queue structure with expansions @@ -2314,8 +2317,8 @@ UniqueCursorPtr ExpandVariable::MakeCursor(utils::MemoryResource *mem) const { class ConstructNamedPathCursor : public Cursor { public: - ConstructNamedPathCursor(const ConstructNamedPath &self, utils::MemoryResource *mem) - : self_(self), input_cursor_(self_.input()->MakeCursor(mem)) {} + ConstructNamedPathCursor(ConstructNamedPath self, utils::MemoryResource *mem) + : self_(std::move(self)), input_cursor_(self_.input()->MakeCursor(mem)) {} bool Pull(Frame &frame, ExecutionContext &context) override { OOMExceptionEnabler oom_exception; @@ -2413,11 +2416,11 @@ Filter::Filter(const std::shared_ptr &input, Filter::Filter(const std::shared_ptr &input, const std::vector> &pattern_filters, Expression *expression, - const Filters &all_filters) + Filters all_filters) : input_(input ? input : std::make_shared()), pattern_filters_(pattern_filters), expression_(expression), - all_filters_(all_filters) {} + all_filters_(std::move(all_filters)) {} bool Filter::Accept(HierarchicalLogicalOperatorVisitor &visitor) { if (visitor.PreVisit(*this)) { @@ -2478,7 +2481,7 @@ void Filter::FilterCursor::Shutdown() { input_cursor_->Shutdown(); } void Filter::FilterCursor::Reset() { input_cursor_->Reset(); } EvaluatePatternFilter::EvaluatePatternFilter(const std::shared_ptr &input, Symbol output_symbol) - : input_(input), output_symbol_(output_symbol) {} + : input_(input), output_symbol_(std::move(output_symbol)) {} ACCEPT_WITH_INPUT(EvaluatePatternFilter); @@ -2801,7 +2804,7 @@ void SetProperty::SetPropertyCursor::Shutdown() { input_cursor_->Shutdown(); } void SetProperty::SetPropertyCursor::Reset() { input_cursor_->Reset(); } SetProperties::SetProperties(const std::shared_ptr &input, Symbol input_symbol, Expression *rhs, Op op) - : input_(input), input_symbol_(input_symbol), rhs_(rhs), op_(op) {} + : input_(input), input_symbol_(std::move(input_symbol)), rhs_(rhs), op_(op) {} ACCEPT_WITH_INPUT(SetProperties) @@ -3000,7 +3003,7 @@ void SetProperties::SetPropertiesCursor::Reset() { input_cursor_->Reset(); } SetLabels::SetLabels(const std::shared_ptr &input, Symbol input_symbol, const std::vector &labels) - : input_(input), input_symbol_(input_symbol), labels_(labels) {} + : input_(input), input_symbol_(std::move(input_symbol)), labels_(labels) {} ACCEPT_WITH_INPUT(SetLabels) @@ -3160,7 +3163,7 @@ void RemoveProperty::RemovePropertyCursor::Reset() { input_cursor_->Reset(); } RemoveLabels::RemoveLabels(const std::shared_ptr &input, Symbol input_symbol, const std::vector &labels) - : input_(input), input_symbol_(input_symbol), labels_(labels) {} + : input_(input), input_symbol_(std::move(input_symbol)), labels_(labels) {} ACCEPT_WITH_INPUT(RemoveLabels) @@ -3234,7 +3237,7 @@ void RemoveLabels::RemoveLabelsCursor::Reset() { input_cursor_->Reset(); } EdgeUniquenessFilter::EdgeUniquenessFilter(const std::shared_ptr &input, Symbol expand_symbol, const std::vector &previous_symbols) - : input_(input), expand_symbol_(expand_symbol), previous_symbols_(previous_symbols) {} + : input_(input), expand_symbol_(std::move(expand_symbol)), previous_symbols_(previous_symbols) {} ACCEPT_WITH_INPUT(EdgeUniquenessFilter) @@ -4204,7 +4207,7 @@ void Optional::OptionalCursor::Reset() { Unwind::Unwind(const std::shared_ptr &input, Expression *input_expression, Symbol output_symbol) : input_(input ? input : std::make_shared()), input_expression_(input_expression), - output_symbol_(output_symbol) {} + output_symbol_(std::move(output_symbol)) {} ACCEPT_WITH_INPUT(Unwind) @@ -4535,7 +4538,7 @@ WITHOUT_SINGLE_INPUT(OutputTable); class OutputTableCursor : public Cursor { public: - OutputTableCursor(const OutputTable &self) : self_(self) {} + explicit OutputTableCursor(const OutputTable &self) : self_(self) {} bool Pull(Frame &frame, ExecutionContext &context) override { OOMExceptionEnabler oom_exception; @@ -4626,10 +4629,10 @@ CallProcedure::CallProcedure(std::shared_ptr input, std::string std::vector fields, std::vector symbols, Expression *memory_limit, size_t memory_scale, bool is_write, int64_t procedure_id, bool void_procedure) : input_(input ? input : std::make_shared()), - procedure_name_(name), - arguments_(args), - result_fields_(fields), - result_symbols_(symbols), + procedure_name_(std::move(name)), + arguments_(std::move(args)), + result_fields_(std::move(fields)), + result_symbols_(std::move(symbols)), memory_limit_(memory_limit), memory_scale_(memory_scale), is_write_(is_write), @@ -4983,7 +4986,7 @@ LoadCsv::LoadCsv(std::shared_ptr input, Expression *file, bool delimiter_(delimiter), quote_(quote), nullif_(nullif), - row_var_(row_var) { + row_var_(std::move(row_var)) { MG_ASSERT(file_, "Something went wrong - '{}' member file_ shouldn't be a nullptr", __func__); } @@ -5197,7 +5200,7 @@ Foreach::Foreach(std::shared_ptr input, std::shared_ptr()), update_clauses_(std::move(updates)), expression_(expr), - loop_variable_symbol_(loop_variable_symbol) {} + loop_variable_symbol_(std::move(loop_variable_symbol)) {} UniqueCursorPtr Foreach::MakeCursor(utils::MemoryResource *mem) const { memgraph::metrics::IncrementCounter(memgraph::metrics::ForeachOperator); diff --git a/src/query/plan/operator.hpp b/src/query/plan/operator.hpp index 7bb971752..03df07378 100644 --- a/src/query/plan/operator.hpp +++ b/src/query/plan/operator.hpp @@ -32,9 +32,7 @@ #include "utils/synchronized.hpp" #include "utils/visitor.hpp" -namespace memgraph { - -namespace query { +namespace memgraph::query { struct ExecutionContext; class ExpressionEvaluator; @@ -68,7 +66,7 @@ class Cursor { /// Perform cleanup which may throw an exception virtual void Shutdown() = 0; - virtual ~Cursor() {} + virtual ~Cursor() = default; }; /// unique_ptr to Cursor managed with a custom deleter. @@ -172,7 +170,7 @@ class LogicalOperator : public utils::Visitable &input, const NodeCreationInfo &node_info); + CreateNode(const std::shared_ptr &input, NodeCreationInfo node_info); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; std::vector ModifiedSymbols(const SymbolTable &) const override; @@ -445,7 +443,7 @@ class CreateExpand : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - CreateExpand() {} + CreateExpand() = default; /** @brief Construct @c CreateExpand. * @@ -459,8 +457,8 @@ class CreateExpand : public memgraph::query::plan::LogicalOperator { * @param existing_node @c bool indicating whether the @c node_atom refers to * an existing node. If @c false, the operator will also create the node. */ - CreateExpand(const NodeCreationInfo &node_info, const EdgeCreationInfo &edge_info, - const std::shared_ptr &input, Symbol input_symbol, bool existing_node); + CreateExpand(NodeCreationInfo node_info, EdgeCreationInfo edge_info, const std::shared_ptr &input, + Symbol input_symbol, bool existing_node); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; std::vector ModifiedSymbols(const SymbolTable &) const override; @@ -529,7 +527,7 @@ class ScanAll : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ScanAll() {} + ScanAll() = default; ScanAll(const std::shared_ptr &input, Symbol output_symbol, storage::View view = storage::View::OLD); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; @@ -571,7 +569,7 @@ class ScanAllByLabel : public memgraph::query::plan::ScanAll { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ScanAllByLabel() {} + ScanAllByLabel() = default; ScanAllByLabel(const std::shared_ptr &input, Symbol output_symbol, storage::LabelId label, storage::View view = storage::View::OLD); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -606,7 +604,7 @@ class ScanAllByLabelPropertyRange : public memgraph::query::plan::ScanAll { /** Bound with expression which when evaluated produces the bound value. */ using Bound = utils::Bound; - ScanAllByLabelPropertyRange() {} + ScanAllByLabelPropertyRange() = default; /** * Constructs the operator for given label and property value in range * (inclusive). @@ -622,7 +620,7 @@ class ScanAllByLabelPropertyRange : public memgraph::query::plan::ScanAll { * @param view storage::View used when obtaining vertices. */ ScanAllByLabelPropertyRange(const std::shared_ptr &input, Symbol output_symbol, - storage::LabelId label, storage::PropertyId property, const std::string &property_name, + storage::LabelId label, storage::PropertyId property, std::string property_name, std::optional lower_bound, std::optional upper_bound, storage::View view = storage::View::OLD); @@ -675,7 +673,7 @@ class ScanAllByLabelPropertyValue : public memgraph::query::plan::ScanAll { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ScanAllByLabelPropertyValue() {} + ScanAllByLabelPropertyValue() = default; /** * Constructs the operator for given label and property value. * @@ -687,7 +685,7 @@ class ScanAllByLabelPropertyValue : public memgraph::query::plan::ScanAll { * @param view storage::View used when obtaining vertices. */ ScanAllByLabelPropertyValue(const std::shared_ptr &input, Symbol output_symbol, - storage::LabelId label, storage::PropertyId property, const std::string &property_name, + storage::LabelId label, storage::PropertyId property, std::string property_name, Expression *expression, storage::View view = storage::View::OLD); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -727,9 +725,9 @@ class ScanAllByLabelProperty : public memgraph::query::plan::ScanAll { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ScanAllByLabelProperty() {} + ScanAllByLabelProperty() = default; ScanAllByLabelProperty(const std::shared_ptr &input, Symbol output_symbol, storage::LabelId label, - storage::PropertyId property, const std::string &property_name, + storage::PropertyId property, std::string property_name, storage::View view = storage::View::OLD); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; @@ -763,7 +761,7 @@ class ScanAllById : public memgraph::query::plan::ScanAll { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ScanAllById() {} + ScanAllById() = default; ScanAllById(const std::shared_ptr &input, Symbol output_symbol, Expression *expression, storage::View view = storage::View::OLD); @@ -842,7 +840,7 @@ class Expand : public memgraph::query::plan::LogicalOperator { EdgeAtom::Direction direction, const std::vector &edge_types, bool existing_node, storage::View view); - Expand() {} + Expand() = default; bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; @@ -950,7 +948,7 @@ class ExpandVariable : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ExpandVariable() {} + ExpandVariable() = default; /** * Creates a variable-length expansion. Most params are forwarded @@ -1073,10 +1071,10 @@ class ConstructNamedPath : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - ConstructNamedPath() {} + ConstructNamedPath() = default; ConstructNamedPath(const std::shared_ptr &input, Symbol path_symbol, const std::vector &path_elements) - : input_(input), path_symbol_(path_symbol), path_elements_(path_elements) {} + : input_(input), path_symbol_(std::move(path_symbol)), path_elements_(path_elements) {} bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; std::vector ModifiedSymbols(const SymbolTable &) const override; @@ -1108,13 +1106,13 @@ class Filter : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Filter() {} + Filter() = default; Filter(const std::shared_ptr &input, const std::vector> &pattern_filters, Expression *expression); Filter(const std::shared_ptr &input, const std::vector> &pattern_filters, Expression *expression, - const Filters &all_filters); + Filters all_filters); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; UniqueCursorPtr MakeCursor(utils::MemoryResource *) const override; std::vector ModifiedSymbols(const SymbolTable &) const override; @@ -1126,12 +1124,12 @@ class Filter : public memgraph::query::plan::LogicalOperator { std::shared_ptr input_; std::vector> pattern_filters_; Expression *expression_; - const memgraph::query::plan::Filters all_filters_; + memgraph::query::plan::Filters all_filters_; static std::string SingleFilterName(const query::plan::FilterInfo &single_filter) { using Type = query::plan::FilterInfo::Type; if (single_filter.type == Type::Generic) { - std::set symbol_names; + std::set> symbol_names; for (const auto &symbol : single_filter.used_symbols) { symbol_names.insert(symbol.name()); } @@ -1144,7 +1142,7 @@ class Filter : public memgraph::query::plan::LogicalOperator { LOG_FATAL("Label filters not using LabelsTest are not supported for query inspection!"); } auto filter_expression = static_cast(single_filter.expression); - std::set label_names; + std::set> label_names; for (const auto &label : filter_expression->labels_) { label_names.insert(label.name); } @@ -1167,7 +1165,7 @@ class Filter : public memgraph::query::plan::LogicalOperator { } std::string ToString() const override { - std::set filter_names; + std::set> filter_names; for (const auto &filter : all_filters_) { filter_names.insert(Filter::SingleFilterName(filter)); } @@ -1214,7 +1212,7 @@ class Produce : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Produce() {} + Produce() = default; Produce(const std::shared_ptr &input, const std::vector &named_expressions); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1271,7 +1269,7 @@ class Delete : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Delete() {} + Delete() = default; Delete(const std::shared_ptr &input_, const std::vector &expressions, bool detach_); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1326,7 +1324,7 @@ class SetProperty : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - SetProperty() {} + SetProperty() = default; SetProperty(const std::shared_ptr &input, storage::PropertyId property, PropertyLookup *lhs, Expression *rhs); @@ -1385,7 +1383,7 @@ class SetProperties : public memgraph::query::plan::LogicalOperator { /// that the old properties are discarded and replaced with new ones. enum class Op { UPDATE, REPLACE }; - SetProperties() {} + SetProperties() = default; SetProperties(const std::shared_ptr &input, Symbol input_symbol, Expression *rhs, Op op); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1433,7 +1431,7 @@ class SetLabels : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - SetLabels() {} + SetLabels() = default; SetLabels(const std::shared_ptr &input, Symbol input_symbol, const std::vector &labels); @@ -1477,7 +1475,7 @@ class RemoveProperty : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - RemoveProperty() {} + RemoveProperty() = default; RemoveProperty(const std::shared_ptr &input, storage::PropertyId property, PropertyLookup *lhs); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1522,7 +1520,7 @@ class RemoveLabels : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - RemoveLabels() {} + RemoveLabels() = default; RemoveLabels(const std::shared_ptr &input, Symbol input_symbol, const std::vector &labels); @@ -1578,7 +1576,7 @@ class EdgeUniquenessFilter : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - EdgeUniquenessFilter() {} + EdgeUniquenessFilter() = default; EdgeUniquenessFilter(const std::shared_ptr &input, Symbol expand_symbol, const std::vector &previous_symbols); @@ -1636,7 +1634,7 @@ class EmptyResult : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - EmptyResult() {} + EmptyResult() = default; EmptyResult(const std::shared_ptr &input); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1688,7 +1686,7 @@ class Accumulate : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Accumulate() {} + Accumulate() = default; Accumulate(const std::shared_ptr &input, const std::vector &symbols, bool advance_command = false); @@ -1811,7 +1809,7 @@ class Skip : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Skip() {} + Skip() = default; Skip(const std::shared_ptr &input, Expression *expression); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1857,7 +1855,7 @@ class EvaluatePatternFilter : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - EvaluatePatternFilter() {} + EvaluatePatternFilter() = default; EvaluatePatternFilter(const std::shared_ptr &input, Symbol output_symbol); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1911,7 +1909,7 @@ class Limit : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Limit() {} + Limit() = default; Limit(const std::shared_ptr &input, Expression *expression); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -1966,7 +1964,7 @@ class OrderBy : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - OrderBy() {} + OrderBy() = default; OrderBy(const std::shared_ptr &input, const std::vector &order_by, const std::vector &output_symbols); @@ -2018,7 +2016,7 @@ class Merge : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Merge() {} + Merge() = default; Merge(const std::shared_ptr &input, const std::shared_ptr &merge_match, const std::shared_ptr &merge_create); @@ -2078,7 +2076,7 @@ class Optional : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Optional() {} + Optional() = default; Optional(const std::shared_ptr &input, const std::shared_ptr &optional, const std::vector &optional_symbols); @@ -2132,7 +2130,7 @@ class Unwind : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Unwind() {} + Unwind() = default; Unwind(const std::shared_ptr &input, Expression *input_expression_, Symbol output_symbol); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -2167,7 +2165,7 @@ class Distinct : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Distinct() {} + Distinct() = default; Distinct(const std::shared_ptr &input, const std::vector &value_symbols); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -2200,7 +2198,7 @@ class Union : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Union() {} + Union() = default; Union(const std::shared_ptr &left_op, const std::shared_ptr &right_op, const std::vector &union_symbols, const std::vector &left_symbols, @@ -2256,7 +2254,7 @@ class Cartesian : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Cartesian() {} + Cartesian() = default; /** Construct the operator with left input branch and right input branch. */ Cartesian(const std::shared_ptr &left_op, const std::vector &left_symbols, const std::shared_ptr &right_op, const std::vector &right_symbols) @@ -2291,7 +2289,7 @@ class OutputTable : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - OutputTable() {} + OutputTable() = default; OutputTable(std::vector output_symbols, std::function>(Frame *, ExecutionContext *)> callback); OutputTable(std::vector output_symbols, std::vector> rows); @@ -2327,7 +2325,7 @@ class OutputTableStream : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - OutputTableStream() {} + OutputTableStream() = default; OutputTableStream(std::vector output_symbols, std::function>(Frame *, ExecutionContext *)> callback); @@ -2498,7 +2496,7 @@ class Apply : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - Apply() {} + Apply() = default; Apply(const std::shared_ptr input, const std::shared_ptr subquery, bool subquery_has_return); @@ -2545,7 +2543,7 @@ class IndexedJoin : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - IndexedJoin() {} + IndexedJoin() = default; IndexedJoin(std::shared_ptr main_branch, std::shared_ptr sub_branch); bool Accept(HierarchicalLogicalOperatorVisitor &visitor) override; @@ -2588,7 +2586,7 @@ class HashJoin : public memgraph::query::plan::LogicalOperator { static const utils::TypeInfo kType; const utils::TypeInfo &GetTypeInfo() const override { return kType; } - HashJoin() {} + HashJoin() = default; /** Construct the operator with left input branch and right input branch. */ HashJoin(const std::shared_ptr &left_op, const std::vector &left_symbols, const std::shared_ptr &right_op, const std::vector &right_symbols, @@ -2631,5 +2629,4 @@ class HashJoin : public memgraph::query::plan::LogicalOperator { }; } // namespace plan -} // namespace query -} // namespace memgraph +} // namespace memgraph::query diff --git a/src/query/plan/planner.hpp b/src/query/plan/planner.hpp index 3f3d853bc..10318e6b9 100644 --- a/src/query/plan/planner.hpp +++ b/src/query/plan/planner.hpp @@ -17,6 +17,8 @@ #pragma once +#include + #include "query/plan/cost_estimator.hpp" #include "query/plan/operator.hpp" #include "query/plan/preprocess.hpp" @@ -42,11 +44,11 @@ class PostProcessor final { using ProcessedPlan = std::unique_ptr; - explicit PostProcessor(const Parameters ¶meters) : parameters_(parameters) {} + explicit PostProcessor(Parameters parameters) : parameters_(std::move(parameters)) {} template - PostProcessor(const Parameters ¶meters, std::vector index_hints, TDbAccessor *db) - : parameters_(parameters), index_hints_(IndexHints(index_hints, db)) {} + PostProcessor(Parameters parameters, std::vector index_hints, TDbAccessor *db) + : parameters_(std::move(parameters)), index_hints_(IndexHints(index_hints, db)) {} template std::unique_ptr Rewrite(std::unique_ptr plan, TPlanningContext *context) { diff --git a/src/query/plan/preprocess.cpp b/src/query/plan/preprocess.cpp index 8b1689796..e03c51841 100644 --- a/src/query/plan/preprocess.cpp +++ b/src/query/plan/preprocess.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "query/exceptions.hpp" @@ -199,7 +200,7 @@ auto SplitExpressionOnAnd(Expression *expression) { PropertyFilter::PropertyFilter(const SymbolTable &symbol_table, const Symbol &symbol, PropertyIx property, Expression *value, Type type) - : symbol_(symbol), property_(property), type_(type), value_(value) { + : symbol_(symbol), property_(std::move(property)), type_(type), value_(value) { MG_ASSERT(type != Type::RANGE); UsedSymbolsCollector collector(symbol_table); value->Accept(collector); @@ -209,7 +210,11 @@ PropertyFilter::PropertyFilter(const SymbolTable &symbol_table, const Symbol &sy PropertyFilter::PropertyFilter(const SymbolTable &symbol_table, const Symbol &symbol, PropertyIx property, const std::optional &lower_bound, const std::optional &upper_bound) - : symbol_(symbol), property_(property), type_(Type::RANGE), lower_bound_(lower_bound), upper_bound_(upper_bound) { + : symbol_(symbol), + property_(std::move(property)), + type_(Type::RANGE), + lower_bound_(lower_bound), + upper_bound_(upper_bound) { UsedSymbolsCollector collector(symbol_table); if (lower_bound) { lower_bound->value()->Accept(collector); @@ -220,8 +225,8 @@ PropertyFilter::PropertyFilter(const SymbolTable &symbol_table, const Symbol &sy is_symbol_in_value_ = utils::Contains(collector.symbols_, symbol); } -PropertyFilter::PropertyFilter(const Symbol &symbol, PropertyIx property, Type type) - : symbol_(symbol), property_(property), type_(type) { +PropertyFilter::PropertyFilter(Symbol symbol, PropertyIx property, Type type) + : symbol_(std::move(symbol)), property_(std::move(property)), type_(type) { // As this constructor is used for property filters where // we don't have to evaluate the filter expression, we set // the is_symbol_in_value_ to false, although the filter diff --git a/src/query/plan/preprocess.hpp b/src/query/plan/preprocess.hpp index e9f7aeeb9..8e1955907 100644 --- a/src/query/plan/preprocess.hpp +++ b/src/query/plan/preprocess.hpp @@ -103,29 +103,29 @@ class UsedSymbolsCollector : public HierarchicalTreeVisitor { }; // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define PREPROCESS_DEFINE_ID_TYPE(name) \ - class name final { \ - private: \ - explicit name(uint64_t id) : id_(id) {} \ - \ - public: \ - /* Default constructor to allow serialization or preallocation. */ \ - name() = default; \ - \ - static name FromUint(uint64_t id) { return name(id); } \ - static name FromInt(int64_t id) { return name(utils::MemcpyCast(id)); } \ - uint64_t AsUint() const { return id_; } \ - int64_t AsInt() const { return utils::MemcpyCast(id_); } \ - \ - private: \ - uint64_t id_; \ - }; \ - static_assert(std::is_trivially_copyable::value, "query::plan::" #name " must be trivially copyable!"); \ - inline bool operator==(const name &first, const name &second) { return first.AsUint() == second.AsUint(); } \ - inline bool operator!=(const name &first, const name &second) { return first.AsUint() != second.AsUint(); } \ - inline bool operator<(const name &first, const name &second) { return first.AsUint() < second.AsUint(); } \ - inline bool operator>(const name &first, const name &second) { return first.AsUint() > second.AsUint(); } \ - inline bool operator<=(const name &first, const name &second) { return first.AsUint() <= second.AsUint(); } \ +#define PREPROCESS_DEFINE_ID_TYPE(name) \ + class name final { \ + private: \ + explicit name(uint64_t id) : id_(id) {} \ + \ + public: \ + /* Default constructor to allow serialization or preallocation. */ \ + name() = default; \ + \ + static name FromUint(uint64_t id) { return name(id); } \ + static name FromInt(int64_t id) { return name(utils::MemcpyCast(id)); } \ + uint64_t AsUint() const { return id_; } \ + int64_t AsInt() const { return utils::MemcpyCast(id_); } \ + \ + private: \ + uint64_t id_; \ + }; \ + static_assert(std::is_trivially_copyable_v, "query::plan::" #name " must be trivially copyable!"); \ + inline bool operator==(const name &first, const name &second) { return first.AsUint() == second.AsUint(); } \ + inline bool operator!=(const name &first, const name &second) { return first.AsUint() != second.AsUint(); } \ + inline bool operator<(const name &first, const name &second) { return first.AsUint() < second.AsUint(); } \ + inline bool operator>(const name &first, const name &second) { return first.AsUint() > second.AsUint(); } \ + inline bool operator<=(const name &first, const name &second) { return first.AsUint() <= second.AsUint(); } \ inline bool operator>=(const name &first, const name &second) { return first.AsUint() >= second.AsUint(); } PREPROCESS_DEFINE_ID_TYPE(ExpansionGroupId); @@ -259,7 +259,7 @@ class PropertyFilter { /// Used for the "PROP IS NOT NULL" filter, and can be used for any /// property filter that doesn't need to use an expression to produce /// values that should be filtered further. - PropertyFilter(const Symbol &, PropertyIx, Type); + PropertyFilter(Symbol, PropertyIx, Type); /// Symbol whose property is looked up. Symbol symbol_; diff --git a/src/query/plan/profile.hpp b/src/query/plan/profile.hpp index 041a34ac9..e0d884449 100644 --- a/src/query/plan/profile.hpp +++ b/src/query/plan/profile.hpp @@ -18,9 +18,7 @@ #include "query/typed_value.hpp" -namespace memgraph::query { - -namespace plan { +namespace memgraph::query::plan { /** * Stores profiling statistics for a single logical operator. @@ -43,5 +41,4 @@ std::vector> ProfilingStatsToTable(const ProfilingStatsW nlohmann::json ProfilingStatsToJson(const ProfilingStatsWithTotalTime &stats); -} // namespace plan -} // namespace memgraph::query +} // namespace memgraph::query::plan diff --git a/src/query/plan/rewrite/index_lookup.hpp b/src/query/plan/rewrite/index_lookup.hpp index 05361cf73..4054f8c12 100644 --- a/src/query/plan/rewrite/index_lookup.hpp +++ b/src/query/plan/rewrite/index_lookup.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -84,7 +85,7 @@ template class IndexLookupRewriter final : public HierarchicalLogicalOperatorVisitor { public: IndexLookupRewriter(SymbolTable *symbol_table, AstStorage *ast_storage, TDbAccessor *db, IndexHints index_hints) - : symbol_table_(symbol_table), ast_storage_(ast_storage), db_(db), index_hints_(index_hints) {} + : symbol_table_(symbol_table), ast_storage_(ast_storage), db_(db), index_hints_(std::move(index_hints)) {} using HierarchicalLogicalOperatorVisitor::PostVisit; using HierarchicalLogicalOperatorVisitor::PreVisit; @@ -676,9 +677,9 @@ class IndexLookupRewriter final : public HierarchicalLogicalOperatorVisitor { if (!db_->LabelPropertyIndexExists(GetLabel(label), GetProperty(property))) { continue; } - candidate_indices.emplace_back(std::make_pair( + candidate_indices.emplace_back( IndexHint{.index_type_ = IndexHint::IndexType::LABEL_PROPERTY, .label_ = label, .property_ = property}, - filter)); + filter); candidate_index_lookup.insert({std::make_pair(label, property), filter}); } } diff --git a/src/query/plan/variable_start_planner.cpp b/src/query/plan/variable_start_planner.cpp index eb30226d8..1c230628a 100644 --- a/src/query/plan/variable_start_planner.cpp +++ b/src/query/plan/variable_start_planner.cpp @@ -13,6 +13,7 @@ #include #include +#include #include "utils/flag_validation.hpp" #include "utils/logging.hpp" @@ -216,7 +217,7 @@ CartesianProduct VaryMultiMatchingStarts(const std::vector variants; variants.reserve(matchings.size()); for (const auto &matching : matchings) { - variants.emplace_back(VaryMatchingStart(matching, symbol_table)); + variants.emplace_back(matching, symbol_table); } return MakeCartesianProduct(std::move(variants)); } @@ -247,8 +248,7 @@ VaryQueryPartMatching::VaryQueryPartMatching(SingleQueryPart query_part, const S merge_matchings_(VaryMultiMatchingStarts(query_part_.merge_matching, symbol_table)), filter_matchings_(VaryFilterMatchingStarts(query_part_.matching, symbol_table)) {} -VaryQueryPartMatching::iterator::iterator(const SingleQueryPart &query_part, - VaryMatchingStart::iterator matchings_begin, +VaryQueryPartMatching::iterator::iterator(SingleQueryPart query_part, VaryMatchingStart::iterator matchings_begin, VaryMatchingStart::iterator matchings_end, CartesianProduct::iterator optional_begin, CartesianProduct::iterator optional_end, @@ -256,18 +256,18 @@ VaryQueryPartMatching::iterator::iterator(const SingleQueryPart &query_part, CartesianProduct::iterator merge_end, CartesianProduct::iterator filter_begin, CartesianProduct::iterator filter_end) - : current_query_part_(query_part), - matchings_it_(matchings_begin), - matchings_end_(matchings_end), + : current_query_part_(std::move(query_part)), + matchings_it_(std::move(matchings_begin)), + matchings_end_(std::move(matchings_end)), optional_it_(optional_begin), optional_begin_(optional_begin), - optional_end_(optional_end), + optional_end_(std::move(optional_end)), merge_it_(merge_begin), merge_begin_(merge_begin), - merge_end_(merge_end), + merge_end_(std::move(merge_end)), filter_it_(filter_begin), filter_begin_(filter_begin), - filter_end_(filter_end) { + filter_end_(std::move(filter_end)) { if (matchings_it_ != matchings_end_) { // Fill the query part with the first variation of matchings SetCurrentQueryPart(); diff --git a/src/query/plan/variable_start_planner.hpp b/src/query/plan/variable_start_planner.hpp index 96fd3b78d..6bdba71f3 100644 --- a/src/query/plan/variable_start_planner.hpp +++ b/src/query/plan/variable_start_planner.hpp @@ -49,16 +49,16 @@ class CartesianProduct { using TElement = typename decltype(begin_->begin())::value_type; public: - CartesianProduct(std::vector sets) + explicit CartesianProduct(std::vector sets) : original_sets_(std::move(sets)), begin_(original_sets_.begin()), end_(original_sets_.end()) {} class iterator { public: - typedef std::input_iterator_tag iterator_category; - typedef std::vector value_type; - typedef long difference_type; - typedef const std::vector &reference; - typedef const std::vector *pointer; + using iterator_category = std::input_iterator_tag; + using value_type = std::vector; + using difference_type = long; + using reference = const std::vector &; + using pointer = const std::vector *; explicit iterator(CartesianProduct *self, bool is_done) : self_(self), is_done_(is_done) { if (is_done || self->begin_ == self->end_) { @@ -186,11 +186,11 @@ class VaryMatchingStart { class iterator { public: - typedef std::input_iterator_tag iterator_category; - typedef Matching value_type; - typedef long difference_type; - typedef const Matching &reference; - typedef const Matching *pointer; + using iterator_category = std::input_iterator_tag; + using value_type = Matching; + using difference_type = long; + using reference = const Matching &; + using pointer = const Matching *; iterator(VaryMatchingStart *, bool); @@ -240,13 +240,13 @@ class VaryQueryPartMatching { class iterator { public: - typedef std::input_iterator_tag iterator_category; - typedef SingleQueryPart value_type; - typedef long difference_type; - typedef const SingleQueryPart &reference; - typedef const SingleQueryPart *pointer; + using iterator_category = std::input_iterator_tag; + using value_type = SingleQueryPart; + using difference_type = long; + using reference = const SingleQueryPart &; + using pointer = const SingleQueryPart *; - iterator(const SingleQueryPart &, VaryMatchingStart::iterator, VaryMatchingStart::iterator, + iterator(SingleQueryPart, VaryMatchingStart::iterator, VaryMatchingStart::iterator, CartesianProduct::iterator, CartesianProduct::iterator, CartesianProduct::iterator, CartesianProduct::iterator, CartesianProduct::iterator, CartesianProduct::iterator); @@ -383,8 +383,8 @@ class VariableStartPlanner { /// @brief The result of plan generation is an iterable of roots to multiple /// generated operator trees. - using PlanResult = typename std::result_of::Plan)( - VariableStartPlanner, QueryParts &)>::type; + using PlanResult = std::result_of_t::Plan)( + VariableStartPlanner, QueryParts &)>; }; } // namespace memgraph::query::plan diff --git a/src/query/plan/vertex_count_cache.hpp b/src/query/plan/vertex_count_cache.hpp index ff19ee95a..4cfb2486b 100644 --- a/src/query/plan/vertex_count_cache.hpp +++ b/src/query/plan/vertex_count_cache.hpp @@ -27,7 +27,7 @@ namespace memgraph::query::plan { template class VertexCountCache { public: - VertexCountCache(TDbAccessor *db) : db_(db) {} + explicit VertexCountCache(TDbAccessor *db) : db_(db) {} auto NameToLabel(const std::string &name) { return db_->NameToLabel(name); } auto NameToProperty(const std::string &name) { return db_->NameToProperty(name); } @@ -88,7 +88,7 @@ class VertexCountCache { } private: - typedef std::pair LabelPropertyKey; + using LabelPropertyKey = std::pair; struct LabelPropertyHash { size_t operator()(const LabelPropertyKey &key) const { @@ -96,9 +96,8 @@ class VertexCountCache { } }; - typedef std::pair>, - std::optional>> - BoundsKey; + using BoundsKey = std::pair>, + std::optional>>; struct BoundsHash { size_t operator()(const BoundsKey &key) const { diff --git a/src/replication/include/replication/config.hpp b/src/replication/include/replication/config.hpp index ca0cd8f16..f98069955 100644 --- a/src/replication/include/replication/config.hpp +++ b/src/replication/include/replication/config.hpp @@ -34,8 +34,8 @@ struct ReplicationClientConfig { std::chrono::seconds replica_check_frequency{1}; struct SSL { - std::string key_file = ""; - std::string cert_file = ""; + std::string key_file; + std::string cert_file; friend bool operator==(const SSL &, const SSL &) = default; }; diff --git a/src/replication/include/replication/replication_server.hpp b/src/replication/include/replication/replication_server.hpp index 032312dcc..e9ca1b549 100644 --- a/src/replication/include/replication/replication_server.hpp +++ b/src/replication/include/replication/replication_server.hpp @@ -23,7 +23,7 @@ struct FrequentHeartbeatReq { static void Load(FrequentHeartbeatReq *self, memgraph::slk::Reader *reader); static void Save(const FrequentHeartbeatReq &self, memgraph::slk::Builder *builder); - FrequentHeartbeatReq() {} + FrequentHeartbeatReq() = default; }; struct FrequentHeartbeatRes { @@ -32,7 +32,7 @@ struct FrequentHeartbeatRes { static void Load(FrequentHeartbeatRes *self, memgraph::slk::Reader *reader); static void Save(const FrequentHeartbeatRes &self, memgraph::slk::Builder *builder); - FrequentHeartbeatRes() {} + FrequentHeartbeatRes() = default; explicit FrequentHeartbeatRes(bool success) : success(success) {} bool success; diff --git a/src/requests/requests.cpp b/src/requests/requests.cpp index d6c37bd61..8a871184a 100644 --- a/src/requests/requests.cpp +++ b/src/requests/requests.cpp @@ -35,7 +35,7 @@ bool RequestPostJson(const std::string &url, const nlohmann::json &data, int tim CURLcode res = CURLE_UNSUPPORTED_PROTOCOL; long response_code = 0; - struct curl_slist *headers = NULL; + struct curl_slist *headers = nullptr; std::string payload = data.dump(); std::string user_agent = fmt::format("memgraph/{}", gflags::VersionString()); diff --git a/src/rpc/client.hpp b/src/rpc/client.hpp index bd98afe89..f727391ac 100644 --- a/src/rpc/client.hpp +++ b/src/rpc/client.hpp @@ -55,7 +55,7 @@ class Client { StreamHandler(const StreamHandler &) = delete; StreamHandler &operator=(const StreamHandler &) = delete; - ~StreamHandler() {} + ~StreamHandler() = default; slk::Builder *GetBuilder() { return &req_builder_; } diff --git a/src/rpc/client_pool.hpp b/src/rpc/client_pool.hpp index 408b006a2..86123899d 100644 --- a/src/rpc/client_pool.hpp +++ b/src/rpc/client_pool.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -13,6 +13,7 @@ #include #include +#include #include "rpc/client.hpp" @@ -25,8 +26,8 @@ namespace memgraph::rpc { */ class ClientPool { public: - ClientPool(const io::network::Endpoint &endpoint, communication::ClientContext *context) - : endpoint_(endpoint), context_(context) {} + ClientPool(io::network::Endpoint endpoint, communication::ClientContext *context) + : endpoint_(std::move(endpoint)), context_(context) {} template typename TRequestResponse::Response Call(Args &&...args) { diff --git a/src/rpc/exceptions.hpp b/src/rpc/exceptions.hpp index b0eb6c329..346c53a9a 100644 --- a/src/rpc/exceptions.hpp +++ b/src/rpc/exceptions.hpp @@ -21,7 +21,7 @@ namespace memgraph::rpc { /// This exception always requires explicit handling. class RpcFailedException : public utils::BasicException { public: - RpcFailedException(std::string_view msg) : utils::BasicException(msg) {} + explicit RpcFailedException(std::string_view msg) : utils::BasicException(msg) {} SPECIALIZE_GET_EXCEPTION_NAME(RpcFailedException); }; diff --git a/src/rpc/protocol.cpp b/src/rpc/protocol.cpp index 933daaa7f..8bc77579b 100644 --- a/src/rpc/protocol.cpp +++ b/src/rpc/protocol.cpp @@ -11,6 +11,8 @@ #include "rpc/protocol.hpp" +#include + #include "rpc/messages.hpp" #include "rpc/server.hpp" #include "rpc/version.hpp" @@ -21,9 +23,9 @@ namespace memgraph::rpc { -Session::Session(Server *server, const io::network::Endpoint &endpoint, communication::InputStream *input_stream, +Session::Session(Server *server, io::network::Endpoint endpoint, communication::InputStream *input_stream, communication::OutputStream *output_stream) - : server_(server), endpoint_(endpoint), input_stream_(input_stream), output_stream_(output_stream) {} + : server_(server), endpoint_(std::move(endpoint)), input_stream_(input_stream), output_stream_(output_stream) {} void Session::Execute() { auto ret = slk::CheckStreamComplete(input_stream_->data(), input_stream_->size()); diff --git a/src/rpc/protocol.hpp b/src/rpc/protocol.hpp index f8b25664c..a1deea17c 100644 --- a/src/rpc/protocol.hpp +++ b/src/rpc/protocol.hpp @@ -48,7 +48,7 @@ class SessionException : public utils::BasicException { */ class Session { public: - Session(Server *server, const io::network::Endpoint &endpoint, communication::InputStream *input_stream, + Session(Server *server, io::network::Endpoint endpoint, communication::InputStream *input_stream, communication::OutputStream *output_stream); /** diff --git a/src/slk/serialization.hpp b/src/slk/serialization.hpp index 06628e229..9ca99527d 100644 --- a/src/slk/serialization.hpp +++ b/src/slk/serialization.hpp @@ -60,10 +60,10 @@ void Save(const std::vector &obj, Builder *builder); template void Load(std::vector *obj, Reader *reader); -template -void Save(const std::set &obj, Builder *builder); -template -void Load(std::set *obj, Reader *reader); +template +void Save(const std::set &obj, Builder *builder); +template +void Load(std::set *obj, Reader *reader); template void Save(const std::map &obj, Builder *builder); @@ -201,8 +201,8 @@ inline void Load(std::vector *obj, Reader *reader) { } } -template -inline void Save(const std::set &obj, Builder *builder) { +template +inline void Save(const std::set &obj, Builder *builder) { uint64_t size = obj.size(); Save(size, builder); for (const auto &item : obj) { @@ -210,8 +210,8 @@ inline void Save(const std::set &obj, Builder *builder) { } } -template -inline void Load(std::set *obj, Reader *reader) { +template +inline void Load(std::set *obj, Reader *reader) { uint64_t size = 0; Load(&size, reader); for (uint64_t i = 0; i < size; ++i) { @@ -273,7 +273,7 @@ inline void Load(std::unique_ptr *obj, Reader *reader) { // Prevent any loading which may potentially break class hierarchies. // Unfortunately, C++14 doesn't have (or I'm not aware of it) a trait for // checking whether some type has any derived or base classes. - static_assert(!std::is_polymorphic::value, + static_assert(!std::is_polymorphic_v, "Only non polymorphic types can be loaded generically from a " "pointer. Pass a custom load function as the 3rd argument."); bool exists = false; @@ -379,7 +379,7 @@ inline void Load(std::shared_ptr *obj, Reader *reader, std::vector::value, + static_assert(!std::is_polymorphic_v, "Only non polymorphic types can be loaded generically from a " "pointer. Pass a custom load function as the 4th argument."); bool exists = false; diff --git a/src/slk/streams.cpp b/src/slk/streams.cpp index 1346393e8..5125d635a 100644 --- a/src/slk/streams.cpp +++ b/src/slk/streams.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -12,12 +12,13 @@ #include "slk/streams.hpp" #include +#include #include "utils/logging.hpp" namespace memgraph::slk { -Builder::Builder(std::function write_func) : write_func_(write_func) {} +Builder::Builder(std::function write_func) : write_func_(std::move(write_func)) {} void Builder::Save(const uint8_t *data, uint64_t size) { size_t offset = 0; diff --git a/src/storage/v2/disk/label_property_index.cpp b/src/storage/v2/disk/label_property_index.cpp index 5e538559a..9a40f03d1 100644 --- a/src/storage/v2/disk/label_property_index.cpp +++ b/src/storage/v2/disk/label_property_index.cpp @@ -211,8 +211,7 @@ uint64_t DiskLabelPropertyIndex::ApproximateVertexCount( void DiskLabelPropertyIndex::LoadIndexInfo(const std::vector &keys) { for (const auto &label_property : keys) { std::vector label_property_split = utils::Split(label_property, ","); - index_.emplace( - std::make_pair(LabelId::FromString(label_property_split[0]), PropertyId::FromString(label_property_split[1]))); + index_.emplace(LabelId::FromString(label_property_split[0]), PropertyId::FromString(label_property_split[1])); } } diff --git a/src/storage/v2/disk/rocksdb_storage.hpp b/src/storage/v2/disk/rocksdb_storage.hpp index 0e55c2748..09200d38a 100644 --- a/src/storage/v2/disk/rocksdb_storage.hpp +++ b/src/storage/v2/disk/rocksdb_storage.hpp @@ -32,7 +32,7 @@ namespace memgraph::storage { /// Wraps RocksDB objects inside a struct. Vertex_chandle and edge_chandle are column family handles that may be /// nullptr. In that case client should take care about them. struct RocksDBStorage { - explicit RocksDBStorage() {} + explicit RocksDBStorage() = default; RocksDBStorage(const RocksDBStorage &) = delete; RocksDBStorage &operator=(const RocksDBStorage &) = delete; diff --git a/src/storage/v2/disk/unique_constraints.cpp b/src/storage/v2/disk/unique_constraints.cpp index e0ec3cf82..3c17530c2 100644 --- a/src/storage/v2/disk/unique_constraints.cpp +++ b/src/storage/v2/disk/unique_constraints.cpp @@ -344,7 +344,7 @@ void DiskUniqueConstraints::LoadUniqueConstraints(const std::vector for (int i = 1; i < key_parts.size(); i++) { properties.insert(PropertyId::FromString(key_parts[i])); } - constraints_.emplace(std::make_pair(label, properties)); + constraints_.emplace(label, properties); } } diff --git a/src/storage/v2/durability/serialization.hpp b/src/storage/v2/durability/serialization.hpp index 409293220..ca3a19e0f 100644 --- a/src/storage/v2/durability/serialization.hpp +++ b/src/storage/v2/durability/serialization.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -27,7 +27,7 @@ namespace memgraph::storage::durability { /// (e.g. file and network). class BaseEncoder { protected: - ~BaseEncoder() {} + ~BaseEncoder() = default; public: virtual void WriteMarker(Marker marker) = 0; @@ -84,7 +84,7 @@ class Encoder final : public BaseEncoder { /// (e.g. file and network). class BaseDecoder { protected: - ~BaseDecoder() {} + ~BaseDecoder() = default; public: virtual std::optional ReadMarker() = 0; diff --git a/src/storage/v2/durability/snapshot.cpp b/src/storage/v2/durability/snapshot.cpp index d4278dba9..52872222b 100644 --- a/src/storage/v2/durability/snapshot.cpp +++ b/src/storage/v2/durability/snapshot.cpp @@ -1212,7 +1212,7 @@ RecoveredSnapshot LoadSnapshotVersion15(const std::filesystem::path &path, utils spdlog::info("Recover connectivity."); recovery_info.vertex_batches.reserve(vertex_batches.size()); for (const auto batch : vertex_batches) { - recovery_info.vertex_batches.emplace_back(std::make_pair(Gid::FromUint(0), batch.count)); + recovery_info.vertex_batches.emplace_back(Gid::FromUint(0), batch.count); } std::atomic highest_edge_gid{0}; @@ -1505,7 +1505,7 @@ RecoveredSnapshot LoadSnapshot(const std::filesystem::path &path, utils::SkipLis spdlog::info("Recover connectivity."); recovery_info.vertex_batches.reserve(vertex_batches.size()); for (const auto batch : vertex_batches) { - recovery_info.vertex_batches.emplace_back(std::make_pair(Gid::FromUint(0), batch.count)); + recovery_info.vertex_batches.emplace_back(Gid::FromUint(0), batch.count); } std::atomic highest_edge_gid{0}; diff --git a/src/storage/v2/durability/wal.hpp b/src/storage/v2/durability/wal.hpp index 3f598cb99..8f6492ac7 100644 --- a/src/storage/v2/durability/wal.hpp +++ b/src/storage/v2/durability/wal.hpp @@ -108,7 +108,7 @@ struct WalDeltaData { struct { std::string label; - std::set properties; + std::set> properties; } operation_label_properties; struct { diff --git a/src/storage/v2/edge_accessor.hpp b/src/storage/v2/edge_accessor.hpp index 86912c2b6..365619149 100644 --- a/src/storage/v2/edge_accessor.hpp +++ b/src/storage/v2/edge_accessor.hpp @@ -110,7 +110,7 @@ class EdgeAccessor final { } // namespace memgraph::storage -static_assert(std::is_trivially_copyable::value, +static_assert(std::is_trivially_copyable_v, "storage::EdgeAccessor must be trivially copyable!"); namespace std { diff --git a/src/storage/v2/id_types.hpp b/src/storage/v2/id_types.hpp index 2f9577246..3f2c8aa40 100644 --- a/src/storage/v2/id_types.hpp +++ b/src/storage/v2/id_types.hpp @@ -42,7 +42,7 @@ namespace memgraph::storage { private: \ uint64_t id_; \ }; \ - static_assert(std::is_trivially_copyable::value, "storage::" #name " must be trivially copyable!"); \ + static_assert(std::is_trivially_copyable_v, "storage::" #name " must be trivially copyable!"); \ inline bool operator==(const name &first, const name &second) { return first.AsUint() == second.AsUint(); } \ inline bool operator!=(const name &first, const name &second) { return first.AsUint() != second.AsUint(); } \ inline bool operator<(const name &first, const name &second) { return first.AsUint() < second.AsUint(); } \ diff --git a/src/storage/v2/modified_edge.hpp b/src/storage/v2/modified_edge.hpp index e08ef4ce8..293c74f43 100644 --- a/src/storage/v2/modified_edge.hpp +++ b/src/storage/v2/modified_edge.hpp @@ -34,8 +34,7 @@ struct ModifiedEdgeInfo { EdgeRef edge_ref; }; -static_assert(std::is_trivially_copyable::value, - "storage::ModifiedEdgeInfo must be trivially copyable!"); +static_assert(std::is_trivially_copyable_v, "storage::ModifiedEdgeInfo must be trivially copyable!"); using ModifiedEdgesMap = std::unordered_map; diff --git a/src/storage/v2/property_store.cpp b/src/storage/v2/property_store.cpp index 65f08f4d9..530d5f5f6 100644 --- a/src/storage/v2/property_store.cpp +++ b/src/storage/v2/property_store.cpp @@ -179,7 +179,7 @@ class Writer { public: class MetadataHandle { public: - MetadataHandle() {} + MetadataHandle() = default; explicit MetadataHandle(uint8_t *value) : value_(value) {} @@ -195,7 +195,7 @@ class Writer { uint8_t *value_{nullptr}; }; - Writer() {} + Writer() = default; Writer(uint8_t *data, uint64_t size) : data_(data), size_(size) {} @@ -1311,7 +1311,7 @@ std::vector> PropertyStore: id_old_new_change.reserve(properties.size() + old_properties.size()); for (const auto &[prop_id, new_value] : properties) { if (!old_properties.contains(prop_id)) { - id_old_new_change.emplace_back(std::make_tuple(prop_id, PropertyValue(), new_value)); + id_old_new_change.emplace_back(prop_id, PropertyValue(), new_value); } } @@ -1319,7 +1319,7 @@ std::vector> PropertyStore: auto [it, inserted] = properties.emplace(old_key, old_value); if (!inserted) { auto &new_value = it->second; - id_old_new_change.emplace_back(std::make_tuple(it->first, old_value, new_value)); + id_old_new_change.emplace_back(it->first, old_value, new_value); } } diff --git a/src/storage/v2/replication/replication_client.hpp b/src/storage/v2/replication/replication_client.hpp index 817f47bcb..8cd8cb384 100644 --- a/src/storage/v2/replication/replication_client.hpp +++ b/src/storage/v2/replication/replication_client.hpp @@ -90,7 +90,7 @@ class ReplicationClient { auto GetStorageId() const -> std::string; void Start(); - void StartTransactionReplication(const uint64_t current_wal_seq_num); + void StartTransactionReplication(uint64_t current_wal_seq_num); // Replication clients can be removed at any point // so to avoid any complexity of checking if the client was removed whenever // we want to send part of transaction and to avoid adding some GC logic this diff --git a/src/storage/v2/replication/rpc.cpp b/src/storage/v2/replication/rpc.cpp index 1477aa108..b722dfebf 100644 --- a/src/storage/v2/replication/rpc.cpp +++ b/src/storage/v2/replication/rpc.cpp @@ -14,9 +14,7 @@ namespace memgraph { -namespace storage { - -namespace replication { +namespace storage::replication { void AppendDeltasReq::Save(const AppendDeltasReq &self, memgraph::slk::Builder *builder) { memgraph::slk::Save(self, builder); @@ -59,8 +57,7 @@ void TimestampRes::Save(const TimestampRes &self, memgraph::slk::Builder *builde } void TimestampRes::Load(TimestampRes *self, memgraph::slk::Reader *reader) { memgraph::slk::Load(self, reader); } -} // namespace replication -} // namespace storage +} // namespace storage::replication constexpr utils::TypeInfo storage::replication::AppendDeltasReq::kType{utils::TypeId::REP_APPEND_DELTAS_REQ, "AppendDeltasReq", nullptr}; diff --git a/src/storage/v2/replication/rpc.hpp b/src/storage/v2/replication/rpc.hpp index 1c0d425c8..9e2f0b35e 100644 --- a/src/storage/v2/replication/rpc.hpp +++ b/src/storage/v2/replication/rpc.hpp @@ -14,16 +14,13 @@ #include #include #include +#include #include "rpc/messages.hpp" #include "slk/serialization.hpp" #include "slk/streams.hpp" -namespace memgraph { - -namespace storage { - -namespace replication { +namespace memgraph::storage::replication { struct AppendDeltasReq { static const utils::TypeInfo kType; @@ -31,7 +28,7 @@ struct AppendDeltasReq { static void Load(AppendDeltasReq *self, memgraph::slk::Reader *reader); static void Save(const AppendDeltasReq &self, memgraph::slk::Builder *builder); - AppendDeltasReq() {} + AppendDeltasReq() = default; AppendDeltasReq(std::string name, uint64_t previous_commit_timestamp, uint64_t seq_num) : db_name(std::move(name)), previous_commit_timestamp(previous_commit_timestamp), seq_num(seq_num) {} @@ -46,7 +43,7 @@ struct AppendDeltasRes { static void Load(AppendDeltasRes *self, memgraph::slk::Reader *reader); static void Save(const AppendDeltasRes &self, memgraph::slk::Builder *builder); - AppendDeltasRes() {} + AppendDeltasRes() = default; AppendDeltasRes(std::string name, bool success, uint64_t current_commit_timestamp) : db_name(std::move(name)), success(success), current_commit_timestamp(current_commit_timestamp) {} @@ -63,7 +60,7 @@ struct HeartbeatReq { static void Load(HeartbeatReq *self, memgraph::slk::Reader *reader); static void Save(const HeartbeatReq &self, memgraph::slk::Builder *builder); - HeartbeatReq() {} + HeartbeatReq() = default; HeartbeatReq(std::string name, uint64_t main_commit_timestamp, std::string epoch_id) : db_name(std::move(name)), main_commit_timestamp(main_commit_timestamp), epoch_id(std::move(epoch_id)) {} @@ -78,12 +75,12 @@ struct HeartbeatRes { static void Load(HeartbeatRes *self, memgraph::slk::Reader *reader); static void Save(const HeartbeatRes &self, memgraph::slk::Builder *builder); - HeartbeatRes() {} + HeartbeatRes() = default; HeartbeatRes(std::string name, bool success, uint64_t current_commit_timestamp, std::string epoch_id) : db_name(std::move(name)), success(success), current_commit_timestamp(current_commit_timestamp), - epoch_id(epoch_id) {} + epoch_id(std::move(epoch_id)) {} std::string db_name; bool success; @@ -99,7 +96,7 @@ struct SnapshotReq { static void Load(SnapshotReq *self, memgraph::slk::Reader *reader); static void Save(const SnapshotReq &self, memgraph::slk::Builder *builder); - SnapshotReq() {} + SnapshotReq() = default; explicit SnapshotReq(std::string name) : db_name(std::move(name)) {} std::string db_name; @@ -111,7 +108,7 @@ struct SnapshotRes { static void Load(SnapshotRes *self, memgraph::slk::Reader *reader); static void Save(const SnapshotRes &self, memgraph::slk::Builder *builder); - SnapshotRes() {} + SnapshotRes() = default; SnapshotRes(std::string name, bool success, uint64_t current_commit_timestamp) : db_name(std::move(name)), success(success), current_commit_timestamp(current_commit_timestamp) {} @@ -128,7 +125,7 @@ struct WalFilesReq { static void Load(WalFilesReq *self, memgraph::slk::Reader *reader); static void Save(const WalFilesReq &self, memgraph::slk::Builder *builder); - WalFilesReq() {} + WalFilesReq() = default; explicit WalFilesReq(std::string name, uint64_t file_number) : db_name(std::move(name)), file_number(file_number) {} std::string db_name; @@ -141,7 +138,7 @@ struct WalFilesRes { static void Load(WalFilesRes *self, memgraph::slk::Reader *reader); static void Save(const WalFilesRes &self, memgraph::slk::Builder *builder); - WalFilesRes() {} + WalFilesRes() = default; WalFilesRes(std::string name, bool success, uint64_t current_commit_timestamp) : db_name(std::move(name)), success(success), current_commit_timestamp(current_commit_timestamp) {} @@ -158,7 +155,7 @@ struct CurrentWalReq { static void Load(CurrentWalReq *self, memgraph::slk::Reader *reader); static void Save(const CurrentWalReq &self, memgraph::slk::Builder *builder); - CurrentWalReq() {} + CurrentWalReq() = default; explicit CurrentWalReq(std::string name) : db_name(std::move(name)) {} std::string db_name; @@ -170,7 +167,7 @@ struct CurrentWalRes { static void Load(CurrentWalRes *self, memgraph::slk::Reader *reader); static void Save(const CurrentWalRes &self, memgraph::slk::Builder *builder); - CurrentWalRes() {} + CurrentWalRes() = default; CurrentWalRes(std::string name, bool success, uint64_t current_commit_timestamp) : db_name(std::move(name)), success(success), current_commit_timestamp(current_commit_timestamp) {} @@ -187,7 +184,7 @@ struct TimestampReq { static void Load(TimestampReq *self, memgraph::slk::Reader *reader); static void Save(const TimestampReq &self, memgraph::slk::Builder *builder); - TimestampReq() {} + TimestampReq() = default; explicit TimestampReq(std::string name) : db_name(std::move(name)) {} std::string db_name; @@ -199,7 +196,7 @@ struct TimestampRes { static void Load(TimestampRes *self, memgraph::slk::Reader *reader); static void Save(const TimestampRes &self, memgraph::slk::Builder *builder); - TimestampRes() {} + TimestampRes() = default; TimestampRes(std::string name, bool success, uint64_t current_commit_timestamp) : db_name(std::move(name)), success(success), current_commit_timestamp(current_commit_timestamp) {} @@ -209,12 +206,9 @@ struct TimestampRes { }; using TimestampRpc = rpc::RequestResponse; -} // namespace replication -} // namespace storage -} // namespace memgraph +} // namespace memgraph::storage::replication // SLK serialization declarations -#include "slk/serialization.hpp" namespace memgraph::slk { void Save(const memgraph::storage::replication::TimestampRes &self, memgraph::slk::Builder *builder); diff --git a/src/storage/v2/storage.hpp b/src/storage/v2/storage.hpp index d91846ca4..8d8b06cd6 100644 --- a/src/storage/v2/storage.hpp +++ b/src/storage/v2/storage.hpp @@ -140,7 +140,7 @@ class Storage { Accessor(Accessor &&other) noexcept; - virtual ~Accessor() {} + virtual ~Accessor() = default; virtual VertexAccessor CreateVertex() = 0; diff --git a/src/storage/v2/vertex_accessor.hpp b/src/storage/v2/vertex_accessor.hpp index 8f67bc30b..0e5972d14 100644 --- a/src/storage/v2/vertex_accessor.hpp +++ b/src/storage/v2/vertex_accessor.hpp @@ -127,7 +127,7 @@ class VertexAccessor final { bool for_deleted_{false}; }; -static_assert(std::is_trivially_copyable::value, +static_assert(std::is_trivially_copyable_v, "storage::VertexAccessor must be trivially copyable!"); struct EdgesVertexAccessorResult { diff --git a/src/telemetry/telemetry.cpp b/src/telemetry/telemetry.cpp index 714788841..1635dda99 100644 --- a/src/telemetry/telemetry.cpp +++ b/src/telemetry/telemetry.cpp @@ -12,6 +12,7 @@ #include "telemetry/telemetry.hpp" #include +#include #include @@ -36,8 +37,8 @@ Telemetry::Telemetry(std::string url, std::filesystem::path storage_directory, s bool ssl, std::filesystem::path root_directory, std::chrono::duration refresh_interval, const uint64_t send_every_n) : url_(std::move(url)), - uuid_(uuid), - machine_id_(machine_id), + uuid_(std::move(uuid)), + machine_id_(std::move(machine_id)), ssl_(ssl), send_every_n_(send_every_n), storage_(std::move(storage_directory)) { diff --git a/src/utils/cast.hpp b/src/utils/cast.hpp index bdb8facc6..f015caf94 100644 --- a/src/utils/cast.hpp +++ b/src/utils/cast.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -18,8 +18,8 @@ namespace memgraph::utils { template -constexpr typename std::underlying_type::type UnderlyingCast(T e) { - return static_cast::type>(e); +constexpr std::underlying_type_t UnderlyingCast(T e) { + return static_cast>(e); } /** @@ -36,8 +36,8 @@ template TDest MemcpyCast(TSrc src) { TDest dest; static_assert(sizeof(dest) == sizeof(src), "MemcpyCast expects source and destination to be of same size"); - static_assert(std::is_arithmetic::value, "MemcpyCast expects source is an arithmetic type"); - static_assert(std::is_arithmetic::value, "MemcypCast expects destination is an arithmetic type"); + static_assert(std::is_arithmetic_v, "MemcpyCast expects source is an arithmetic type"); + static_assert(std::is_arithmetic_v, "MemcypCast expects destination is an arithmetic type"); std::memcpy(&dest, &src, sizeof(src)); return dest; } diff --git a/src/utils/event_histogram.hpp b/src/utils/event_histogram.hpp index 3768f0ec1..02d612b60 100644 --- a/src/utils/event_histogram.hpp +++ b/src/utils/event_histogram.hpp @@ -12,6 +12,7 @@ #pragma once #include +#include #include "utils/logging.hpp" @@ -73,7 +74,9 @@ class Histogram { percentiles_ = {0, 25, 50, 75, 90, 100}; } - explicit Histogram(std::vector percentiles) : percentiles_(percentiles) { samples_.resize(kSampleLimit, 0); } + explicit Histogram(std::vector percentiles) : percentiles_(std::move(percentiles)) { + samples_.resize(kSampleLimit, 0); + } uint64_t Count() const { return count_.load(std::memory_order_relaxed); } @@ -104,7 +107,7 @@ class Histogram { percentile_yield.reserve(percentiles_.size()); for (const auto percentile : percentiles_) { - percentile_yield.emplace_back(std::make_pair(percentile, Percentile(percentile))); + percentile_yield.emplace_back(percentile, Percentile(percentile)); } return percentile_yield; diff --git a/src/utils/exceptions.hpp b/src/utils/exceptions.hpp index d9a927beb..fa49f770e 100644 --- a/src/utils/exceptions.hpp +++ b/src/utils/exceptions.hpp @@ -61,7 +61,7 @@ class BasicException : public std::exception { /** * @brief Virtual destructor to allow for subclassing. */ - virtual ~BasicException() {} + ~BasicException() override = default; /** * @brief Returns a pointer to the (constant) error description. @@ -116,7 +116,7 @@ class StacktraceException : public std::exception { /** * @brief Virtual destructor to allow for subclassing. */ - virtual ~StacktraceException() {} + ~StacktraceException() override = default; /** * @brief Returns a pointer to the (constant) error description. diff --git a/src/utils/logging.hpp b/src/utils/logging.hpp index 9b9e7705b..02389beab 100644 --- a/src/utils/logging.hpp +++ b/src/utils/logging.hpp @@ -47,17 +47,21 @@ inline void AssertFailed(const char *file_name, int line_num, const char *expr, #define GET_MESSAGE(...) \ BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), 0), "", fmt::format(__VA_ARGS__)) -#define MG_ASSERT(expr, ...) \ - if (expr) [[likely]] { \ - (void)0; \ - } else { \ - ::memgraph::logging::AssertFailed(__FILE__, __LINE__, #expr, GET_MESSAGE(__VA_ARGS__)); \ - } +#define MG_ASSERT(expr, ...) \ + do { \ + if (expr) [[likely]] { \ + (void)0; \ + } else { \ + ::memgraph::logging::AssertFailed(__FILE__, __LINE__, #expr, GET_MESSAGE(__VA_ARGS__)); \ + } \ + } while (false) #ifndef NDEBUG #define DMG_ASSERT(expr, ...) MG_ASSERT(expr, __VA_ARGS__) #else -#define DMG_ASSERT(...) +#define DMG_ASSERT(...) \ + do { \ + } while (false) #endif template @@ -75,7 +79,9 @@ void Fatal(const char *msg, const Args &...msg_args) { #ifndef NDEBUG #define DLOG_FATAL(...) LOG_FATAL(__VA_ARGS__) #else -#define DLOG_FATAL(...) +#define DLOG_FATAL(...) \ + do { \ + } while (false) #endif inline void RedirectToStderr() { spdlog::set_default_logger(spdlog::stderr_color_mt("stderr")); } diff --git a/src/utils/lru_cache.hpp b/src/utils/lru_cache.hpp index 1ab636670..f94365331 100644 --- a/src/utils/lru_cache.hpp +++ b/src/utils/lru_cache.hpp @@ -24,7 +24,7 @@ namespace memgraph::utils { template class LRUCache { public: - LRUCache(int cache_size_) : cache_size(cache_size_){}; + explicit LRUCache(int cache_size_) : cache_size(cache_size_){}; void put(const TKey &key, const TVal &val) { auto it = item_map.find(key); diff --git a/src/utils/memory.hpp b/src/utils/memory.hpp index 3bec47ec0..225a3b6a1 100644 --- a/src/utils/memory.hpp +++ b/src/utils/memory.hpp @@ -45,7 +45,7 @@ class BadAlloc final : public std::bad_alloc { std::string msg_; public: - explicit BadAlloc(const std::string &msg) : msg_(msg) {} + explicit BadAlloc(std::string msg) : msg_(std::move(msg)) {} const char *what() const noexcept override { return msg_.c_str(); } }; @@ -53,7 +53,7 @@ class BadAlloc final : public std::bad_alloc { /// Abstract class for writing custom memory management, i.e. allocators. class MemoryResource { public: - virtual ~MemoryResource() {} + virtual ~MemoryResource() = default; /// Allocate storage with a size of at least `bytes` bytes. /// diff --git a/src/utils/scheduler.hpp b/src/utils/scheduler.hpp index b97320c21..d96178598 100644 --- a/src/utils/scheduler.hpp +++ b/src/utils/scheduler.hpp @@ -28,7 +28,7 @@ namespace memgraph::utils { */ class Scheduler { public: - Scheduler() {} + Scheduler() = default; /** * @param pause - Duration between two function executions. If function is * still running when it should be ran again, it will run right after it diff --git a/src/utils/skip_list.hpp b/src/utils/skip_list.hpp index e2079b5be..de4892375 100644 --- a/src/utils/skip_list.hpp +++ b/src/utils/skip_list.hpp @@ -1091,8 +1091,8 @@ class SkipList final : detail::SkipListNode_base { if (lower) { layer_found = find_node(lower->value(), preds, succs); } else { - for (int i = 0; i < kSkipListMaxHeight; ++i) { - preds[i] = head_; + for (auto &pred : preds) { + pred = head_; } layer_found = kSkipListMaxHeight - 1; } diff --git a/src/utils/small_vector.hpp b/src/utils/small_vector.hpp index 8654c1849..d6d7a8dd2 100644 --- a/src/utils/small_vector.hpp +++ b/src/utils/small_vector.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -105,12 +105,12 @@ class SmallVectorTemplateCommon : public SmallVectorBase { // don't want it to be automatically run, so we need to represent the space as // something else. Use an array of char of sufficient alignment. ////////////typedef utils::AlignedCharArrayUnion U; - typedef typename std::aligned_union<1, T>::type U; + using U = typename std::aligned_union<1, T>::type; U first_el_; // Space after 'first_el' is clobbered, do not add any instance vars after it. protected: - SmallVectorTemplateCommon(size_t size) : SmallVectorBase(&first_el_, size) {} + explicit SmallVectorTemplateCommon(size_t size) : SmallVectorBase(&first_el_, size) {} void GrowPod(size_t min_size_in_bytes, size_t t_size) { SmallVectorBase::GrowPod(&first_el_, min_size_in_bytes, t_size); @@ -126,19 +126,19 @@ class SmallVectorTemplateCommon : public SmallVectorBase { void SetEnd(T *P) { this->end_x_ = P; } public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T value_type; - typedef T *iterator; - typedef const T *const_iterator; + using size_type = size_t; + using difference_type = ptrdiff_t; + using value_type = T; + using iterator = T *; + using const_iterator = const T *; - typedef std::reverse_iterator const_reverse_iterator; - typedef std::reverse_iterator reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + using reverse_iterator = std::reverse_iterator; - typedef T &reference; - typedef const T &const_reference; - typedef T *pointer; - typedef const T *const_pointer; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; // forward iterator creation methods. inline iterator begin() { return (iterator)this->begin_x_; } @@ -201,7 +201,7 @@ class SmallVectorTemplateCommon : public SmallVectorBase { template class SmallVectorTemplateBase : public SmallVectorTemplateCommon { protected: - SmallVectorTemplateBase(size_t size) : SmallVectorTemplateCommon(size) {} + explicit SmallVectorTemplateBase(size_t size) : SmallVectorTemplateCommon(size) {} static void DestroyRange(T *s, T *e) { while (s != e) { @@ -277,7 +277,7 @@ void SmallVectorTemplateBase::Grow(size_t min_size) { template class SmallVectorTemplateBase : public SmallVectorTemplateCommon { protected: - SmallVectorTemplateBase(size_t size) : SmallVectorTemplateCommon(size) {} + explicit SmallVectorTemplateBase(size_t size) : SmallVectorTemplateCommon(size) {} // No need to do a destroy loop for POD's. static void DestroyRange(T *, T *) {} @@ -331,14 +331,14 @@ inline constexpr bool is_pod = std::is_standard_layout_v &&std::is_trivial_v< /// reduce code duplication based on the SmallVector 'n' template parameter. template class SmallVectorImpl : public SmallVectorTemplateBase> { - typedef SmallVectorTemplateBase> SuperClass; + using SuperClass = SmallVectorTemplateBase>; SmallVectorImpl(const SmallVectorImpl &) = delete; public: - typedef typename SuperClass::iterator iterator; - typedef typename SuperClass::const_iterator const_iterator; - typedef typename SuperClass::size_type size_type; + using iterator = typename SuperClass::iterator; + using const_iterator = typename SuperClass::const_iterator; + using size_type = typename SuperClass::size_type; protected: // Default ctor - Initialize to empty. @@ -861,7 +861,7 @@ class SmallVector : public SmallVectorImpl { return *this; } - SmallVector(SmallVectorImpl &&rhs) : SmallVectorImpl(N) { + explicit SmallVector(SmallVectorImpl &&rhs) : SmallVectorImpl(N) { if (!rhs.empty()) SmallVectorImpl::operator=(::std::move(rhs)); } diff --git a/src/utils/stacktrace.hpp b/src/utils/stacktrace.hpp index a2aa5a6c3..f06152e7d 100644 --- a/src/utils/stacktrace.hpp +++ b/src/utils/stacktrace.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -15,6 +15,7 @@ #include #include #include +#include #include "utils/on_scope_exit.hpp" @@ -25,10 +26,10 @@ class Stacktrace { class Line { public: // cppcheck-suppress noExplicitConstructor - Line(const std::string &original) : original(original) {} + explicit Line(std::string original) : original(std::move(original)) {} - Line(const std::string &original, const std::string &function, const std::string &location) - : original(original), function(function), location(location) {} + Line(std::string original, std::string function, std::string location) + : original(std::move(original)), function(std::move(function)), location(std::move(location)) {} std::string original, function, location; }; @@ -84,7 +85,7 @@ class Stacktrace { auto begin = line.find('('); auto end = line.find('+'); - if (begin == std::string::npos || end == std::string::npos) return {original}; + if (begin == std::string::npos || end == std::string::npos) return Line{original}; line[end] = '\0'; diff --git a/src/utils/variant_helpers.hpp b/src/utils/variant_helpers.hpp index 6a58deafb..b7751fe3e 100644 --- a/src/utils/variant_helpers.hpp +++ b/src/utils/variant_helpers.hpp @@ -26,7 +26,7 @@ Overloaded(Ts...) -> Overloaded; template struct ChainedOverloaded : Ts... { template - ChainedOverloaded(Us &&...ts) : Ts(std::forward(ts))... {} + explicit ChainedOverloaded(Us &&...ts) : Ts(std::forward(ts))... {} template auto operator()(Args &&...args) { diff --git a/tests/benchmark/query/profile.cpp b/tests/benchmark/query/profile.cpp index cfa346fbf..1c28fd21c 100644 --- a/tests/benchmark/query/profile.cpp +++ b/tests/benchmark/query/profile.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -233,9 +233,9 @@ struct ScopedProfile { stats = nullptr; // Was this logical operator already hit on one of the previous pulls? - for (size_t i = 0; i < root->children.size(); ++i) { - if (root->children[i].key == key) { - stats = &root->children[i]; + for (auto &child : root->children) { + if (child.key == key) { + stats = &child; break; } } @@ -345,9 +345,9 @@ struct ScopedProfile { stats = nullptr; // Was this logical operator already hit on one of the previous pulls? - for (size_t i = 0; i < root->children.size(); ++i) { - if (root->children[i].key == key) { - stats = &root->children[i]; + for (auto &child : root->children) { + if (child.key == key) { + stats = &child; break; } } diff --git a/tests/benchmark/rpc.cpp b/tests/benchmark/rpc.cpp index 3dace0531..0bb1da4d3 100644 --- a/tests/benchmark/rpc.cpp +++ b/tests/benchmark/rpc.cpp @@ -11,6 +11,7 @@ #include #include +#include #include @@ -24,8 +25,8 @@ struct EchoMessage { static const memgraph::utils::TypeInfo kType; - EchoMessage() {} // Needed for serialization. - explicit EchoMessage(const std::string &data) : data(data) {} + EchoMessage() = default; // Needed for serialization. + explicit EchoMessage(std::string data) : data(std::move(data)) {} static void Load(EchoMessage *obj, memgraph::slk::Reader *reader); static void Save(const EchoMessage &obj, memgraph::slk::Builder *builder); diff --git a/tests/e2e/isolation_levels/isolation_levels.cpp b/tests/e2e/isolation_levels/isolation_levels.cpp index 15151b106..2ead05750 100644 --- a/tests/e2e/isolation_levels/isolation_levels.cpp +++ b/tests/e2e/isolation_levels/isolation_levels.cpp @@ -91,7 +91,7 @@ void SwitchToSameDB(std::unique_ptr &main, std::unique_ptrFetchAll(); MG_ASSERT(dbs, "Failed to show databases"); for (const auto &elem : *dbs) { - MG_ASSERT(elem.size(), "Show databases wrong output"); + MG_ASSERT(!elem.empty(), "Show databases wrong output"); const auto &active = elem[1].ValueString(); if (active == "*") { const auto &name = elem[0].ValueString(); diff --git a/tests/e2e/memory/memory_limit_global_alloc_proc.cpp b/tests/e2e/memory/memory_limit_global_alloc_proc.cpp index e1f530123..34aeae509 100644 --- a/tests/e2e/memory/memory_limit_global_alloc_proc.cpp +++ b/tests/e2e/memory/memory_limit_global_alloc_proc.cpp @@ -57,6 +57,6 @@ int main(int argc, char **argv) { MG_ASSERT(client->Execute("CALL libglobal_memory_limit_proc.success() YIELD *")); auto result2 = client->FetchAll(); - MG_ASSERT(result2 != std::nullopt && result2->size() > 0); + MG_ASSERT(result2 != std::nullopt && !result2->empty()); return 0; } diff --git a/tests/e2e/memory/memory_limit_global_multi_thread_proc_create.cpp b/tests/e2e/memory/memory_limit_global_multi_thread_proc_create.cpp index 2132fbb16..e44c91ea7 100644 --- a/tests/e2e/memory/memory_limit_global_multi_thread_proc_create.cpp +++ b/tests/e2e/memory/memory_limit_global_multi_thread_proc_create.cpp @@ -54,7 +54,7 @@ int main(int argc, char **argv) { auto result_rows = client->FetchAll(); if (result_rows) { auto row = *result_rows->begin(); - error = row[0].ValueBool() == false; + error = !row[0].ValueBool(); } } catch (const std::exception &e) { diff --git a/tests/e2e/memory/memory_limit_global_thread_alloc_proc.cpp b/tests/e2e/memory/memory_limit_global_thread_alloc_proc.cpp index 0c2eb1ee6..e9892ac82 100644 --- a/tests/e2e/memory/memory_limit_global_thread_alloc_proc.cpp +++ b/tests/e2e/memory/memory_limit_global_thread_alloc_proc.cpp @@ -55,7 +55,7 @@ int main(int argc, char **argv) { auto result_rows = client->FetchAll(); if (result_rows) { auto row = *result_rows->begin(); - error = row[0].ValueBool() == false; + error = !row[0].ValueBool(); } } catch (const std::exception &e) { diff --git a/tests/e2e/memory/procedure_memory_limit.cpp b/tests/e2e/memory/procedure_memory_limit.cpp index 89a91a9ce..07fbd17b2 100644 --- a/tests/e2e/memory/procedure_memory_limit.cpp +++ b/tests/e2e/memory/procedure_memory_limit.cpp @@ -53,7 +53,7 @@ int main(int argc, char **argv) { auto result_rows = client->FetchAll(); if (result_rows) { auto row = *result_rows->begin(); - error = row[0].ValueBool() == false; + error = !row[0].ValueBool(); } } catch (const std::exception &e) { diff --git a/tests/e2e/memory/query_memory_limit_proc.cpp b/tests/e2e/memory/query_memory_limit_proc.cpp index 39baf4d8e..38509a766 100644 --- a/tests/e2e/memory/query_memory_limit_proc.cpp +++ b/tests/e2e/memory/query_memory_limit_proc.cpp @@ -53,7 +53,7 @@ int main(int argc, char **argv) { auto result_rows = client->FetchAll(); if (result_rows) { auto row = *result_rows->begin(); - error = row[0].ValueBool() == false; + error = !row[0].ValueBool(); } } catch (const std::exception &e) { diff --git a/tests/e2e/memory/query_memory_limit_proc_multi_thread.cpp b/tests/e2e/memory/query_memory_limit_proc_multi_thread.cpp index 5a5ec94f0..5acac5404 100644 --- a/tests/e2e/memory/query_memory_limit_proc_multi_thread.cpp +++ b/tests/e2e/memory/query_memory_limit_proc_multi_thread.cpp @@ -53,7 +53,7 @@ int main(int argc, char **argv) { auto result_rows = client->FetchAll(); if (result_rows) { auto row = *result_rows->begin(); - error = row[0].ValueBool() == false; + error = !row[0].ValueBool(); } } catch (const std::exception &e) { diff --git a/tests/e2e/replication/common.hpp b/tests/e2e/replication/common.hpp index f3cff293e..f5113ac37 100644 --- a/tests/e2e/replication/common.hpp +++ b/tests/e2e/replication/common.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -39,7 +39,7 @@ auto ParseDatabaseEndpoints(const std::string &database_endpoints_str) { for (const auto &db_endpoint_str : db_endpoints_strs) { const auto maybe_host_port = memgraph::io::network::Endpoint::ParseSocketOrIpAddress(db_endpoint_str, 7687); MG_ASSERT(maybe_host_port); - database_endpoints.emplace_back(memgraph::io::network::Endpoint(maybe_host_port->first, maybe_host_port->second)); + database_endpoints.emplace_back(maybe_host_port->first, maybe_host_port->second); } return database_endpoints; } diff --git a/tests/e2e/replication/constraints.cpp b/tests/e2e/replication/constraints.cpp index f56e97946..01c1217f2 100644 --- a/tests/e2e/replication/constraints.cpp +++ b/tests/e2e/replication/constraints.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -132,7 +132,7 @@ int main(int argc, char **argv) { auto client = mg::e2e::replication::Connect(database_endpoint); client->Execute("SHOW CONSTRAINT INFO;"); if (const auto data = client->FetchAll()) { - if ((*data).size() != 0) { + if (!(*data).empty()) { LOG_FATAL("{} still have some constraints.", database_endpoint); } } else { diff --git a/tests/e2e/replication/read_write_benchmark.cpp b/tests/e2e/replication/read_write_benchmark.cpp index df1c4fb90..243aab2a8 100644 --- a/tests/e2e/replication/read_write_benchmark.cpp +++ b/tests/e2e/replication/read_write_benchmark.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -138,7 +138,7 @@ int main(int argc, char **argv) { auto client = mg::e2e::replication::Connect(database_endpoint); client->Execute("SHOW INDEX INFO;"); if (const auto data = client->FetchAll()) { - if ((*data).size() != 0) { + if (!(*data).empty()) { LOG_FATAL("{} still have some indexes.", database_endpoint); } } else { diff --git a/tests/e2e/triggers/common.hpp b/tests/e2e/triggers/common.hpp index fbffd19f3..74593c1b9 100644 --- a/tests/e2e/triggers/common.hpp +++ b/tests/e2e/triggers/common.hpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -22,7 +22,7 @@ inline constexpr std::string_view kVertexLabel{"VERTEX"}; inline constexpr std::string_view kEdgeLabel{"EDGE"}; std::unique_ptr Connect(); -std::unique_ptr ConnectWithUser(const std::string_view username); +std::unique_ptr ConnectWithUser(std::string_view username); void CreateVertex(mg::Client &client, int vertex_id); void CreateEdge(mg::Client &client, int from_vertex, int to_vertex, int edge_id); diff --git a/tests/manual/antlr_tree_pretty_print.cpp b/tests/manual/antlr_tree_pretty_print.cpp index 0ba057f34..8957fc7e7 100644 --- a/tests/manual/antlr_tree_pretty_print.cpp +++ b/tests/manual/antlr_tree_pretty_print.cpp @@ -1,4 +1,4 @@ -// Copyright 2021 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -40,7 +40,7 @@ int main(int, const char **) { CommonTokenStream tokens(&lexer); tokens.fill(); - for (auto token : tokens.getTokens()) { + for (auto *token : tokens.getTokens()) { std::cout << token->toString() << std::endl; } diff --git a/tests/stress/long_running.cpp b/tests/stress/long_running.cpp index edf4b8452..37ed562ce 100644 --- a/tests/stress/long_running.cpp +++ b/tests/stress/long_running.cpp @@ -86,7 +86,7 @@ class GraphSession { std::set edges_; std::string indexed_label_; - std::set labels_; + std::set> labels_; std::map> labels_vertices_; @@ -109,7 +109,7 @@ class GraphSession { return *it; } - std::string RandomElement(std::set &data) { + std::string RandomElement(std::set> &data) { uint64_t pos = std::floor(GetRandom() * data.size()); auto it = data.begin(); std::advance(it, pos); diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index b7a90f22d..956cba781 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -6,7 +6,8 @@ find_package(Threads REQUIRED) add_custom_target(memgraph__unit) -set(memgraph_unit_main main.cpp) +add_library(memgraph_unit_main OBJECT main.cpp) +target_link_libraries(memgraph_unit_main mg-memory mg-utils gtest gmock Threads::Threads dl) function(add_unit_test test_cpp) _add_unit_test(${test_cpp} FALSE ${ARGN}) @@ -25,19 +26,19 @@ function(_add_unit_test test_cpp custom_main) ${test_cpp} ${ARGN}) - if(NOT ${custom_main}) - set(source_files - ${source_files} - ${memgraph_unit_main}) - endif() - add_executable(${target_name} ${source_files}) + if(NOT ${custom_main}) + target_link_libraries(${target_name} memgraph_unit_main) + else() + target_link_libraries(${target_name} gtest gmock Threads::Threads dl) + endif() + # OUTPUT_NAME sets the real name of a target when it is built and can be # used to help create two targets of the same name even though CMake # requires unique logical target names set_target_properties(${target_name} PROPERTIES OUTPUT_NAME ${exec_name}) - target_link_libraries(${target_name} mg-memory mg-utils gtest gmock Threads::Threads dl) + # register test if(TEST_COVERAGE) diff --git a/tests/unit/auth.cpp b/tests/unit/auth.cpp index 86a794480..6dbe20914 100644 --- a/tests/unit/auth.cpp +++ b/tests/unit/auth.cpp @@ -32,7 +32,7 @@ DECLARE_string(password_encryption_algorithm); class AuthWithStorage : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { memgraph::utils::EnsureDir(test_folder_); FLAGS_auth_password_permit_null = true; FLAGS_auth_password_strength_regex = ".+"; @@ -40,7 +40,7 @@ class AuthWithStorage : public ::testing::Test { memgraph::license::global_license_checker.EnableTesting(); } - virtual void TearDown() { fs::remove_all(test_folder_); } + void TearDown() override { fs::remove_all(test_folder_); } fs::path test_folder_{fs::temp_directory_path() / "MG_tests_unit_auth"}; @@ -58,7 +58,7 @@ TEST_F(AuthWithStorage, RemoveRole) { ASSERT_TRUE(auth.RemoveRole("admin")); class AuthWithStorage : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { memgraph::utils::EnsureDir(test_folder_); FLAGS_auth_password_permit_null = true; FLAGS_auth_password_strength_regex = ".+"; @@ -66,7 +66,7 @@ TEST_F(AuthWithStorage, RemoveRole) { memgraph::license::global_license_checker.EnableTesting(); } - virtual void TearDown() { fs::remove_all(test_folder_); } + void TearDown() override { fs::remove_all(test_folder_); } fs::path test_folder_{fs::temp_directory_path() / "MG_tests_unit_auth"}; @@ -589,9 +589,9 @@ TEST(AuthWithoutStorage, FineGrainedAccessPermissions) { } TEST_F(AuthWithStorage, FineGrainedAccessCheckerMerge) { - auto any_label = "AnyString"; - auto check_label = "Label"; - auto asterisk = "*"; + const auto *any_label = "AnyString"; + const auto *check_label = "Label"; + const auto *asterisk = "*"; { FineGrainedAccessPermissions fga_permissions1, fga_permissions2; @@ -929,7 +929,7 @@ TEST(AuthWithoutStorage, Crypto) { class AuthWithVariousEncryptionAlgorithms : public ::testing::Test { protected: - virtual void SetUp() { FLAGS_password_encryption_algorithm = "bcrypt"; } + void SetUp() override { FLAGS_password_encryption_algorithm = "bcrypt"; } }; TEST_F(AuthWithVariousEncryptionAlgorithms, VerifyPasswordDefault) { @@ -964,7 +964,7 @@ TEST_F(AuthWithVariousEncryptionAlgorithms, VerifyPasswordEmptyEncryptionThrow) class AuthWithStorageWithVariousEncryptionAlgorithms : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { memgraph::utils::EnsureDir(test_folder_); FLAGS_auth_password_permit_null = true; FLAGS_auth_password_strength_regex = ".+"; @@ -973,7 +973,7 @@ class AuthWithStorageWithVariousEncryptionAlgorithms : public ::testing::Test { memgraph::license::global_license_checker.EnableTesting(); } - virtual void TearDown() { fs::remove_all(test_folder_); } + void TearDown() override { fs::remove_all(test_folder_); } fs::path test_folder_{fs::temp_directory_path() / "MG_tests_unit_auth"}; diff --git a/tests/unit/auth_handler.cpp b/tests/unit/auth_handler.cpp index e3352220f..6537575fd 100644 --- a/tests/unit/auth_handler.cpp +++ b/tests/unit/auth_handler.cpp @@ -36,12 +36,12 @@ class AuthQueryHandlerFixture : public testing::Test { #ifdef MG_ENTERPRISE memgraph::auth::FineGrainedAccessHandler handler{}; #endif - virtual void SetUp() { + void SetUp() override { memgraph::utils::EnsureDir(test_folder_); memgraph::license::global_license_checker.EnableTesting(); } - virtual void TearDown() { + void TearDown() override { std::filesystem::remove_all(test_folder_); perms = memgraph::auth::Permissions{}; #ifdef MG_ENTERPRISE diff --git a/tests/unit/bfs_common.hpp b/tests/unit/bfs_common.hpp index 3b16e4141..9bed67971 100644 --- a/tests/unit/bfs_common.hpp +++ b/tests/unit/bfs_common.hpp @@ -288,7 +288,7 @@ class Database { virtual std::pair, std::vector> BuildGraph(memgraph::query::DbAccessor *dba, const std::vector &vertex_locations, const std::vector> &edges) = 0; - virtual ~Database() {} + virtual ~Database() = default; void BfsTest(Database *db, int lower_bound, int upper_bound, memgraph::query::EdgeAtom::Direction direction, std::vector edge_types, bool known_sink, FilterLambdaType filter_lambda_type) { diff --git a/tests/unit/bolt_chunked_encoder_buffer.cpp b/tests/unit/bolt_chunked_encoder_buffer.cpp index 8dd23a0ff..47238b403 100644 --- a/tests/unit/bolt_chunked_encoder_buffer.cpp +++ b/tests/unit/bolt_chunked_encoder_buffer.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -87,7 +87,7 @@ TEST_F(BoltChunkedEncoderBuffer, TwoSmallChunks) { // the output array should look like this: // [0, 100, first 100 bytes of test data] + // [0, 100, second 100 bytes of test data] - auto data = output_stream.output.data(); + auto *data = output_stream.output.data(); VerifyChunkOfTestData(data, size1); VerifyChunkOfTestData(data + kChunkHeaderSize + size1, size2, size1); } @@ -105,7 +105,7 @@ TEST_F(BoltChunkedEncoderBuffer, OneAndAHalfOfMaxChunk) { // the output array should look like this: // [0xFF, 0xFF, first 65535 bytes of test data, // 0x86, 0xA1, 34465 bytes of test data after the first 65535 bytes] - auto output = output_stream.output.data(); + auto *output = output_stream.output.data(); VerifyChunkOfTestData(output, kChunkMaxDataSize); VerifyChunkOfTestData(output + kChunkWholeSize, kTestDataSize - kChunkMaxDataSize, kChunkMaxDataSize); } diff --git a/tests/unit/cpp_api.cpp b/tests/unit/cpp_api.cpp index ecad43487..929a70431 100644 --- a/tests/unit/cpp_api.cpp +++ b/tests/unit/cpp_api.cpp @@ -27,7 +27,7 @@ template struct CppApiTestFixture : public ::testing::Test { protected: - virtual void SetUp() override { mgp::mrd.Register(&memory); } + void SetUp() override { mgp::mrd.Register(&memory); } void TearDown() override { if (std::is_same::value) { diff --git a/tests/unit/cypher_main_visitor.cpp b/tests/unit/cypher_main_visitor.cpp index 1d7f236a2..54453de09 100644 --- a/tests/unit/cypher_main_visitor.cpp +++ b/tests/unit/cypher_main_visitor.cpp @@ -58,7 +58,7 @@ class Base { ParsingContext context_; Parameters parameters_; - virtual ~Base() {} + virtual ~Base() = default; virtual Query *ParseQuery(const std::string &query_string) = 0; @@ -199,8 +199,8 @@ class CachedAstGenerator : public Base { class MockModule : public procedure::Module { public: - MockModule(){}; - ~MockModule() override{}; + MockModule() = default; + ~MockModule() override = default; MockModule(const MockModule &) = delete; MockModule(MockModule &&) = delete; MockModule &operator=(const MockModule &) = delete; diff --git a/tests/unit/integrations_kafka_consumer.cpp b/tests/unit/integrations_kafka_consumer.cpp index 63a419552..3d5feb80b 100644 --- a/tests/unit/integrations_kafka_consumer.cpp +++ b/tests/unit/integrations_kafka_consumer.cpp @@ -48,7 +48,7 @@ inline constexpr int64_t kDefaultBatchSize{1000}; } // namespace struct ConsumerTest : public ::testing::Test { - ConsumerTest() {} + ConsumerTest() = default; ConsumerInfo CreateDefaultConsumerInfo() const { const auto test_name = std::string{::testing::UnitTest::GetInstance()->current_test_info()->name()}; @@ -132,7 +132,7 @@ TEST_F(ConsumerTest, BatchInterval) { info.batch_interval = kBatchInterval; auto expected_messages_received = true; auto consumer_function = [&](const std::vector &messages) mutable { - received_timestamps.push_back({messages.size(), std::chrono::steady_clock::now()}); + received_timestamps.emplace_back(messages.size(), std::chrono::steady_clock::now()); for (const auto &message : messages) { expected_messages_received &= (kMessage == std::string_view(message.Payload().data(), message.Payload().size())); } @@ -227,7 +227,7 @@ TEST_F(ConsumerTest, BatchSize) { static constexpr std::string_view kMessage = "BatchSizeTestMessage"; auto expected_messages_received = true; auto consumer_function = [&](const std::vector &messages) mutable { - received_timestamps.push_back({messages.size(), std::chrono::steady_clock::now()}); + received_timestamps.emplace_back(messages.size(), std::chrono::steady_clock::now()); for (const auto &message : messages) { expected_messages_received &= (kMessage == std::string_view(message.Payload().data(), message.Payload().size())); } diff --git a/tests/unit/interpreter.cpp b/tests/unit/interpreter.cpp index 5eb7cd539..57bb79db8 100644 --- a/tests/unit/interpreter.cpp +++ b/tests/unit/interpreter.cpp @@ -64,7 +64,7 @@ class InterpreterTest : public ::testing::Test { const std::string testSuiteCsv = "interpreter_csv"; std::filesystem::path data_directory = std::filesystem::temp_directory_path() / "MG_tests_unit_interpreter"; - InterpreterTest() {} + InterpreterTest() = default; memgraph::storage::Config config{ [&]() { @@ -334,7 +334,7 @@ TYPED_TEST(InterpreterTest, Bfs) { auto kNumUnreachableNodes = 1000; auto kNumUnreachableEdges = 100000; auto kResCoeff = 5; - const auto kReachable = "reachable"; + const auto *const kReachable = "reachable"; const auto kId = "id"; if (std::is_same::value) { diff --git a/tests/unit/kvstore.cpp b/tests/unit/kvstore.cpp index 8af05e482..48ab7dc82 100644 --- a/tests/unit/kvstore.cpp +++ b/tests/unit/kvstore.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -20,9 +20,9 @@ namespace fs = std::filesystem; class KVStore : public ::testing::Test { protected: - virtual void SetUp() { memgraph::utils::EnsureDir(test_folder_); } + void SetUp() override { memgraph::utils::EnsureDir(test_folder_); } - virtual void TearDown() { fs::remove_all(test_folder_); } + void TearDown() override { fs::remove_all(test_folder_); } fs::path test_folder_{fs::temp_directory_path() / ("unit_kvstore_test_" + std::to_string(static_cast(getpid())))}; diff --git a/tests/unit/mgp_kafka_c_api.cpp b/tests/unit/mgp_kafka_c_api.cpp index 91218dc75..828d52163 100644 --- a/tests/unit/mgp_kafka_c_api.cpp +++ b/tests/unit/mgp_kafka_c_api.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -113,7 +113,7 @@ class MgpApiTest : public ::testing::Test { using KafkaMessage = MockedRdKafkaMessage; MgpApiTest() { messages_.emplace(CreateMockedBatch()); } - ~MgpApiTest() { messages_.reset(); } + ~MgpApiTest() override { messages_.reset(); } mgp_messages &Messages() { return *messages_; } diff --git a/tests/unit/plan_pretty_print.cpp b/tests/unit/plan_pretty_print.cpp index 94b7342f9..97f1355cb 100644 --- a/tests/unit/plan_pretty_print.cpp +++ b/tests/unit/plan_pretty_print.cpp @@ -46,7 +46,7 @@ class PrintToJsonTest : public ::testing::Test { dba_storage(db->Access()), dba(dba_storage.get()) {} - ~PrintToJsonTest() { + ~PrintToJsonTest() override { if (std::is_same::value) { disk_test_utils::RemoveRocksDbDirs(testSuite); } diff --git a/tests/unit/query_common.hpp b/tests/unit/query_common.hpp index e06d63908..a14ef2d30 100644 --- a/tests/unit/query_common.hpp +++ b/tests/unit/query_common.hpp @@ -46,9 +46,7 @@ #include "storage/v2/id_types.hpp" #include "utils/string.hpp" -namespace memgraph::query { - -namespace test_common { +namespace memgraph::query::test_common { auto ToIntList(const TypedValue &t) { std::vector list; @@ -189,7 +187,7 @@ auto GetEdgeVariable(AstStorage &storage, const std::string &name, EdgeAtom::Typ for (const auto &type : edge_types) { types.push_back(storage.GetEdgeTypeIx(type)); } - auto r_val = storage.Create(storage.Create(name), type, dir, types); + auto *r_val = storage.Create(storage.Create(name), type, dir, types); r_val->filter_lambda_.inner_edge = flambda_inner_edge ? flambda_inner_edge : storage.Create(memgraph::utils::RandomString(20)); @@ -215,14 +213,14 @@ auto GetEdgeVariable(AstStorage &storage, const std::string &name, EdgeAtom::Typ /// Name is used to create the Identifier which is assigned to the node. auto GetNode(AstStorage &storage, const std::string &name, std::optional label = std::nullopt, const bool user_declared = true) { - auto node = storage.Create(storage.Create(name, user_declared)); + auto *node = storage.Create(storage.Create(name, user_declared)); if (label) node->labels_.emplace_back(storage.GetLabelIx(*label)); return node; } /// Create a Pattern with given atoms. auto GetPattern(AstStorage &storage, std::vector atoms) { - auto pattern = storage.Create(); + auto *pattern = storage.Create(); pattern->identifier_ = storage.Create(memgraph::utils::RandomString(20), false); pattern->atoms_.insert(pattern->atoms_.begin(), atoms.begin(), atoms.end()); return pattern; @@ -230,7 +228,7 @@ auto GetPattern(AstStorage &storage, std::vector atoms) { /// Create a Pattern with given name and atoms. auto GetPattern(AstStorage &storage, const std::string &name, std::vector atoms) { - auto pattern = storage.Create(); + auto *pattern = storage.Create(); pattern->identifier_ = storage.Create(name, true); pattern->atoms_.insert(pattern->atoms_.begin(), atoms.begin(), atoms.end()); return pattern; @@ -377,7 +375,7 @@ void FillReturnBody(AstStorage &storage, ReturnBody &body, const std::string &na /// @sa GetWith template auto GetReturn(AstStorage &storage, bool distinct, T... exprs) { - auto ret = storage.Create(); + auto *ret = storage.Create(); ret->body_.distinct = distinct; FillReturnBody(storage, ret->body_, exprs...); return ret; @@ -390,7 +388,7 @@ auto GetReturn(AstStorage &storage, bool distinct, T... exprs) { /// @sa GetReturn template auto GetWith(AstStorage &storage, bool distinct, T... exprs) { - auto with = storage.Create(); + auto *with = storage.Create(); with->body_.distinct = distinct; FillReturnBody(storage, with->body_, exprs...); return with; @@ -407,7 +405,7 @@ auto GetUnwind(AstStorage &storage, Expression *expr, NamedExpression *as) { /// Create the delete clause with given named expressions. auto GetDelete(AstStorage &storage, std::vector exprs, bool detach = false) { - auto del = storage.Create(); + auto *del = storage.Create(); del->expressions_.insert(del->expressions_.begin(), exprs.begin(), exprs.end()); del->detach_ = detach; return del; @@ -495,9 +493,7 @@ auto GetForeach(AstStorage &storage, NamedExpression *named_expr, const std::vec return storage.Create(named_expr, clauses); } -} // namespace test_common - -} // namespace memgraph::query +} // namespace memgraph::query::test_common /// All the following macros implicitly pass `storage` variable to functions. /// You need to have `AstStorage storage;` somewhere in scope to use them. diff --git a/tests/unit/query_cost_estimator.cpp b/tests/unit/query_cost_estimator.cpp index a2c7b4a48..f3d6b3864 100644 --- a/tests/unit/query_cost_estimator.cpp +++ b/tests/unit/query_cost_estimator.cpp @@ -49,7 +49,7 @@ class QueryCostEstimator : public ::testing::Test { Parameters parameters_; int symbol_count = 0; - void SetUp() { + void SetUp() override { { auto unique_acc = db->UniqueAccess(); ASSERT_FALSE(unique_acc->CreateIndex(label).HasError()); @@ -131,7 +131,7 @@ TEST_F(QueryCostEstimator, ScanAllByLabelCardinality) { TEST_F(QueryCostEstimator, ScanAllByLabelPropertyValueConstant) { AddVertices(100, 30, 20); - for (auto const_val : {Literal(12), Parameter(12)}) { + for (auto *const_val : {Literal(12), Parameter(12)}) { MakeOp(nullptr, NextSymbol(), label, property, "property", const_val); EXPECT_COST(1 * CostParam::MakeScanAllByLabelPropertyValue); } @@ -139,7 +139,7 @@ TEST_F(QueryCostEstimator, ScanAllByLabelPropertyValueConstant) { TEST_F(QueryCostEstimator, ScanAllByLabelPropertyValueConstExpr) { AddVertices(100, 30, 20); - for (auto const_val : {Literal(12), Parameter(12)}) { + for (auto *const_val : {Literal(12), Parameter(12)}) { MakeOp(nullptr, NextSymbol(), label, property, "property", // once we make expression const-folding this test case will fail storage_.Create(const_val)); @@ -149,7 +149,7 @@ TEST_F(QueryCostEstimator, ScanAllByLabelPropertyValueConstExpr) { TEST_F(QueryCostEstimator, ScanAllByLabelPropertyRangeUpperConstant) { AddVertices(100, 30, 20); - for (auto const_val : {Literal(12), Parameter(12)}) { + for (auto *const_val : {Literal(12), Parameter(12)}) { MakeOp(nullptr, NextSymbol(), label, property, "property", nullopt, InclusiveBound(const_val)); // cardinality estimation is exact for very small indexes @@ -159,7 +159,7 @@ TEST_F(QueryCostEstimator, ScanAllByLabelPropertyRangeUpperConstant) { TEST_F(QueryCostEstimator, ScanAllByLabelPropertyRangeLowerConstant) { AddVertices(100, 30, 20); - for (auto const_val : {Literal(17), Parameter(17)}) { + for (auto *const_val : {Literal(17), Parameter(17)}) { MakeOp(nullptr, NextSymbol(), label, property, "property", InclusiveBound(const_val), nullopt); // cardinality estimation is exact for very small indexes @@ -169,7 +169,7 @@ TEST_F(QueryCostEstimator, ScanAllByLabelPropertyRangeLowerConstant) { TEST_F(QueryCostEstimator, ScanAllByLabelPropertyRangeConstExpr) { AddVertices(100, 30, 20); - for (auto const_val : {Literal(12), Parameter(12)}) { + for (auto *const_val : {Literal(12), Parameter(12)}) { auto bound = std::make_optional( memgraph::utils::MakeBoundInclusive(static_cast(storage_.Create(const_val)))); MakeOp(nullptr, NextSymbol(), label, property, "property", bound, nullopt); diff --git a/tests/unit/query_dump.cpp b/tests/unit/query_dump.cpp index f212d9189..5556ab90a 100644 --- a/tests/unit/query_dump.cpp +++ b/tests/unit/query_dump.cpp @@ -46,7 +46,7 @@ const char *kRemoveInternalLabelProperty = "MATCH (u) REMOVE u:__mg_vertex__, u. struct DatabaseState { struct Vertex { int64_t id; - std::set labels; + std::set> labels; std::map props; }; @@ -67,7 +67,7 @@ struct DatabaseState { struct LabelPropertiesItem { std::string label; - std::set properties; + std::set> properties; }; std::set vertices; @@ -139,7 +139,7 @@ DatabaseState GetState(memgraph::storage::Storage *db) { std::set vertices; auto dba = db->Access(); for (const auto &vertex : dba->Vertices(memgraph::storage::View::NEW)) { - std::set labels; + std::set> labels; auto maybe_labels = vertex.Labels(memgraph::storage::View::NEW); MG_ASSERT(maybe_labels.HasValue()); for (const auto &label : *maybe_labels) { @@ -198,7 +198,7 @@ DatabaseState GetState(memgraph::storage::Storage *db) { existence_constraints.insert({dba->LabelToName(item.first), dba->PropertyToName(item.second)}); } for (const auto &item : info.unique) { - std::set properties; + std::set> properties; for (const auto &property : item.second) { properties.insert(dba->PropertyToName(property)); } diff --git a/tests/unit/query_expression_evaluator.cpp b/tests/unit/query_expression_evaluator.cpp index 86ac5d624..44d3ed301 100644 --- a/tests/unit/query_expression_evaluator.cpp +++ b/tests/unit/query_expression_evaluator.cpp @@ -69,7 +69,7 @@ class ExpressionEvaluatorTest : public ::testing::Test { storage_dba(db->Access()), dba(storage_dba.get()) {} - ~ExpressionEvaluatorTest() { + ~ExpressionEvaluatorTest() override { if (std::is_same::value) { disk_test_utils::RemoveRocksDbDirs(testSuite); } @@ -580,7 +580,7 @@ TYPED_TEST(ExpressionEvaluatorTest, VertexAndEdgeIndexing) { TYPED_TEST(ExpressionEvaluatorTest, TypedValueListIndexing) { auto list_vector = memgraph::utils::pmr::vector(this->ctx.memory); list_vector.emplace_back("string1"); - list_vector.emplace_back(TypedValue("string2")); + list_vector.emplace_back("string2"); auto *identifier = this->storage.template Create("n"); auto node_symbol = this->symbol_table.CreateSymbol("n", true); @@ -1196,7 +1196,7 @@ class ExpressionEvaluatorPropertyLookup : public ExpressionEvaluatorTeststorage.template Create("element"); Symbol symbol = this->symbol_table.CreateSymbol("element", true); - void SetUp() { identifier->MapTo(symbol); } + void SetUp() override { identifier->MapTo(symbol); } auto Value(std::pair property) { auto *op = this->storage.template Create(identifier, this->storage.GetPropertyIx(property.first)); @@ -1388,7 +1388,7 @@ class ExpressionEvaluatorAllPropertiesLookup : public ExpressionEvaluatorTeststorage.template Create("element"); Symbol symbol = this->symbol_table.CreateSymbol("element", true); - void SetUp() { identifier->MapTo(symbol); } + void SetUp() override { identifier->MapTo(symbol); } auto Value() { auto *op = this->storage.template Create(identifier); diff --git a/tests/unit/query_plan_checker.hpp b/tests/unit/query_plan_checker.hpp index 37695b581..6f2f23df7 100644 --- a/tests/unit/query_plan_checker.hpp +++ b/tests/unit/query_plan_checker.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include "query/frontend/semantic/symbol_generator.hpp" #include "query/frontend/semantic/symbol_table.hpp" @@ -23,7 +24,7 @@ namespace memgraph::query::plan { class BaseOpChecker { public: - virtual ~BaseOpChecker() {} + virtual ~BaseOpChecker() = default; virtual void CheckOp(LogicalOperator &, const SymbolTable &) = 0; }; @@ -187,7 +188,7 @@ using ExpectEvaluatePatternFilter = OpChecker; class ExpectFilter : public OpChecker { public: - ExpectFilter(const std::vector> &pattern_filters = {}) + explicit ExpectFilter(const std::vector> &pattern_filters = {}) : pattern_filters_(pattern_filters) {} void ExpectOp(Filter &filter, const SymbolTable &symbol_table) override { @@ -222,7 +223,7 @@ class ExpectForeach : public OpChecker { class ExpectApply : public OpChecker { public: - ExpectApply(const std::list &subquery) : subquery_(subquery) {} + explicit ExpectApply(const std::list &subquery) : subquery_(subquery) {} void ExpectOp(Apply &apply, const SymbolTable &symbol_table) override { PlanChecker check_subquery(subquery_, symbol_table); @@ -287,7 +288,7 @@ class ExpectAggregate : public OpChecker { auto aggr_it = aggregations_.begin(); for (const auto &aggr_elem : op.aggregations_) { ASSERT_NE(aggr_it, aggregations_.end()); - auto aggr = *aggr_it++; + auto *aggr = *aggr_it++; // TODO: Proper expression equality EXPECT_EQ(typeid(aggr_elem.value).hash_code(), typeid(aggr->expression1_).hash_code()); EXPECT_EQ(typeid(aggr_elem.key).hash_code(), typeid(aggr->expression2_).hash_code()); @@ -472,9 +473,9 @@ class ExpectIndexedJoin : public OpChecker { class ExpectCallProcedure : public OpChecker { public: - ExpectCallProcedure(const std::string &name, const std::vector &args, + ExpectCallProcedure(std::string name, const std::vector &args, const std::vector &fields, const std::vector &result_syms) - : name_(name), args_(args), fields_(fields), result_syms_(result_syms) {} + : name_(std::move(name)), args_(args), fields_(fields), result_syms_(result_syms) {} void ExpectOp(CallProcedure &op, const SymbolTable &symbol_table) override { EXPECT_EQ(op.procedure_name_, name_); @@ -526,7 +527,7 @@ class FakeDbAccessor { } int64_t VerticesCount(memgraph::storage::LabelId label, memgraph::storage::PropertyId property) const { - for (auto &index : label_property_index_) { + for (const auto &index : label_property_index_) { if (std::get<0>(index) == label && std::get<1>(index) == property) { return std::get<2>(index); } @@ -539,7 +540,7 @@ class FakeDbAccessor { } bool LabelPropertyIndexExists(memgraph::storage::LabelId label, memgraph::storage::PropertyId property) const { - for (auto &index : label_property_index_) { + for (const auto &index : label_property_index_) { if (std::get<0>(index) == label && std::get<1>(index) == property) { return true; } diff --git a/tests/unit/query_plan_common.hpp b/tests/unit/query_plan_common.hpp index 4deba7648..1831a53d7 100644 --- a/tests/unit/query_plan_common.hpp +++ b/tests/unit/query_plan_common.hpp @@ -64,7 +64,7 @@ std::vector> CollectProduce(const Produce &produce, Exec // collect the symbols from the return clause std::vector symbols; - for (auto named_expression : produce.named_expressions_) + for (auto *named_expression : produce.named_expressions_) symbols.emplace_back(context->symbol_table.at(*named_expression)); // stream out results @@ -109,7 +109,7 @@ struct ScanAllTuple { ScanAllTuple MakeScanAll(AstStorage &storage, SymbolTable &symbol_table, const std::string &identifier, std::shared_ptr input = {nullptr}, memgraph::storage::View view = memgraph::storage::View::OLD) { - auto node = memgraph::query::test_common::GetNode(storage, identifier); + auto *node = memgraph::query::test_common::GetNode(storage, identifier); auto symbol = symbol_table.CreateSymbol(identifier, true); node->identifier_->MapTo(symbol); auto logical_op = std::make_shared(input, symbol, view); @@ -125,7 +125,7 @@ ScanAllTuple MakeScanAll(AstStorage &storage, SymbolTable &symbol_table, const s ScanAllTuple MakeScanAllByLabel(AstStorage &storage, SymbolTable &symbol_table, const std::string &identifier, memgraph::storage::LabelId label, std::shared_ptr input = {nullptr}, memgraph::storage::View view = memgraph::storage::View::OLD) { - auto node = memgraph::query::test_common::GetNode(storage, identifier); + auto *node = memgraph::query::test_common::GetNode(storage, identifier); auto symbol = symbol_table.CreateSymbol(identifier, true); node->identifier_->MapTo(symbol); auto logical_op = std::make_shared(input, symbol, label, view); @@ -144,7 +144,7 @@ ScanAllTuple MakeScanAllByLabelPropertyRange(AstStorage &storage, SymbolTable &s std::optional upper_bound, std::shared_ptr input = {nullptr}, memgraph::storage::View view = memgraph::storage::View::OLD) { - auto node = memgraph::query::test_common::GetNode(storage, identifier); + auto *node = memgraph::query::test_common::GetNode(storage, identifier); auto symbol = symbol_table.CreateSymbol(identifier, true); node->identifier_->MapTo(symbol); auto logical_op = std::make_shared(input, symbol, label, property, property_name, @@ -163,7 +163,7 @@ ScanAllTuple MakeScanAllByLabelPropertyValue(AstStorage &storage, SymbolTable &s const std::string &property_name, Expression *value, std::shared_ptr input = {nullptr}, memgraph::storage::View view = memgraph::storage::View::OLD) { - auto node = memgraph::query::test_common::GetNode(storage, identifier); + auto *node = memgraph::query::test_common::GetNode(storage, identifier); auto symbol = symbol_table.CreateSymbol(identifier, true); node->identifier_->MapTo(symbol); auto logical_op = @@ -183,11 +183,11 @@ ExpandTuple MakeExpand(AstStorage &storage, SymbolTable &symbol_table, std::shar Symbol input_symbol, const std::string &edge_identifier, EdgeAtom::Direction direction, const std::vector &edge_types, const std::string &node_identifier, bool existing_node, memgraph::storage::View view) { - auto edge = memgraph::query::test_common::GetEdge(storage, edge_identifier, direction); + auto *edge = memgraph::query::test_common::GetEdge(storage, edge_identifier, direction); auto edge_sym = symbol_table.CreateSymbol(edge_identifier, true); edge->identifier_->MapTo(edge_sym); - auto node = memgraph::query::test_common::GetNode(storage, node_identifier); + auto *node = memgraph::query::test_common::GetNode(storage, node_identifier); auto node_sym = symbol_table.CreateSymbol(node_identifier, true); node->identifier_->MapTo(node_sym); diff --git a/tests/unit/query_plan_edge_cases.cpp b/tests/unit/query_plan_edge_cases.cpp index 52769fa55..d0953651e 100644 --- a/tests/unit/query_plan_edge_cases.cpp +++ b/tests/unit/query_plan_edge_cases.cpp @@ -43,7 +43,7 @@ class QueryExecution : public testing::Test { std::optional repl_state; std::optional> db_gk; - void SetUp() { + void SetUp() override { auto config = [&]() { memgraph::storage::Config config{}; config.durability.storage_directory = data_directory; @@ -70,7 +70,7 @@ class QueryExecution : public testing::Test { interpreter_.emplace(&*interpreter_context_, *db_acc_); } - void TearDown() { + void TearDown() override { interpreter_ = std::nullopt; interpreter_context_ = std::nullopt; db_acc_.reset(); diff --git a/tests/unit/query_plan_operator_to_string.cpp b/tests/unit/query_plan_operator_to_string.cpp index 36918425d..27d27f0d1 100644 --- a/tests/unit/query_plan_operator_to_string.cpp +++ b/tests/unit/query_plan_operator_to_string.cpp @@ -40,7 +40,7 @@ class OperatorToStringTest : public ::testing::Test { dba_storage(db->Access()), dba(dba_storage.get()) {} - ~OperatorToStringTest() { + ~OperatorToStringTest() override { if (std::is_same::value) { disk_test_utils::RemoveRocksDbDirs(testSuite); } diff --git a/tests/unit/query_required_privileges.cpp b/tests/unit/query_required_privileges.cpp index e43525f5b..630bc44a0 100644 --- a/tests/unit/query_required_privileges.cpp +++ b/tests/unit/query_required_privileges.cpp @@ -153,7 +153,7 @@ TEST_F(TestPrivilegeExtractor, DumpDatabase) { } TEST_F(TestPrivilegeExtractor, ReadFile) { - auto load_csv = storage.Create(); + auto *load_csv = storage.Create(); load_csv->row_var_ = IDENT("row"); auto *query = QUERY(SINGLE_QUERY(load_csv)); EXPECT_THAT(GetRequiredPrivileges(query), UnorderedElementsAre(AuthQuery::Privilege::READ_FILE)); diff --git a/tests/unit/query_semantic.cpp b/tests/unit/query_semantic.cpp index d49eb3798..5d015f103 100644 --- a/tests/unit/query_semantic.cpp +++ b/tests/unit/query_semantic.cpp @@ -54,17 +54,17 @@ TYPED_TEST(TestSymbolGenerator, MatchNodeReturn) { auto symbol_table = memgraph::query::MakeSymbolTable(query_ast); // symbols for pattern, node_atom_1 and named_expr in return EXPECT_EQ(symbol_table.max_position(), 3); - auto match = dynamic_cast(query_ast->single_query_->clauses_[0]); - auto pattern = match->patterns_[0]; + auto *match = dynamic_cast(query_ast->single_query_->clauses_[0]); + auto *pattern = match->patterns_[0]; auto pattern_sym = symbol_table.at(*pattern->identifier_); EXPECT_EQ(pattern_sym.type(), Symbol::Type::PATH); EXPECT_FALSE(pattern_sym.user_declared()); - auto node_atom = dynamic_cast(pattern->atoms_[0]); + auto *node_atom = dynamic_cast(pattern->atoms_[0]); auto node_sym = symbol_table.at(*node_atom->identifier_); EXPECT_EQ(node_sym.name(), "node_atom_1"); EXPECT_EQ(node_sym.type(), Symbol::Type::VERTEX); - auto ret = dynamic_cast(query_ast->single_query_->clauses_[1]); - auto named_expr = ret->body_.named_expressions[0]; + auto *ret = dynamic_cast(query_ast->single_query_->clauses_[1]); + auto *named_expr = ret->body_.named_expressions[0]; auto column_sym = symbol_table.at(*named_expr); EXPECT_EQ(node_sym.name(), column_sym.name()); EXPECT_NE(node_sym, column_sym); @@ -78,8 +78,8 @@ TYPED_TEST(TestSymbolGenerator, MatchNamedPattern) { auto symbol_table = memgraph::query::MakeSymbolTable(query_ast); // symbols for p, node_atom_1 and named_expr in return EXPECT_EQ(symbol_table.max_position(), 3); - auto match = dynamic_cast(query_ast->single_query_->clauses_[0]); - auto pattern = match->patterns_[0]; + auto *match = dynamic_cast(query_ast->single_query_->clauses_[0]); + auto *pattern = match->patterns_[0]; auto pattern_sym = symbol_table.at(*pattern->identifier_); EXPECT_EQ(pattern_sym.type(), Symbol::Type::PATH); EXPECT_EQ(pattern_sym.name(), "p"); @@ -114,14 +114,14 @@ TYPED_TEST(TestSymbolGenerator, CreateNodeReturn) { auto symbol_table = memgraph::query::MakeSymbolTable(query_ast); // symbols for pattern, `n` and named_expr EXPECT_EQ(symbol_table.max_position(), 3); - auto create = dynamic_cast(query_ast->single_query_->clauses_[0]); - auto pattern = create->patterns_[0]; - auto node_atom = dynamic_cast(pattern->atoms_[0]); + auto *create = dynamic_cast(query_ast->single_query_->clauses_[0]); + auto *pattern = create->patterns_[0]; + auto *node_atom = dynamic_cast(pattern->atoms_[0]); auto node_sym = symbol_table.at(*node_atom->identifier_); EXPECT_EQ(node_sym.name(), "n"); EXPECT_EQ(node_sym.type(), Symbol::Type::VERTEX); - auto ret = dynamic_cast(query_ast->single_query_->clauses_[1]); - auto named_expr = ret->body_.named_expressions[0]; + auto *ret = dynamic_cast(query_ast->single_query_->clauses_[1]); + auto *named_expr = ret->body_.named_expressions[0]; auto column_sym = symbol_table.at(*named_expr); EXPECT_EQ(node_sym.name(), column_sym.name()); EXPECT_NE(node_sym, column_sym); @@ -151,7 +151,7 @@ TYPED_TEST(TestSymbolGenerator, MatchCreateRedeclareNode) { TYPED_TEST(TestSymbolGenerator, MatchCreateRedeclareEdge) { // AST with redeclaring a match edge variable in create: // MATCH (n) -[r]- (m) CREATE (n) -[r :relationship]-> (l) - auto relationship = "relationship"; + const auto *relationship = "relationship"; auto query = QUERY(SINGLE_QUERY(MATCH(PATTERN(NODE("n"), EDGE("r"), NODE("m"))), CREATE(PATTERN(NODE("n"), EDGE("r", EdgeAtom::Direction::OUT, {relationship}), NODE("l"))))); @@ -176,8 +176,8 @@ TYPED_TEST(TestSymbolGenerator, MatchCreateTypeMismatch) { TYPED_TEST(TestSymbolGenerator, CreateMultipleEdgeType) { // Multiple edge relationship are not allowed when creating edges. // CREATE (n) -[r :rel1 | :rel2]-> (m) - auto rel1 = "rel1"; - auto rel2 = "rel2"; + const auto *rel1 = "rel1"; + const auto *rel2 = "rel2"; auto edge = EDGE("r", EdgeAtom::Direction::OUT, {rel1}); edge->edge_types_.emplace_back(this->storage.GetEdgeTypeIx(rel2)); auto query = QUERY(SINGLE_QUERY(CREATE(PATTERN(NODE("n"), edge, NODE("m"))))); @@ -187,7 +187,7 @@ TYPED_TEST(TestSymbolGenerator, CreateMultipleEdgeType) { TYPED_TEST(TestSymbolGenerator, CreateBidirectionalEdge) { // Bidirectional relationships are not allowed when creating edges. // CREATE (n) -[r :rel1]- (m) - auto rel1 = "rel1"; + const auto *rel1 = "rel1"; auto query = QUERY(SINGLE_QUERY(CREATE(PATTERN(NODE("n"), EDGE("r", EdgeAtom::Direction::BOTH, {rel1}), NODE("m"))))); EXPECT_THROW(memgraph::query::MakeSymbolTable(query), SemanticException); } @@ -276,8 +276,8 @@ TYPED_TEST(TestSymbolGenerator, MatchWithWhereUnbound) { TYPED_TEST(TestSymbolGenerator, CreateMultiExpand) { // Test CREATE (n) -[r :r]-> (m), (n) - [p :p]-> (l) - auto r_type = "r"; - auto p_type = "p"; + const auto *r_type = "r"; + const auto *p_type = "p"; auto node_n1 = NODE("n"); auto edge_r = EDGE("r", EdgeAtom::Direction::OUT, {r_type}); auto node_m = NODE("m"); @@ -308,8 +308,8 @@ TYPED_TEST(TestSymbolGenerator, CreateMultiExpand) { TYPED_TEST(TestSymbolGenerator, MatchCreateExpandLabel) { // Test MATCH (n) CREATE (m) -[r :r]-> (n:label) - auto r_type = "r"; - auto label = "label"; + const auto *r_type = "r"; + const auto *label = "label"; auto query = QUERY(SINGLE_QUERY(MATCH(PATTERN(NODE("n"))), CREATE(PATTERN(NODE("m"), EDGE("r", EdgeAtom::Direction::OUT, {r_type}), NODE("n", label))))); @@ -318,7 +318,7 @@ TYPED_TEST(TestSymbolGenerator, MatchCreateExpandLabel) { TYPED_TEST(TestSymbolGenerator, CreateExpandProperty) { // Test CREATE (n) -[r :r]-> (n {prop: 42}) - auto r_type = "r"; + const auto *r_type = "r"; auto n_prop = NODE("n"); std::get<0>(n_prop->properties_)[this->storage.GetPropertyIx("prop")] = LITERAL(42); auto query = QUERY(SINGLE_QUERY(CREATE(PATTERN(NODE("n"), EDGE("r", EdgeAtom::Direction::OUT, {r_type}), n_prop)))); @@ -379,7 +379,7 @@ TYPED_TEST(TestSymbolGenerator, MatchPropCreateNodeProp) { TYPED_TEST(TestSymbolGenerator, CreateNodeEdge) { // Test CREATE (n), (n) -[r :r]-> (n) - auto r_type = "r"; + const auto *r_type = "r"; auto node_1 = NODE("n"); auto node_2 = NODE("n"); auto edge = EDGE("r", EdgeAtom::Direction::OUT, {r_type}); @@ -396,7 +396,7 @@ TYPED_TEST(TestSymbolGenerator, CreateNodeEdge) { TYPED_TEST(TestSymbolGenerator, MatchWithCreate) { // Test MATCH (n) WITH n AS m CREATE (m) -[r :r]-> (m) - auto r_type = "r"; + const auto *r_type = "r"; auto node_1 = NODE("n"); auto node_2 = NODE("m"); auto edge = EDGE("r", EdgeAtom::Direction::OUT, {r_type}); @@ -500,7 +500,7 @@ TYPED_TEST(TestSymbolGenerator, MergeVariableError) { TYPED_TEST(TestSymbolGenerator, MergeVariableErrorEdge) { // Test MATCH (n) -[r]- (m) MERGE (a) -[r :rel]- (b) - auto rel = "rel"; + const auto *rel = "rel"; auto query = QUERY(SINGLE_QUERY(MATCH(PATTERN(NODE("n"), EDGE("r"), NODE("m"))), MERGE(PATTERN(NODE("a"), EDGE("r", EdgeAtom::Direction::BOTH, {rel}), NODE("b"))))); EXPECT_THROW(memgraph::query::MakeSymbolTable(query), RedeclareVariableError); @@ -516,7 +516,7 @@ TYPED_TEST(TestSymbolGenerator, MergeEdgeWithoutType) { TYPED_TEST(TestSymbolGenerator, MergeOnMatchOnCreate) { // Test MATCH (n) MERGE (n) -[r :rel]- (m) ON MATCH SET n.prop = 42 // ON CREATE SET m.prop = 42 RETURN r AS r - auto rel = "rel"; + const auto *rel = "rel"; auto prop = this->dba.NameToProperty("prop"); auto match_n = NODE("n"); auto merge_n = NODE("n"); @@ -641,8 +641,8 @@ TYPED_TEST(TestSymbolGenerator, MatchReturnAsteriskNoUserVariables) { TYPED_TEST(TestSymbolGenerator, MatchMergeExpandLabel) { // Test MATCH (n) MERGE (m) -[r :r]-> (n:label) - auto r_type = "r"; - auto label = "label"; + const auto *r_type = "r"; + const auto *label = "label"; auto query = QUERY(SINGLE_QUERY(MATCH(PATTERN(NODE("n"))), MERGE(PATTERN(NODE("m"), EDGE("r", EdgeAtom::Direction::OUT, {r_type}), NODE("n", label))))); diff --git a/tests/unit/rpc_messages.hpp b/tests/unit/rpc_messages.hpp index 6058c37cf..2f8175a36 100644 --- a/tests/unit/rpc_messages.hpp +++ b/tests/unit/rpc_messages.hpp @@ -11,6 +11,8 @@ #pragma once +#include + #include "rpc/messages.hpp" #include "slk/serialization.hpp" #include "utils/typeinfo.hpp" @@ -18,7 +20,7 @@ struct SumReq { static const memgraph::utils::TypeInfo kType; - SumReq() {} // Needed for serialization. + SumReq() = default; // Needed for serialization. SumReq(int x, int y) : x(x), y(y) {} static void Load(SumReq *obj, memgraph::slk::Reader *reader); @@ -33,8 +35,8 @@ const memgraph::utils::TypeInfo SumReq::kType{memgraph::utils::TypeId::UNKNOWN, struct SumRes { static const memgraph::utils::TypeInfo kType; - SumRes() {} // Needed for serialization. - SumRes(int sum) : sum(sum) {} + SumRes() = default; // Needed for serialization. + explicit SumRes(int sum) : sum(sum) {} static void Load(SumRes *obj, memgraph::slk::Reader *reader); static void Save(const SumRes &obj, memgraph::slk::Builder *builder); @@ -57,8 +59,8 @@ using Sum = memgraph::rpc::RequestResponse; struct EchoMessage { static const memgraph::utils::TypeInfo kType; - EchoMessage() {} // Needed for serialization. - EchoMessage(const std::string &data) : data(data) {} + EchoMessage() = default; // Needed for serialization. + explicit EchoMessage(std::string data) : data(std::move(data)) {} static void Load(EchoMessage *obj, memgraph::slk::Reader *reader); static void Save(const EchoMessage &obj, memgraph::slk::Builder *builder); diff --git a/tests/unit/slk_core.cpp b/tests/unit/slk_core.cpp index 65b916db3..9b63b82f8 100644 --- a/tests/unit/slk_core.cpp +++ b/tests/unit/slk_core.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -108,7 +108,7 @@ TEST(SlkCore, SetPrimitive) { } TEST(SlkCore, SetString) { - std::set original{"hai hai hai", "nandare!"}; + std::set> original{"hai hai hai", "nandare!"}; memgraph::slk::Loopback loopback; auto builder = loopback.GetBuilder(); memgraph::slk::Save(original, builder); @@ -116,7 +116,7 @@ TEST(SlkCore, SetString) { for (const auto &item : original) { size += sizeof(uint64_t) + item.size(); } - std::set decoded; + std::set> decoded; auto reader = loopback.GetReader(); memgraph::slk::Load(&decoded, reader); ASSERT_EQ(original, decoded); diff --git a/tests/unit/slk_streams.cpp b/tests/unit/slk_streams.cpp index 634eaecb5..8a673af1c 100644 --- a/tests/unit/slk_streams.cpp +++ b/tests/unit/slk_streams.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -66,7 +66,7 @@ std::vector BufferToBinaryData(const uint8_t *data, size_t size, std size_t pos = 0; for (size_t i = 0; i < sizes.size(); ++i) { EXPECT_GE(size, pos + sizes[i]); - ret.push_back({data + pos, sizes[i]}); + ret.emplace_back(data + pos, sizes[i]); pos += sizes[i]; } return ret; diff --git a/tests/unit/storage_rocks.cpp b/tests/unit/storage_rocks.cpp index 42890c383..6d5db7d75 100644 --- a/tests/unit/storage_rocks.cpp +++ b/tests/unit/storage_rocks.cpp @@ -49,7 +49,7 @@ class RocksDBStorageTest : public ::testing::TestWithParam { disk_test_utils::RemoveRocksDbDirs(testSuite); } - ~RocksDBStorageTest() override {} + ~RocksDBStorageTest() override = default; protected: std::unique_ptr storage; diff --git a/tests/unit/storage_v2_property_store.cpp b/tests/unit/storage_v2_property_store.cpp index 9da503f71..59b38c632 100644 --- a/tests/unit/storage_v2_property_store.cpp +++ b/tests/unit/storage_v2_property_store.cpp @@ -670,7 +670,7 @@ TEST(PropertyStore, SetMultipleProperties) { const std::map data_in_map{data.begin(), data.end()}; auto check_store = [data](const memgraph::storage::PropertyStore &store) { - for (auto &[key, value] : data) { + for (const auto &[key, value] : data) { ASSERT_TRUE(store.IsPropertyEqual(key, value)); } }; diff --git a/tests/unit/storage_v2_wal_file.cpp b/tests/unit/storage_v2_wal_file.cpp index 19b633f9f..a67b09305 100644 --- a/tests/unit/storage_v2_wal_file.cpp +++ b/tests/unit/storage_v2_wal_file.cpp @@ -231,7 +231,7 @@ class DeltaGenerator final { } void AppendOperation(memgraph::storage::durability::StorageMetadataOperation operation, const std::string &label, - const std::set properties = {}, const std::string &stats = {}) { + const std::set> properties = {}, const std::string &stats = {}) { auto label_id = memgraph::storage::LabelId::FromUint(mapper_.NameToId(label)); std::set property_ids; for (const auto &property : properties) { @@ -378,7 +378,7 @@ void AssertWalDataEqual(const DeltaGenerator::DataT &data, const std::filesystem class WalFileTest : public ::testing::TestWithParam { public: - WalFileTest() {} + WalFileTest() = default; void SetUp() override { Clear(); } @@ -710,7 +710,7 @@ TEST_P(WalFileTest, PartialData) { class StorageModeWalFileTest : public ::testing::TestWithParam { public: - StorageModeWalFileTest() {} + StorageModeWalFileTest() = default; void SetUp() override { Clear(); } diff --git a/tests/unit/utils_file.cpp b/tests/unit/utils_file.cpp index 05d8184be..89c3699a9 100644 --- a/tests/unit/utils_file.cpp +++ b/tests/unit/utils_file.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -132,7 +132,7 @@ class UtilsFileTest : public ::testing::Test { private: void Clear() { if (fs::exists(storage)) { - for (auto &file : fs::recursive_directory_iterator(storage)) { + for (const auto &file : fs::recursive_directory_iterator(storage)) { std::error_code error_code; // For exception suppression. fs::permissions(file.path(), fs::perms::owner_all, fs::perm_options::add, error_code); } diff --git a/tests/unit/utils_string.cpp b/tests/unit/utils_string.cpp index 4cde1dfe1..cefe57a6a 100644 --- a/tests/unit/utils_string.cpp +++ b/tests/unit/utils_string.cpp @@ -1,4 +1,4 @@ -// Copyright 2022 Memgraph Ltd. +// Copyright 2023 Memgraph Ltd. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source @@ -151,7 +151,7 @@ TEST(String, RandomString) { EXPECT_EQ(RandomString(1).size(), 1); EXPECT_EQ(RandomString(42).size(), 42); - std::set string_set; + std::set> string_set; for (int i = 0; i < 20; ++i) string_set.emplace(RandomString(256)); EXPECT_EQ(string_set.size(), 20);