diff --git a/.github/workflows/ci-workflow.yml b/.github/workflows/ci-workflow.yml index 551ca7b4f4..8fc91b162e 100644 --- a/.github/workflows/ci-workflow.yml +++ b/.github/workflows/ci-workflow.yml @@ -330,6 +330,9 @@ jobs: - name: Check and fix test format run: python3 scripts/run-clang-format.py --in-place --clang-format-executable /usr/bin/clang-format-18 -r test/ + - name: Check and fix tools format + run: python3 scripts/run-clang-format.py --in-place --clang-format-executable /usr/bin/clang-format-18 -r tools/ + - name: Check and fix extension format run: python3 scripts/run-clang-format.py --in-place --clang-format-executable /usr/bin/clang-format-18 -r extension/ diff --git a/tools/benchmark/benchmark.cpp b/tools/benchmark/benchmark.cpp index 2d417ea727..381f0f7cda 100644 --- a/tools/benchmark/benchmark.cpp +++ b/tools/benchmark/benchmark.cpp @@ -36,8 +36,8 @@ std::unique_ptr Benchmark::runWithProfile() const { return conn->query("PROFILE " + query, encodedJoin); } -void Benchmark::logQueryInfo( - std::ofstream& log, uint32_t runNum, std::vector& actualOutput) const { +void Benchmark::logQueryInfo(std::ofstream& log, uint32_t runNum, + std::vector& actualOutput) const { log << "Run Num: " << runNum << '\n'; log << "Status: " << (actualOutput == expectedOutput ? "pass" : "error") << '\n'; log << "Query: " << query << '\n'; diff --git a/tools/benchmark/benchmark_runner.cpp b/tools/benchmark/benchmark_runner.cpp index 151c3221f0..e7a956aed7 100644 --- a/tools/benchmark/benchmark_runner.cpp +++ b/tools/benchmark/benchmark_runner.cpp @@ -12,11 +12,11 @@ namespace benchmark { const char* BENCHMARK_SUFFIX = ".benchmark"; -BenchmarkRunner::BenchmarkRunner( - const std::string& datasetPath, std::unique_ptr config) +BenchmarkRunner::BenchmarkRunner(const std::string& datasetPath, + std::unique_ptr config) : config{std::move(config)} { - database = std::make_unique( - datasetPath, SystemConfig(this->config->bufferPoolSize, this->config->numThreads)); + database = std::make_unique(datasetPath, + SystemConfig(this->config->bufferPoolSize, this->config->numThreads)); spdlog::set_level(spdlog::level::debug); } @@ -37,8 +37,8 @@ void BenchmarkRunner::runAllBenchmarks() { // an unitialized object. benchmark.get()); } catch (std::exception& e) { - spdlog::error( - "Error encountered while running benchmark {}: {}.", benchmark->name, e.what()); + spdlog::error("Error encountered while running benchmark {}: {}.", benchmark->name, + e.what()); } } } @@ -51,8 +51,8 @@ void BenchmarkRunner::registerBenchmark(const std::string& path) { } } -double BenchmarkRunner::computeAverageOfLastRuns( - const double* runTimes, const int& len, const int& lastRunsToAverage) { +double BenchmarkRunner::computeAverageOfLastRuns(const double* runTimes, const int& len, + const int& lastRunsToAverage) { double sum = 0; for (int i = len - lastRunsToAverage; i < len; ++i) { sum += runTimes[i]; @@ -77,15 +77,15 @@ void BenchmarkRunner::runBenchmark(Benchmark* benchmark) const { runTimes[i] = queryResult->getQuerySummary()->getExecutionTime(); } spdlog::info("Time Taken (Average of Last {} runs) (ms): {}", config->numRuns, - computeAverageOfLastRuns( - &runTimes[0], config->numRuns, config->numRuns /* numRunsToAverage */)); + computeAverageOfLastRuns(&runTimes[0], config->numRuns, + config->numRuns /* numRunsToAverage */)); } void BenchmarkRunner::profileQueryIfEnabled(Benchmark* benchmark) const { if (config->enableProfile && !config->outputPath.empty()) { auto profileInfo = benchmark->runWithProfile(); - std::ofstream profileFile( - config->outputPath + "/" + benchmark->name + "_profile.txt", std::ios_base::app); + std::ofstream profileFile(config->outputPath + "/" + benchmark->name + "_profile.txt", + std::ios_base::app); profileFile << profileInfo->getNext()->toString() << '\n'; profileFile.flush(); profileFile.close(); diff --git a/tools/benchmark/include/benchmark.h b/tools/benchmark/include/benchmark.h index e45bdd7c0d..21f651acde 100644 --- a/tools/benchmark/include/benchmark.h +++ b/tools/benchmark/include/benchmark.h @@ -20,8 +20,8 @@ class Benchmark { private: void loadBenchmark(const std::string& benchmarkPath); - void logQueryInfo( - std::ofstream& log, uint32_t runNum, std::vector& actualOutput) const; + void logQueryInfo(std::ofstream& log, uint32_t runNum, + std::vector& actualOutput) const; void verify(std::vector& actualOutput) const; public: diff --git a/tools/benchmark/include/benchmark_runner.h b/tools/benchmark/include/benchmark_runner.h index ab409a3308..96fcdb9826 100644 --- a/tools/benchmark/include/benchmark_runner.h +++ b/tools/benchmark/include/benchmark_runner.h @@ -14,8 +14,8 @@ class BenchmarkRunner { void registerBenchmarks(const std::string& path); void runAllBenchmarks(); - static double computeAverageOfLastRuns( - const double* runTimes, const int& len, const int& lastRunsToAverage); + static double computeAverageOfLastRuns(const double* runTimes, const int& len, + const int& lastRunsToAverage); private: void registerBenchmark(const std::string& path); diff --git a/tools/benchmark/main.cpp b/tools/benchmark/main.cpp index 48264377f4..7d2396c137 100644 --- a/tools/benchmark/main.cpp +++ b/tools/benchmark/main.cpp @@ -53,8 +53,8 @@ int main(int argc, char** argv) { try { runner.registerBenchmarks(benchmarkPath); } catch (std::exception& e) { - spdlog::error( - "Error encountered while registering benchmark in {}: {}.", benchmarkPath, e.what()); + spdlog::error("Error encountered while registering benchmark in {}: {}.", benchmarkPath, + e.what()); } runner.runAllBenchmarks(); return 0; diff --git a/tools/java_api/src/jni/kuzu_java.cpp b/tools/java_api/src/jni/kuzu_java.cpp index 4f7418cd98..1c32cc3362 100644 --- a/tools/java_api/src/jni/kuzu_java.cpp +++ b/tools/java_api/src/jni/kuzu_java.cpp @@ -23,8 +23,8 @@ using namespace kuzu::main; using namespace kuzu::common; using namespace kuzu::processor; -jobject createJavaObject( - JNIEnv* env, void* memAddress, const std::string& classPath, const std::string& refFieldName) { +jobject createJavaObject(JNIEnv* env, void* memAddress, const std::string& classPath, + const std::string& refFieldName) { auto address = reinterpret_cast(memAddress); auto ref = static_cast(address); @@ -118,8 +118,8 @@ std::string dataTypeToString(const LogicalType& dataType) { return LogicalTypeUtils::toString(dataType.getLogicalTypeID()); } -std::unordered_map> javaMapToCPPMap( - JNIEnv* env, jobject javaMap) { +std::unordered_map> javaMapToCPPMap(JNIEnv* env, + jobject javaMap) { jclass mapClass = env->FindClass("java/util/Map"); jmethodID entrySet = env->GetMethodID(mapClass, "entrySet", "()Ljava/util/Set;"); @@ -156,8 +156,8 @@ std::unordered_map> javaMapToCPPMap( * All Database native functions */ // protected static native void kuzu_native_reload_library(String lib_path); -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1native_1reload_1library( - JNIEnv* env, jclass, jstring lib_path) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1native_1reload_1library(JNIEnv* env, jclass, + jstring lib_path) { #ifdef _WIN32 // Do nothing on Windows #else @@ -174,8 +174,8 @@ JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1native_1reload_1library( } JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1init(JNIEnv* env, jclass, - jstring database_path, jlong buffer_pool_size, jboolean enable_compression, - jboolean read_only, jlong max_db_size) { + jstring database_path, jlong buffer_pool_size, jboolean enable_compression, jboolean read_only, + jlong max_db_size) { const char* path = env->GetStringUTFChars(database_path, JNI_FALSE); uint64_t buffer = static_cast(buffer_pool_size); @@ -198,14 +198,14 @@ JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1init(JNIEnv* return 0; } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1destroy( - JNIEnv* env, jclass, jobject thisDB) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1destroy(JNIEnv* env, jclass, + jobject thisDB) { Database* db = getDatabase(env, thisDB); delete db; } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1set_1logging_1level( - JNIEnv* env, jclass, jstring logging_level) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1set_1logging_1level(JNIEnv* env, + jclass, jstring logging_level) { const char* lvl = env->GetStringUTFChars(logging_level, JNI_FALSE); try { Database::setLoggingLevel(lvl); @@ -221,8 +221,8 @@ JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1database_1set_1logging_1 * All Connection native functions */ -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1init( - JNIEnv* env, jclass, jobject db) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1init(JNIEnv* env, jclass, + jobject db) { try { Database* conn_db = getDatabase(env, db); @@ -238,31 +238,31 @@ JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1init( return 0; } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1destroy( - JNIEnv* env, jclass, jobject thisConn) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1destroy(JNIEnv* env, jclass, + jobject thisConn) { Connection* conn = getConnection(env, thisConn); delete conn; } JNIEXPORT void JNICALL -Java_com_kuzudb_KuzuNative_kuzu_1connection_1set_1max_1num_1thread_1for_1exec( - JNIEnv* env, jclass, jobject thisConn, jlong num_threads) { +Java_com_kuzudb_KuzuNative_kuzu_1connection_1set_1max_1num_1thread_1for_1exec(JNIEnv* env, jclass, + jobject thisConn, jlong num_threads) { Connection* conn = getConnection(env, thisConn); uint64_t threads = static_cast(num_threads); conn->setMaxNumThreadForExec(threads); } JNIEXPORT jlong JNICALL -Java_com_kuzudb_KuzuNative_kuzu_1connection_1get_1max_1num_1thread_1for_1exec( - JNIEnv* env, jclass, jobject thisConn) { +Java_com_kuzudb_KuzuNative_kuzu_1connection_1get_1max_1num_1thread_1for_1exec(JNIEnv* env, jclass, + jobject thisConn) { Connection* conn = getConnection(env, thisConn); uint64_t threads = conn->getMaxNumThreadForExec(); jlong num_threads = static_cast(threads); return num_threads; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1query( - JNIEnv* env, jclass, jobject thisConn, jstring query) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1query(JNIEnv* env, jclass, + jobject thisConn, jstring query) { Connection* conn = getConnection(env, thisConn); const char* CPPQuery = env->GetStringUTFChars(query, JNI_FALSE); auto query_result = conn->query(CPPQuery).release(); @@ -278,8 +278,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1query( return newQRObject; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1prepare( - JNIEnv* env, jclass, jobject thisConn, jstring query) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1prepare(JNIEnv* env, jclass, + jobject thisConn, jstring query) { Connection* conn = getConnection(env, thisConn); const char* cppquery = env->GetStringUTFChars(query, JNI_FALSE); @@ -294,8 +294,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1prepare( return ret; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1execute( - JNIEnv* env, jclass, jobject thisConn, jobject preStm, jobject param_map) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1execute(JNIEnv* env, jclass, + jobject thisConn, jobject preStm, jobject param_map) { Connection* conn = getConnection(env, thisConn); PreparedStatement* ps = getPreparedStatement(env, preStm); @@ -311,14 +311,14 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1execute( return ret; } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1interrupt( - JNIEnv* env, jclass, jobject thisConn) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1interrupt(JNIEnv* env, jclass, + jobject thisConn) { Connection* conn = getConnection(env, thisConn); conn->interrupt(); } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1set_1query_1timeout( - JNIEnv* env, jclass, jobject thisConn, jlong timeout_in_ms) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1set_1query_1timeout(JNIEnv* env, + jclass, jobject thisConn, jlong timeout_in_ms) { Connection* conn = getConnection(env, thisConn); uint64_t timeout = static_cast(timeout_in_ms); conn->setQueryTimeOut(timeout); @@ -328,15 +328,15 @@ JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1connection_1set_1query_1 * All PreparedStatement native functions */ -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1prepared_1statement_1destroy( - JNIEnv* env, jclass, jobject thisPS) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1prepared_1statement_1destroy(JNIEnv* env, + jclass, jobject thisPS) { PreparedStatement* ps = getPreparedStatement(env, thisPS); delete ps; } JNIEXPORT jboolean JNICALL -Java_com_kuzudb_KuzuNative_kuzu_1prepared_1statement_1allow_1active_1transaction( - JNIEnv* env, jclass, jobject thisPS) { +Java_com_kuzudb_KuzuNative_kuzu_1prepared_1statement_1allow_1active_1transaction(JNIEnv* env, + jclass, jobject thisPS) { PreparedStatement* ps = getPreparedStatement(env, thisPS); return static_cast(ps->allowActiveTransaction()); } @@ -359,14 +359,14 @@ JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1prepared_1statement_1 * All QueryResult native functions */ -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1destroy( - JNIEnv* env, jclass, jobject thisQR) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1destroy(JNIEnv* env, jclass, + jobject thisQR) { QueryResult* qr = getQueryResult(env, thisQR); delete qr; } -JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1is_1success( - JNIEnv* env, jclass, jobject thisQR) { +JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1is_1success(JNIEnv* env, + jclass, jobject thisQR) { QueryResult* qr = getQueryResult(env, thisQR); return static_cast(qr->isSuccess()); } @@ -439,14 +439,14 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1get_1q return newQSObject; } -JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1has_1next( - JNIEnv* env, jclass, jobject thisQR) { +JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1has_1next(JNIEnv* env, + jclass, jobject thisQR) { QueryResult* qr = getQueryResult(env, thisQR); return static_cast(qr->hasNext()); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1get_1next( - JNIEnv* env, jclass, jobject thisQR) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1get_1next(JNIEnv* env, + jclass, jobject thisQR) { QueryResult* qr = getQueryResult(env, thisQR); auto flat_tuple = qr->getNext(); @@ -461,16 +461,16 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1get_1n return newFTObject; } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1to_1string( - JNIEnv* env, jclass, jobject thisQR) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1to_1string(JNIEnv* env, + jclass, jobject thisQR) { QueryResult* qr = getQueryResult(env, thisQR); std::string result_string = qr->toString(); jstring ret = env->NewStringUTF(result_string.c_str()); return ret; } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1reset_1iterator( - JNIEnv* env, jclass, jobject thisQR) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1reset_1iterator(JNIEnv* env, + jclass, jobject thisQR) { QueryResult* qr = getQueryResult(env, thisQR); qr->resetIterator(); } @@ -479,8 +479,8 @@ JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1query_1result_1reset_1it * All FlatTuple native functions */ -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1destroy( - JNIEnv* env, jclass, jobject thisFT) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1destroy(JNIEnv* env, jclass, + jobject thisFT) { jclass javaFTClass = env->GetObjectClass(thisFT); jfieldID fieldID = env->GetFieldID(javaFTClass, "ft_ref", "J"); jlong fieldValue = env->GetLongField(thisFT, fieldID); @@ -492,13 +492,15 @@ JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1destroy( delete flat_tuple_shared_ptr; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1get_1value( - JNIEnv* env, jclass, jobject thisFT, jlong index) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1get_1value(JNIEnv* env, + jclass, jobject thisFT, jlong index) { FlatTuple* ft = getFlatTuple(env, thisFT); Value* value; try { value = ft->getValue(index); - } catch (Exception& e) { return nullptr; } + } catch (Exception& e) { + return nullptr; + } jobject v = createJavaObject(env, value, "com/kuzudb/KuzuValue", "v_ref"); jclass clazz = env->GetObjectClass(v); @@ -508,8 +510,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1get_1val return v; } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1to_1string( - JNIEnv* env, jclass, jobject thisFT) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1to_1string(JNIEnv* env, + jclass, jobject thisFT) { FlatTuple* ft = getFlatTuple(env, thisFT); std::string result_string = ft->toString(); jstring ret = env->NewStringUTF(result_string.c_str()); @@ -522,15 +524,15 @@ JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1flat_1tuple_1to_1stri namespace kuzu::common { struct JavaAPIHelper { - static inline LogicalType* createLogicalType( - LogicalTypeID typeID, std::unique_ptr extraTypeInfo) { + static inline LogicalType* createLogicalType(LogicalTypeID typeID, + std::unique_ptr extraTypeInfo) { return new LogicalType(typeID, std::move(extraTypeInfo)); } }; } // namespace kuzu::common -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1create( - JNIEnv* env, jclass, jobject id, jobject child_type, jlong num_elements_in_array) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1create(JNIEnv* env, jclass, + jobject id, jobject child_type, jlong num_elements_in_array) { jclass javaIDClass = env->GetObjectClass(id); jfieldID fieldID = env->GetFieldID(javaIDClass, "value", "I"); jint fieldValue = env->GetIntField(id, fieldID); @@ -542,18 +544,18 @@ JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1create( data_type = new LogicalType(logicalTypeID); } else { auto child_type_pty = std::make_unique(*getDataType(env, child_type)); - auto extraTypeInfo = num_elements_in_array > 0 ? - std::make_unique( - std::move(child_type_pty), num_elements_in_array) : - std::make_unique(std::move(child_type_pty)); + auto extraTypeInfo = + num_elements_in_array > 0 ? + std::make_unique(std::move(child_type_pty), num_elements_in_array) : + std::make_unique(std::move(child_type_pty)); data_type = JavaAPIHelper::createLogicalType(logicalTypeID, std::move(extraTypeInfo)); } uint64_t address = reinterpret_cast(data_type); return static_cast(address); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1clone( - JNIEnv* env, jclass, jobject thisDT) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1clone(JNIEnv* env, jclass, + jobject thisDT) { auto* oldDT = getDataType(env, thisDT); auto* newDT = new LogicalType(*oldDT); @@ -561,22 +563,22 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1clone( return dt; } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1destroy( - JNIEnv* env, jclass, jobject thisDT) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1destroy(JNIEnv* env, jclass, + jobject thisDT) { auto* dt = getDataType(env, thisDT); delete dt; } -JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1equals( - JNIEnv* env, jclass, jobject dt1, jobject dt2) { +JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1equals(JNIEnv* env, jclass, + jobject dt1, jobject dt2) { auto* cppdt1 = getDataType(env, dt1); auto* cppdt2 = getDataType(env, dt2); return static_cast(*cppdt1 == *cppdt2); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1id( - JNIEnv* env, jclass, jobject thisDT) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1id(JNIEnv* env, jclass, + jobject thisDT) { auto* dt = getDataType(env, thisDT); std::string id_str = dataTypeToString(*dt); @@ -587,8 +589,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1id( return id; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1child_1type( - JNIEnv* env, jclass, jobject thisDT) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1child_1type(JNIEnv* env, + jclass, jobject thisDT) { auto* parent_type = getDataType(env, thisDT); LogicalType* child_type; if (parent_type->getLogicalTypeID() == LogicalTypeID::ARRAY) { @@ -603,8 +605,7 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1chil return ret; } -JNIEXPORT jlong JNICALL -Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1num_1elements_1in_1array( +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1num_1elements_1in_1array( JNIEnv* env, jclass, jobject thisDT) { auto* dt = getDataType(env, thisDT); if (dt->getLogicalTypeID() != LogicalTypeID::ARRAY) { @@ -617,8 +618,8 @@ Java_com_kuzudb_KuzuNative_kuzu_1data_1type_1get_1num_1elements_1in_1array( * All Value native functions */ -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1null( - JNIEnv* env, jclass) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1null(JNIEnv* env, + jclass) { Value* v = new Value(Value::createNullValue()); jobject ret = createJavaObject(env, v, "com/kuzudb/KuzuValue", "v_ref"); return ret; @@ -632,28 +633,28 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1null_1 return ret; } -JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1is_1null( - JNIEnv* env, jclass, jobject thisV) { +JNIEXPORT jboolean JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1is_1null(JNIEnv* env, jclass, + jobject thisV) { Value* v = getValue(env, thisV); return static_cast(v->isNull()); } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1set_1null( - JNIEnv* env, jclass, jobject thisV, jboolean is_null) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1set_1null(JNIEnv* env, jclass, + jobject thisV, jboolean is_null) { Value* v = getValue(env, thisV); v->setNull(static_cast(is_null)); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1default( - JNIEnv* env, jclass, jobject data_type) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1default(JNIEnv* env, + jclass, jobject data_type) { auto* dt = getDataType(env, data_type); Value* v = new Value(Value::createDefaultValue(*dt)); jobject ret = createJavaObject(env, v, "com/kuzudb/KuzuValue", "v_ref"); return ret; } -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1value( - JNIEnv* env, jclass, jobject val) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1value(JNIEnv* env, jclass, + jobject val) { Value* v; jclass val_class = env->GetObjectClass(val); if (env->IsInstanceOf(val, env->FindClass("java/lang/Boolean"))) { @@ -713,34 +714,34 @@ JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1create_1value( return static_cast(address); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1clone( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1clone(JNIEnv* env, jclass, + jobject thisValue) { Value* v = getValue(env, thisValue); Value* copy = new Value(*v); return createJavaObject(env, copy, "com/kuzudb/KuzuValue", "v_ref"); } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1copy( - JNIEnv* env, jclass, jobject thisValue, jobject otherValue) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1copy(JNIEnv* env, jclass, + jobject thisValue, jobject otherValue) { Value* thisV = getValue(env, thisValue); Value* otherV = getValue(env, otherValue); thisV->copyValueFrom(*otherV); } -JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1destroy( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT void JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1destroy(JNIEnv* env, jclass, + jobject thisValue) { Value* v = getValue(env, thisValue); delete v; } -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1list_1size( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1list_1size(JNIEnv* env, jclass, + jobject thisValue) { Value* v = getValue(env, thisValue); return static_cast(NestedVal::getChildrenSize(v)); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1list_1element( - JNIEnv* env, jclass, jobject thisValue, jlong index) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1list_1element(JNIEnv* env, + jclass, jobject thisValue, jlong index) { Value* v = getValue(env, thisValue); uint64_t idx = static_cast(index); @@ -758,15 +759,15 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1list_1ele return element; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1data_1type( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1data_1type(JNIEnv* env, + jclass, jobject thisValue) { Value* v = getValue(env, thisValue); auto* dt = new LogicalType(*v->getDataType()); return createJavaObject(env, dt, "com/kuzudb/KuzuDataType", "dt_ref"); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1value( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1value(JNIEnv* env, jclass, + jobject thisValue) { Value* v = getValue(env, thisValue); auto dt = v->getDataType(); auto logicalTypeId = dt->getLogicalTypeID(); @@ -960,16 +961,16 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1value( } } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1to_1string( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1to_1string(JNIEnv* env, jclass, + jobject thisValue) { Value* v = getValue(env, thisValue); std::string result_string = v->toString(); jstring ret = env->NewStringUTF(result_string.c_str()); return ret; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1id( - JNIEnv* env, jclass, jobject thisNV) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1id(JNIEnv* env, jclass, + jobject thisNV) { auto nv = getValue(env, thisNV); auto idVal = NodeVal::getNodeIDVal(nv); if (idVal == nullptr) { @@ -982,8 +983,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1id( return ret; } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1label_1name( - JNIEnv* env, jclass, jobject thisNV) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1label_1name(JNIEnv* env, + jclass, jobject thisNV) { auto* nv = getValue(env, thisNV); auto labelVal = NodeVal::getLabelVal(nv); if (labelVal == nullptr) { @@ -993,8 +994,8 @@ JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1label return env->NewStringUTF(label.c_str()); } -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1property_1size( - JNIEnv* env, jclass, jobject thisNV) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1property_1size(JNIEnv* env, + jclass, jobject thisNV) { auto* nv = getValue(env, thisNV); auto size = NodeVal::getNumProperties(nv); return static_cast(size); @@ -1018,16 +1019,16 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1get_1prope return ret; } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1to_1string( - JNIEnv* env, jclass, jobject thisNV) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1node_1val_1to_1string(JNIEnv* env, + jclass, jobject thisNV) { auto* nv = getValue(env, thisNV); std::string result_string = NodeVal::toString(nv); jstring ret = env->NewStringUTF(result_string.c_str()); return ret; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1src_1id( - JNIEnv* env, jclass, jobject thisRV) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1src_1id(JNIEnv* env, + jclass, jobject thisRV) { auto* rv = getValue(env, thisRV); auto srcIdVal = RelVal::getSrcNodeIDVal(rv); if (srcIdVal == nullptr) { @@ -1040,8 +1041,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1src_1i return ret; } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1dst_1id( - JNIEnv* env, jclass, jobject thisRV) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1dst_1id(JNIEnv* env, + jclass, jobject thisRV) { auto* rv = getValue(env, thisRV); auto dstIdVal = RelVal::getDstNodeIDVal(rv); if (dstIdVal == nullptr) { @@ -1054,8 +1055,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1dst_1i return ret; } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1label_1name( - JNIEnv* env, jclass, jobject thisRV) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1label_1name(JNIEnv* env, + jclass, jobject thisRV) { auto* rv = getValue(env, thisRV); auto labelVal = RelVal::getLabelVal(rv); if (labelVal == nullptr) { @@ -1065,8 +1066,8 @@ JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1label_ return env->NewStringUTF(label.c_str()); } -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1property_1size( - JNIEnv* env, jclass, jobject thisRV) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1property_1size(JNIEnv* env, + jclass, jobject thisRV) { auto* rv = getValue(env, thisRV); auto size = RelVal::getNumProperties(rv); return static_cast(size); @@ -1092,8 +1093,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1get_1proper return ret; } -JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1to_1string( - JNIEnv* env, jclass, jobject thisRV) { +JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rel_1val_1to_1string(JNIEnv* env, jclass, + jobject thisRV) { auto* rv = getValue(env, thisRV); std::string result_string = RelVal::toString(rv); jstring ret = env->NewStringUTF(result_string.c_str()); @@ -1112,8 +1113,8 @@ JNIEXPORT jstring JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1struct_1f return env->NewStringUTF(name.c_str()); } -JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1struct_1index( - JNIEnv* env, jclass, jobject thisSV, jstring field_name) { +JNIEXPORT jlong JNICALL Java_com_kuzudb_KuzuNative_kuzu_1value_1get_1struct_1index(JNIEnv* env, + jclass, jobject thisSV, jstring field_name) { auto* sv = getValue(env, thisSV); const char* field_name_cstr = env->GetStringUTFChars(field_name, JNI_FALSE); auto dataType = sv->getDataType(); @@ -1135,8 +1136,8 @@ JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rdf_1variant_1get_1da return createJavaObject(env, dt, "com/kuzudb/KuzuDataType", "dt_ref"); } -JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rdf_1variant_1get_1value( - JNIEnv* env, jclass, jobject thisValue) { +JNIEXPORT jobject JNICALL Java_com_kuzudb_KuzuNative_kuzu_1rdf_1variant_1get_1value(JNIEnv* env, + jclass, jobject thisValue) { auto* value = getValue(env, thisValue); auto logicalTypeId = RdfVariant::getLogicalTypeID(value); switch (logicalTypeId) { diff --git a/tools/nodejs_api/src_cpp/include/node_connection.h b/tools/nodejs_api/src_cpp/include/node_connection.h index 7a03cb59a8..7afeb5703e 100644 --- a/tools/nodejs_api/src_cpp/include/node_connection.h +++ b/tools/nodejs_api/src_cpp/include/node_connection.h @@ -43,7 +43,9 @@ class ConnectionInitAsyncWorker : public Napi::AsyncWorker { inline void Execute() override { try { nodeConnection->InitCppConnection(); - } catch (const std::exception& exc) { SetError(std::string(exc.what())); } + } catch (const std::exception& exc) { + SetError(std::string(exc.what())); + } } inline void OnOK() override { Callback().Call({Env().Null()}); } @@ -80,7 +82,9 @@ class ConnectionExecuteAsyncWorker : public Napi::AsyncWorker { SetError(result->getErrorMessage()); return; } - } catch (const std::exception& exc) { SetError(std::string(exc.what())); } + } catch (const std::exception& exc) { + SetError(std::string(exc.what())); + } } inline void OnOK() override { Callback().Call({Env().Null()}); } diff --git a/tools/nodejs_api/src_cpp/include/node_database.h b/tools/nodejs_api/src_cpp/include/node_database.h index 8bbb4ca79a..8971ab57bc 100644 --- a/tools/nodejs_api/src_cpp/include/node_database.h +++ b/tools/nodejs_api/src_cpp/include/node_database.h @@ -43,7 +43,9 @@ class DatabaseInitAsyncWorker : public Napi::AsyncWorker { try { nodeDatabase->InitCppDatabase(); - } catch (const std::exception& exc) { SetError(std::string(exc.what())); } + } catch (const std::exception& exc) { + SetError(std::string(exc.what())); + } } inline void OnOK() override { Callback().Call({Env().Null()}); } diff --git a/tools/nodejs_api/src_cpp/include/node_prepared_statement.h b/tools/nodejs_api/src_cpp/include/node_prepared_statement.h index 08e6efc780..6bad1944ba 100644 --- a/tools/nodejs_api/src_cpp/include/node_prepared_statement.h +++ b/tools/nodejs_api/src_cpp/include/node_prepared_statement.h @@ -29,8 +29,8 @@ class NodePreparedStatement : public Napi::ObjectWrap { class PreparedStatementInitAsyncWorker : public Napi::AsyncWorker { public: - PreparedStatementInitAsyncWorker( - Napi::Function& callback, NodePreparedStatement* nodePreparedStatement) + PreparedStatementInitAsyncWorker(Napi::Function& callback, + NodePreparedStatement* nodePreparedStatement) : AsyncWorker(callback), nodePreparedStatement(nodePreparedStatement) {} ~PreparedStatementInitAsyncWorker() override = default; @@ -38,7 +38,9 @@ class PreparedStatementInitAsyncWorker : public Napi::AsyncWorker { inline void Execute() override { try { nodePreparedStatement->InitCppPreparedStatement(); - } catch (const std::exception& exc) { SetError(std::string(exc.what())); } + } catch (const std::exception& exc) { + SetError(std::string(exc.what())); + } } inline void OnOK() override { Callback().Call({Env().Null()}); } diff --git a/tools/nodejs_api/src_cpp/include/node_query_result.h b/tools/nodejs_api/src_cpp/include/node_query_result.h index 6ef1f51f00..0fa171ae3d 100644 --- a/tools/nodejs_api/src_cpp/include/node_query_result.h +++ b/tools/nodejs_api/src_cpp/include/node_query_result.h @@ -36,8 +36,8 @@ enum GetColumnMetadataType { DATA_TYPE, NAME }; class NodeQueryResultGetColumnMetadataAsyncWorker : public Napi::AsyncWorker { public: - NodeQueryResultGetColumnMetadataAsyncWorker( - Napi::Function& callback, NodeQueryResult* nodeQueryResult, GetColumnMetadataType type) + NodeQueryResultGetColumnMetadataAsyncWorker(Napi::Function& callback, + NodeQueryResult* nodeQueryResult, GetColumnMetadataType type) : AsyncWorker(callback), nodeQueryResult(nodeQueryResult), type(type) {} ~NodeQueryResultGetColumnMetadataAsyncWorker() override = default; @@ -53,7 +53,9 @@ class NodeQueryResultGetColumnMetadataAsyncWorker : public Napi::AsyncWorker { } else { result = nodeQueryResult->queryResult->getColumnNames(); } - } catch (const std::exception& exc) { SetError(std::string(exc.what())); } + } catch (const std::exception& exc) { + SetError(std::string(exc.what())); + } } inline void OnOK() override { @@ -86,7 +88,9 @@ class NodeQueryResultGetNextAsyncWorker : public Napi::AsyncWorker { cppTuple.reset(); } cppTuple = nodeQueryResult->queryResult->getNext(); - } catch (const std::exception& exc) { SetError(std::string(exc.what())); } + } catch (const std::exception& exc) { + SetError(std::string(exc.what())); + } } inline void OnOK() override { diff --git a/tools/nodejs_api/src_cpp/include/node_util.h b/tools/nodejs_api/src_cpp/include/node_util.h index e8980f61d5..c84cac6f54 100644 --- a/tools/nodejs_api/src_cpp/include/node_util.h +++ b/tools/nodejs_api/src_cpp/include/node_util.h @@ -14,6 +14,6 @@ class Util { private: static Napi::Object ConvertNodeIdToNapiObject(const nodeID_t& nodeId, Napi::Env env); - static Value TransformNapiValue( - Napi::Value napiValue, LogicalType* expectedDataType, const std::string& key); + static Value TransformNapiValue(Napi::Value napiValue, LogicalType* expectedDataType, + const std::string& key); }; diff --git a/tools/nodejs_api/src_cpp/node_query_result.cpp b/tools/nodejs_api/src_cpp/node_query_result.cpp index 0ca3223460..bb595210f8 100644 --- a/tools/nodejs_api/src_cpp/node_query_result.cpp +++ b/tools/nodejs_api/src_cpp/node_query_result.cpp @@ -76,8 +76,8 @@ Napi::Value NodeQueryResult::GetColumnDataTypesAsync(const Napi::CallbackInfo& i Napi::Env env = info.Env(); Napi::HandleScope scope(env); auto callback = info[0].As(); - auto* asyncWorker = new NodeQueryResultGetColumnMetadataAsyncWorker( - callback, this, GetColumnMetadataType::DATA_TYPE); + auto* asyncWorker = new NodeQueryResultGetColumnMetadataAsyncWorker(callback, this, + GetColumnMetadataType::DATA_TYPE); asyncWorker->Queue(); return info.Env().Undefined(); } @@ -86,8 +86,8 @@ Napi::Value NodeQueryResult::GetColumnNamesAsync(const Napi::CallbackInfo& info) Napi::Env env = info.Env(); Napi::HandleScope scope(env); auto callback = info[0].As(); - auto* asyncWorker = new NodeQueryResultGetColumnMetadataAsyncWorker( - callback, this, GetColumnMetadataType::NAME); + auto* asyncWorker = new NodeQueryResultGetColumnMetadataAsyncWorker(callback, this, + GetColumnMetadataType::NAME); asyncWorker->Queue(); return info.Env().Undefined(); } diff --git a/tools/nodejs_api/src_cpp/node_util.cpp b/tools/nodejs_api/src_cpp/node_util.cpp index fd676a9fc3..39e8e7a606 100644 --- a/tools/nodejs_api/src_cpp/node_util.cpp +++ b/tools/nodejs_api/src_cpp/node_util.cpp @@ -303,8 +303,8 @@ Napi::Object Util::ConvertNodeIdToNapiObject(const nodeID_t& nodeId, Napi::Env e return napiObject; } -Value Util::TransformNapiValue( - Napi::Value napiValue, LogicalType* expectedDataType, const std::string& key) { +Value Util::TransformNapiValue(Napi::Value napiValue, LogicalType* expectedDataType, + const std::string& key) { auto logicalTypeId = expectedDataType->getLogicalTypeID(); switch (logicalTypeId) { case LogicalTypeID::BOOL: { @@ -461,8 +461,8 @@ Value Util::TransformNapiValue( auto microseconds = napiInterval * Interval::MICROS_PER_MSEC; auto intervalVal = interval_t(0, 0, microseconds); int64_t normalizedMonths, normalizedDays, normalizedMicros; - Interval::normalizeIntervalEntries( - intervalVal, normalizedMonths, normalizedDays, normalizedMicros); + Interval::normalizeIntervalEntries(intervalVal, normalizedMonths, normalizedDays, + normalizedMicros); auto normalizedInterval = interval_t(normalizedMonths, normalizedDays, normalizedMicros); return Value(normalizedInterval); } diff --git a/tools/python_api/src_cpp/cached_import/py_cached_import.cpp b/tools/python_api/src_cpp/cached_import/py_cached_import.cpp index e0317ab9fd..0c4e1c5d36 100644 --- a/tools/python_api/src_cpp/cached_import/py_cached_import.cpp +++ b/tools/python_api/src_cpp/cached_import/py_cached_import.cpp @@ -3,8 +3,8 @@ namespace kuzu { PythonCachedImport::~PythonCachedImport() { - py::gil_scoped_acquire acquire; - allObjects.clear(); + py::gil_scoped_acquire acquire; + allObjects.clear(); } py::handle PythonCachedImport::addToCache(py::object obj) { diff --git a/tools/python_api/src_cpp/cached_import/py_cached_item.cpp b/tools/python_api/src_cpp/cached_import/py_cached_item.cpp index ebbc1ecb39..7e6c150da4 100644 --- a/tools/python_api/src_cpp/cached_import/py_cached_item.cpp +++ b/tools/python_api/src_cpp/cached_import/py_cached_item.cpp @@ -1,6 +1,5 @@ #include "cached_import/py_cached_item.h" - #include "cached_import/py_cached_import.h" #include "common/exception/runtime.h" diff --git a/tools/python_api/src_cpp/include/cached_import/py_cached_item.h b/tools/python_api/src_cpp/include/cached_import/py_cached_item.h index 159220e79b..bcaf1566a0 100644 --- a/tools/python_api/src_cpp/include/cached_import/py_cached_item.h +++ b/tools/python_api/src_cpp/include/cached_import/py_cached_item.h @@ -13,7 +13,7 @@ class PythonCachedItem { : name(name), parent(parent), loaded(false) {} virtual ~PythonCachedItem() = default; - bool isLoaded() const {return loaded;} + bool isLoaded() const { return loaded; } py::handle operator()(); private: diff --git a/tools/python_api/src_cpp/include/cached_import/py_cached_modules.h b/tools/python_api/src_cpp/include/cached_import/py_cached_modules.h index 28146a0cba..8f98ab13bf 100644 --- a/tools/python_api/src_cpp/include/cached_import/py_cached_modules.h +++ b/tools/python_api/src_cpp/include/cached_import/py_cached_modules.h @@ -7,8 +7,9 @@ namespace kuzu { class DateTimeCachedItem : public PythonCachedItem { public: - DateTimeCachedItem() : PythonCachedItem("datetime"), date("date", this), - datetime("datetime", this), timedelta("timedelta", this) {} + DateTimeCachedItem() + : PythonCachedItem("datetime"), date("date", this), datetime("datetime", this), + timedelta("timedelta", this) {} PythonCachedItem date; PythonCachedItem datetime; @@ -35,7 +36,7 @@ class NumpyMaCachedItem : public PythonCachedItem { public: NumpyMaCachedItem() : PythonCachedItem("numpy.ma"), masked_array("masked_array", this) {} - + PythonCachedItem masked_array; }; @@ -43,31 +44,32 @@ class PandasCachedItem : public PythonCachedItem { class SeriesCachedItem : public PythonCachedItem { public: - explicit SeriesCachedItem(PythonCachedItem* parent): PythonCachedItem("series", parent), - Series("Series", this) {} + explicit SeriesCachedItem(PythonCachedItem* parent) + : PythonCachedItem("series", parent), Series("Series", this) {} PythonCachedItem Series; }; class CoreCachedItem : public PythonCachedItem { public: - explicit CoreCachedItem(PythonCachedItem* parent): PythonCachedItem("core", parent), - series(this) {} + explicit CoreCachedItem(PythonCachedItem* parent) + : PythonCachedItem("core", parent), series(this) {} SeriesCachedItem series; }; class DataFrameCachedItem : public PythonCachedItem { public: - explicit DataFrameCachedItem(PythonCachedItem* parent): PythonCachedItem("DataFrame", parent), - from_dict("from_dict", this) {} - + explicit DataFrameCachedItem(PythonCachedItem* parent) + : PythonCachedItem("DataFrame", parent), from_dict("from_dict", this) {} + PythonCachedItem from_dict; }; public: - PandasCachedItem() : PythonCachedItem("pandas"), ArrowDtype("ArrowDtype", this), core(this), DataFrame(this), - NA("NA", this), NaT("NaT", this) {} + PandasCachedItem() + : PythonCachedItem("pandas"), ArrowDtype("ArrowDtype", this), core(this), DataFrame(this), + NA("NA", this), NaT("NaT", this) {} PythonCachedItem ArrowDtype; CoreCachedItem core; @@ -80,24 +82,25 @@ class PyarrowCachedItem : public PythonCachedItem { class RecordBatchCachedItem : public PythonCachedItem { public: - explicit RecordBatchCachedItem(PythonCachedItem* parent): PythonCachedItem("RecordBatch", parent), - _import_from_c("_import_from_c", this) {} + explicit RecordBatchCachedItem(PythonCachedItem* parent) + : PythonCachedItem("RecordBatch", parent), _import_from_c("_import_from_c", this) {} PythonCachedItem _import_from_c; }; class SchemaCachedItem : public PythonCachedItem { public: - explicit SchemaCachedItem(PythonCachedItem* parent): PythonCachedItem("Schema", parent), - _import_from_c("_import_from_c", this) {} + explicit SchemaCachedItem(PythonCachedItem* parent) + : PythonCachedItem("Schema", parent), _import_from_c("_import_from_c", this) {} PythonCachedItem _import_from_c; }; class TableCachedItem : public PythonCachedItem { public: - explicit TableCachedItem(PythonCachedItem* parent): PythonCachedItem("Table", parent), - from_batches("from_batches", this), from_pandas("from_pandas", this) {} + explicit TableCachedItem(PythonCachedItem* parent) + : PythonCachedItem("Table", parent), from_batches("from_batches", this), + from_pandas("from_pandas", this) {} PythonCachedItem from_batches; PythonCachedItem from_pandas; @@ -105,8 +108,8 @@ class PyarrowCachedItem : public PythonCachedItem { class LibCachedItem : public PythonCachedItem { public: - explicit LibCachedItem(PythonCachedItem* parent): PythonCachedItem("lib", parent), - RecordBatch(this), Schema(this), Table(this) {} + explicit LibCachedItem(PythonCachedItem* parent) + : PythonCachedItem("lib", parent), RecordBatch(this), Schema(this), Table(this) {} RecordBatchCachedItem RecordBatch; SchemaCachedItem Schema; @@ -114,7 +117,7 @@ class PyarrowCachedItem : public PythonCachedItem { }; public: - PyarrowCachedItem(): PythonCachedItem("pyarrow"), lib(this) {} + PyarrowCachedItem() : PythonCachedItem("pyarrow"), lib(this) {} LibCachedItem lib; }; diff --git a/tools/python_api/src_cpp/include/numpy/numpy_scan.h b/tools/python_api/src_cpp/include/numpy/numpy_scan.h index 21acb0f82e..4a91dc3b41 100644 --- a/tools/python_api/src_cpp/include/numpy/numpy_scan.h +++ b/tools/python_api/src_cpp/include/numpy/numpy_scan.h @@ -10,8 +10,8 @@ struct PandasColumnBindData; struct NumpyScan { static void scan(PandasColumnBindData* bindData, uint64_t count, uint64_t offset, common::ValueVector* outputVector); - static void scanObjectColumn( - PyObject** col, uint64_t count, uint64_t offset, common::ValueVector* outputVector); + static void scanObjectColumn(PyObject** col, uint64_t count, uint64_t offset, + common::ValueVector* outputVector); }; } // namespace kuzu diff --git a/tools/python_api/src_cpp/include/pandas/pandas_bind.h b/tools/python_api/src_cpp/include/pandas/pandas_bind.h index ed894a4a25..5a4eea7561 100644 --- a/tools/python_api/src_cpp/include/pandas/pandas_bind.h +++ b/tools/python_api/src_cpp/include/pandas/pandas_bind.h @@ -2,8 +2,8 @@ #include "numpy/numpy_type.h" #include "pandas_column.h" -#include "pybind_include.h" #include "py_object_container.h" +#include "pybind_include.h" namespace kuzu { @@ -38,8 +38,7 @@ struct PandasColumnBindData { struct Pandas { static void bind(py::handle dfToBind, std::vector>& columnBindData, - std::vector& returnTypes, - std::vector& names); + std::vector& returnTypes, std::vector& names); }; } // namespace kuzu diff --git a/tools/python_api/src_cpp/include/pandas/pandas_scan.h b/tools/python_api/src_cpp/include/pandas/pandas_scan.h index 7c36db5f1d..ddeb973d97 100644 --- a/tools/python_api/src_cpp/include/pandas/pandas_scan.h +++ b/tools/python_api/src_cpp/include/pandas/pandas_scan.h @@ -1,9 +1,9 @@ #pragma once #include "function/scalar_function.h" -#include "function/table_functions.h" #include "function/table/bind_data.h" #include "function/table/scan_functions.h" +#include "function/table_functions.h" #include "pandas_bind.h" #include "pybind_include.h" @@ -27,7 +27,7 @@ struct PandasScanSharedState : public function::BaseScanSharedState { struct PandasScanFunction { static constexpr const char* name = "READ_PANDAS"; - + static function::function_set getFunctionSet(); }; @@ -50,8 +50,8 @@ struct PandasScanFunctionData : public function::TableFuncBindData { std::vector> copyColumnBindData() const; std::unique_ptr copy() const override { - return std::make_unique( - columnTypes, columnNames, df, numRows, copyColumnBindData()); + return std::make_unique(columnTypes, columnNames, df, numRows, + copyColumnBindData()); } }; diff --git a/tools/python_api/src_cpp/include/py_connection.h b/tools/python_api/src_cpp/include/py_connection.h index 679f026e2d..0841447496 100644 --- a/tools/python_api/src_cpp/include/py_connection.h +++ b/tools/python_api/src_cpp/include/py_connection.h @@ -16,8 +16,8 @@ class PyConnection { void setQueryTimeout(uint64_t timeoutInMS); - std::unique_ptr execute( - PyPreparedStatement* preparedStatement, const py::dict& params); + std::unique_ptr execute(PyPreparedStatement* preparedStatement, + const py::dict& params); void setMaxNumThreadForExec(uint64_t numThreads); diff --git a/tools/python_api/src_cpp/include/py_database.h b/tools/python_api/src_cpp/include/py_database.h index 0cc9265e9c..86d81f9bfd 100644 --- a/tools/python_api/src_cpp/include/py_database.h +++ b/tools/python_api/src_cpp/include/py_database.h @@ -1,8 +1,8 @@ #pragma once +#include "cached_import/py_cached_import.h" #include "main/kuzu.h" #include "main/storage_driver.h" -#include "cached_import/py_cached_import.h" #include "pybind_include.h" // IWYU pragma: keep (used for py:: namespace) #define PYBIND11_DETAILED_ERROR_MESSAGES using namespace kuzu::main; diff --git a/tools/python_api/src_cpp/include/py_object_container.h b/tools/python_api/src_cpp/include/py_object_container.h index 40b6f07f6b..c9b65f4e25 100644 --- a/tools/python_api/src_cpp/include/py_object_container.h +++ b/tools/python_api/src_cpp/include/py_object_container.h @@ -1,8 +1,8 @@ #pragma once #include -#include "common/assert.h" +#include "common/assert.h" #include "pybind_include.h" namespace kuzu { diff --git a/tools/python_api/src_cpp/include/pyarrow/pyarrow_scan.h b/tools/python_api/src_cpp/include/pyarrow/pyarrow_scan.h index 4f477cfc91..763a3653b5 100644 --- a/tools/python_api/src_cpp/include/pyarrow/pyarrow_scan.h +++ b/tools/python_api/src_cpp/include/pyarrow/pyarrow_scan.h @@ -21,8 +21,8 @@ struct PyArrowTableScanSharedState final : public function::BaseScanSharedState uint64_t currentChunk; std::mutex lock; - PyArrowTableScanSharedState( - uint64_t numRows, std::vector> chunks) + PyArrowTableScanSharedState(uint64_t numRows, + std::vector> chunks) : BaseScanSharedState{numRows}, chunks{std::move(chunks)}, currentChunk{0} {} ArrowArrayWrapper* getNextChunk(); @@ -44,14 +44,14 @@ struct PyArrowTableScanFunctionData final : public function::TableFuncBindData { std::unique_ptr copy() const override { py::gil_scoped_acquire acquire; // the schema is considered immutable so copying it by copying the shared_ptr is fine. - return std::make_unique( - columnTypes, schema, columnNames, arrowArrayBatches, numRows); + return std::make_unique(columnTypes, schema, columnNames, + arrowArrayBatches, numRows); } }; struct PyArrowTableScanFunction { static constexpr const char* name = "READ_PYARROW"; - + static function::function_set getFunctionSet(); static function::TableFunction getFunction(); diff --git a/tools/python_api/src_cpp/kuzu_binding.cpp b/tools/python_api/src_cpp/kuzu_binding.cpp index 69a51a4dfc..83029deded 100644 --- a/tools/python_api/src_cpp/kuzu_binding.cpp +++ b/tools/python_api/src_cpp/kuzu_binding.cpp @@ -9,9 +9,7 @@ void bind(py::module& m) { PyConnection::initialize(m); PyPreparedStatement::initialize(m); PyQueryResult::initialize(m); - auto cleanImportCache = []() { - kuzu::importCache.reset(); - }; + auto cleanImportCache = []() { kuzu::importCache.reset(); }; m.add_object("_clean_import_cache", py::capsule(cleanImportCache)); } diff --git a/tools/python_api/src_cpp/numpy/numpy_scan.cpp b/tools/python_api/src_cpp/numpy/numpy_scan.cpp index 227749b2f2..01e0cd0573 100644 --- a/tools/python_api/src_cpp/numpy/numpy_scan.cpp +++ b/tools/python_api/src_cpp/numpy/numpy_scan.cpp @@ -12,15 +12,15 @@ namespace kuzu { using namespace kuzu::common; template -void ScanNumpyColumn( - py::array& npArray, uint64_t offset, ValueVector* outputVector, uint64_t count) { +void ScanNumpyColumn(py::array& npArray, uint64_t offset, ValueVector* outputVector, + uint64_t count) { auto srcData = (T*)npArray.data(); memcpy(outputVector->getData(), srcData + offset, count * sizeof(T)); } template -void scanNumpyMasked( - PandasColumnBindData* bindData, uint64_t count, uint64_t offset, ValueVector* outputVector) { +void scanNumpyMasked(PandasColumnBindData* bindData, uint64_t count, uint64_t offset, + ValueVector* outputVector) { KU_ASSERT(bindData->pandasCol->getBackEnd() == PandasColumnBackend::NUMPY); auto& npColumn = reinterpret_cast(*bindData->pandasCol); ScanNumpyColumn(npColumn.array, offset, outputVector, count); @@ -37,8 +37,8 @@ void setNullIfNan(T value, uint64_t pos, ValueVector* outputVector) { } template -void ScanNumpyFpColumn( - const T* srcData, uint64_t count, uint64_t offset, ValueVector* outputVector) { +void ScanNumpyFpColumn(const T* srcData, uint64_t count, uint64_t offset, + ValueVector* outputVector) { memcpy(outputVector->getData(), srcData + offset, count * sizeof(T)); for (auto i = 0u; i < count; i++) { setNullIfNan(outputVector->getValue(i), i, outputVector); @@ -46,8 +46,8 @@ void ScanNumpyFpColumn( } template -static void appendPythonUnicode( - T* codepoints, uint64_t codepointLength, ValueVector* vectorToAppend, uint64_t pos) { +static void appendPythonUnicode(T* codepoints, uint64_t codepointLength, + ValueVector* vectorToAppend, uint64_t pos) { uint64_t utf8StrLen = 0; for (auto i = 0u; i < codepointLength; i++) { auto len = utf8proc::Utf8Proc::codepointLength(int(codepoints[i])); @@ -102,12 +102,12 @@ void NumpyScan::scan(PandasColumnBindData* bindData, uint64_t count, uint64_t of scanNumpyMasked(bindData, count, offset, outputVector); break; case NumpyNullableType::FLOAT_32: - ScanNumpyFpColumn( - reinterpret_cast(array.data()), count, offset, outputVector); + ScanNumpyFpColumn(reinterpret_cast(array.data()), count, offset, + outputVector); break; case NumpyNullableType::FLOAT_64: - ScanNumpyFpColumn( - reinterpret_cast(array.data()), count, offset, outputVector); + ScanNumpyFpColumn(reinterpret_cast(array.data()), count, offset, + outputVector); break; case NumpyNullableType::DATETIME_S: case NumpyNullableType::DATETIME_MS: @@ -177,8 +177,8 @@ void NumpyScan::scan(PandasColumnBindData* bindData, uint64_t count, uint64_t of } else { auto unicodeObj = reinterpret_cast(val); if (unicodeObj->utf8) { - dstData[i] = ku_string_t( - reinterpret_cast(unicodeObj->utf8), unicodeObj->utf8_length); + dstData[i] = ku_string_t(reinterpret_cast(unicodeObj->utf8), + unicodeObj->utf8_length); } else if (PyStrUtil::isPyUnicodeCompact(unicodeObj) && !PyStrUtil::isPyUnicodeASCII(unicodeObj)) { auto kind = PyStrUtil::getPyUnicodeKind(strHandle); @@ -221,8 +221,8 @@ void scanNumpyObject(PyObject* object, uint64_t offset, common::ValueVector* out transformPythonValue(outputVector, offset, object); } -void NumpyScan::scanObjectColumn( - PyObject** col, uint64_t count, uint64_t offset, common::ValueVector* outputVector) { +void NumpyScan::scanObjectColumn(PyObject** col, uint64_t count, uint64_t offset, + common::ValueVector* outputVector) { py::gil_scoped_acquire gil; auto srcPtr = col + offset; for (auto i = 0u; i < count; i++) { diff --git a/tools/python_api/src_cpp/numpy/numpy_type.cpp b/tools/python_api/src_cpp/numpy/numpy_type.cpp index 263f3594ce..f74fad88e0 100644 --- a/tools/python_api/src_cpp/numpy/numpy_type.cpp +++ b/tools/python_api/src_cpp/numpy/numpy_type.cpp @@ -7,7 +7,7 @@ namespace kuzu { using namespace kuzu::common; static bool isDateTime(NumpyNullableType type) { - switch(type) { + switch (type) { case NumpyNullableType::DATETIME_US: case NumpyNullableType::DATETIME_S: case NumpyNullableType::DATETIME_NS: diff --git a/tools/python_api/src_cpp/pandas/pandas_analyzer.cpp b/tools/python_api/src_cpp/pandas/pandas_analyzer.cpp index 0e8a35b3c6..a778e07996 100644 --- a/tools/python_api/src_cpp/pandas/pandas_analyzer.cpp +++ b/tools/python_api/src_cpp/pandas/pandas_analyzer.cpp @@ -1,7 +1,7 @@ #include "pandas/pandas_analyzer.h" -#include "function/built_in_function_utils.h" #include "cached_import/py_cached_import.h" +#include "function/built_in_function_utils.h" #include "py_conversion.h" namespace kuzu { @@ -22,8 +22,8 @@ static bool upgradeType(common::LogicalType& left, const common::LogicalType& ri common::LogicalTypeID::ANY))) { return true; } - auto leftToRightCost = - function::BuiltInFunctionsUtils::getCastCost(left.getLogicalTypeID(), right.getLogicalTypeID()); + auto leftToRightCost = function::BuiltInFunctionsUtils::getCastCost(left.getLogicalTypeID(), + right.getLogicalTypeID()); if (leftToRightCost != common::UNDEFINED_CAST_COST) { left = right; } else { diff --git a/tools/python_api/src_cpp/pandas/pandas_bind.cpp b/tools/python_api/src_cpp/pandas/pandas_bind.cpp index bb363daa4f..828dc9b962 100644 --- a/tools/python_api/src_cpp/pandas/pandas_bind.cpp +++ b/tools/python_api/src_cpp/pandas/pandas_bind.cpp @@ -41,8 +41,8 @@ struct PandasDataFrameBind { py::object getter; }; -static common::LogicalType bindColumn( - PandasBindColumn& bindColumn, PandasColumnBindData* bindData) { +static common::LogicalType bindColumn(PandasBindColumn& bindColumn, + PandasColumnBindData* bindData) { common::LogicalType columnType; auto& column = bindColumn.handle; diff --git a/tools/python_api/src_cpp/pandas/pandas_scan.cpp b/tools/python_api/src_cpp/pandas/pandas_scan.cpp index d43b37678c..7bec99a500 100644 --- a/tools/python_api/src_cpp/pandas/pandas_scan.cpp +++ b/tools/python_api/src_cpp/pandas/pandas_scan.cpp @@ -1,12 +1,12 @@ #include "pandas/pandas_scan.h" -#include "pyarrow/pyarrow_scan.h" -#include "function/table/bind_input.h" +#include "binder/expression/function_expression.h" #include "cached_import/py_cached_import.h" +#include "function/table/bind_input.h" #include "numpy/numpy_scan.h" #include "py_connection.h" +#include "pyarrow/pyarrow_scan.h" #include "pybind11/pytypes.h" -#include "binder/expression/function_expression.h" using namespace kuzu::function; using namespace kuzu::common; @@ -14,8 +14,8 @@ using namespace kuzu::catalog; namespace kuzu { -std::unique_ptr bindFunc( - main::ClientContext* /*context*/, TableFuncBindInput* input) { +std::unique_ptr bindFunc(main::ClientContext* /*context*/, + TableFuncBindInput* input) { py::gil_scoped_acquire acquire; py::handle df(reinterpret_cast(input->inputs[0].getValue())); std::vector> columnBindData; @@ -29,13 +29,14 @@ std::unique_ptr bindFunc( auto columns = py::list(df.attr("keys")()); auto getFunc = df.attr("__getitem__"); auto numRows = py::len(getFunc(columns[0])); - return std::make_unique( - std::move(returnTypes), std::move(names), df, numRows, std::move(columnBindData)); + return std::make_unique(std::move(returnTypes), std::move(names), df, + numRows, std::move(columnBindData)); } -bool sharedStateNext(const TableFuncBindData* /*bindData*/, - PandasScanLocalState* localState, TableFuncSharedState* sharedState) { - auto pandasSharedState = ku_dynamic_cast(sharedState); +bool sharedStateNext(const TableFuncBindData* /*bindData*/, PandasScanLocalState* localState, + TableFuncSharedState* sharedState) { + auto pandasSharedState = + ku_dynamic_cast(sharedState); std::lock_guard lck{pandasSharedState->lock}; if (pandasSharedState->position >= pandasSharedState->numRows) { return false; @@ -63,12 +64,13 @@ std::unique_ptr initSharedState( throw RuntimeException("PandasScan called but GIL was already held!"); } // LCOV_EXCL_STOP - auto scanBindData = ku_dynamic_cast(input.bindData); + auto scanBindData = + ku_dynamic_cast(input.bindData); return std::make_unique(scanBindData->numRows); } -void pandasBackendScanSwitch( - PandasColumnBindData* bindData, uint64_t count, uint64_t offset, ValueVector* outputVector) { +void pandasBackendScanSwitch(PandasColumnBindData* bindData, uint64_t count, uint64_t offset, + ValueVector* outputVector) { auto backend = bindData->pandasCol->getBackEnd(); switch (backend) { case PandasColumnBackend::NUMPY: { @@ -79,11 +81,13 @@ void pandasBackendScanSwitch( } } -offset_t tableFunc( - TableFuncInput& input, TableFuncOutput& output) { - auto pandasScanData = ku_dynamic_cast(input.bindData); - auto pandasLocalState = ku_dynamic_cast(input.localState); - auto pandasSharedState = ku_dynamic_cast(input.sharedState); +offset_t tableFunc(TableFuncInput& input, TableFuncOutput& output) { + auto pandasScanData = + ku_dynamic_cast(input.bindData); + auto pandasLocalState = + ku_dynamic_cast(input.localState); + auto pandasSharedState = + ku_dynamic_cast(input.sharedState); if (pandasLocalState->start >= pandasLocalState->end) { if (!sharedStateNext(input.bindData, pandasLocalState, input.sharedState)) { @@ -102,7 +106,8 @@ offset_t tableFunc( return numValuesToOutput; } -std::vector> PandasScanFunctionData::copyColumnBindData() const { +std::vector> +PandasScanFunctionData::copyColumnBindData() const { std::vector> result; result.reserve(columnBindData.size()); for (auto& bindData : columnBindData) { @@ -112,12 +117,12 @@ std::vector> PandasScanFunctionData::copyC } static double progressFunc(TableFuncSharedState* sharedState) { - auto pandasSharedState = ku_dynamic_cast(sharedState); + auto pandasSharedState = + ku_dynamic_cast(sharedState); if (pandasSharedState->numRows == 0) { - return 0.0; - } - return static_cast(pandasSharedState->numReadRows) / - pandasSharedState->numRows; + return 0.0; + } + return static_cast(pandasSharedState->numReadRows) / pandasSharedState->numRows; } static TableFunction getFunction() { @@ -131,19 +136,19 @@ function_set PandasScanFunction::getFunctionSet() { return functionSet; } -static bool isPyArrowBacked(const py::handle &df) { - py::list dtypes = df.attr("dtypes"); - if (dtypes.empty()) { - return false; - } - - auto arrow_dtype = importCache->pandas.ArrowDtype(); - for (auto &dtype : dtypes) { - if (py::isinstance(dtype, arrow_dtype)) { - return true; - } - } - return false; +static bool isPyArrowBacked(const py::handle& df) { + py::list dtypes = df.attr("dtypes"); + if (dtypes.empty()) { + return false; + } + + auto arrow_dtype = importCache->pandas.ArrowDtype(); + for (auto& dtype : dtypes) { + if (py::isinstance(dtype, arrow_dtype)) { + return true; + } + } + return false; } static std::unique_ptr tryReplacePD(py::dict& dict, py::str& objectName) { diff --git a/tools/python_api/src_cpp/py_connection.cpp b/tools/python_api/src_cpp/py_connection.cpp index b98c7bac3a..49d122d2ef 100644 --- a/tools/python_api/src_cpp/py_connection.cpp +++ b/tools/python_api/src_cpp/py_connection.cpp @@ -2,8 +2,8 @@ #include -#include "common/constants.h" #include "cached_import/py_cached_import.h" +#include "common/constants.h" #include "common/string_format.h" #include "common/types/uuid.h" #include "datetime.h" // from Python @@ -48,8 +48,8 @@ void PyConnection::setQueryTimeout(uint64_t timeoutInMS) { static std::unordered_map> transformPythonParameters( const py::dict& params, Connection* conn); -std::unique_ptr PyConnection::execute( - PyPreparedStatement* preparedStatement, const py::dict& params) { +std::unique_ptr PyConnection::execute(PyPreparedStatement* preparedStatement, + const py::dict& params) { auto parameters = transformPythonParameters(params, conn.get()); py::gil_scoped_release release; auto queryResult = @@ -189,20 +189,18 @@ static bool canCastPyLogicalType(const LogicalType& from, const LogicalType& to) } auto fromKeyType = MapType::getKeyType(&from), fromValueType = MapType::getValueType(&to); auto toKeyType = MapType::getKeyType(&to), toValueType = MapType::getValueType(&to); - return - (canCastPyLogicalType(*fromKeyType, *toKeyType) || - canCastPyLogicalType(*toKeyType, *fromKeyType)) && - (canCastPyLogicalType(*fromValueType, *toValueType) || - canCastPyLogicalType(*toValueType, *fromValueType)); + return (canCastPyLogicalType(*fromKeyType, *toKeyType) || + canCastPyLogicalType(*toKeyType, *fromKeyType)) && + (canCastPyLogicalType(*fromValueType, *toValueType) || + canCastPyLogicalType(*toValueType, *fromValueType)); } else if (from.getLogicalTypeID() == LogicalTypeID::LIST) { if (to.getLogicalTypeID() != LogicalTypeID::LIST) { return false; } - return canCastPyLogicalType( - *ListType::getChildType(&from), *ListType::getChildType(&to)); + return canCastPyLogicalType(*ListType::getChildType(&from), *ListType::getChildType(&to)); } else { - auto castCost = function::BuiltInFunctionsUtils::getCastCost( - from.getLogicalTypeID(), to.getLogicalTypeID()); + auto castCost = function::BuiltInFunctionsUtils::getCastCost(from.getLogicalTypeID(), + to.getLogicalTypeID()); return castCost != UNDEFINED_CAST_COST; } return false; @@ -210,15 +208,18 @@ static bool canCastPyLogicalType(const LogicalType& from, const LogicalType& to) static void tryConvertPyLogicalType(LogicalType& from, LogicalType& to); -static std::unique_ptr castPyLogicalType(const LogicalType& from, const LogicalType& to) { +static std::unique_ptr castPyLogicalType(const LogicalType& from, + const LogicalType& to) { // assumes from can cast to to if (from.getLogicalTypeID() == LogicalTypeID::MAP) { auto fromKeyType = MapType::getKeyType(&from), fromValueType = MapType::getValueType(&from); auto toKeyType = MapType::getKeyType(&to), toValueType = MapType::getValueType(&to); auto outputKeyType = canCastPyLogicalType(*fromKeyType, *toKeyType) ? - castPyLogicalType(*fromKeyType, *toKeyType) : castPyLogicalType(*toKeyType, *fromKeyType); + castPyLogicalType(*fromKeyType, *toKeyType) : + castPyLogicalType(*toKeyType, *fromKeyType); auto outputValueType = canCastPyLogicalType(*fromValueType, *toValueType) ? - castPyLogicalType(*fromValueType, *toValueType) : castPyLogicalType(*toValueType, *fromValueType); + castPyLogicalType(*fromValueType, *toValueType) : + castPyLogicalType(*toValueType, *fromValueType); return LogicalType::MAP(std::move(outputKeyType), std::move(outputValueType)); } return std::make_unique(to); @@ -230,9 +231,9 @@ void tryConvertPyLogicalType(LogicalType& from, LogicalType& to) { } else if (canCastPyLogicalType(to, from)) { to = *castPyLogicalType(to, from); } else { - throw RuntimeException(stringFormat( - "Cannot convert Python object to Kuzu value : {} is incompatible with {}", - from.toString(), to.toString())); + throw RuntimeException( + stringFormat("Cannot convert Python object to Kuzu value : {} is incompatible with {}", + from.toString(), to.toString())); } } @@ -272,7 +273,7 @@ static std::unique_ptr pyLogicalType(py::handle val) { auto childKeyType = LogicalType::ANY(), childValueType = LogicalType::ANY(); for (auto child : dict) { auto curChildKeyType = pyLogicalType(child.first), - curChildValueType = pyLogicalType(child.second); + curChildValueType = pyLogicalType(child.second); tryConvertPyLogicalType(*childKeyType, *curChildKeyType); tryConvertPyLogicalType(*childValueType, *curChildValueType); } @@ -355,21 +356,21 @@ static Value transformPythonValueAs(py::handle val, const LogicalType* type) { case LogicalTypeID::MAP: { py::dict dict = py::reinterpret_borrow(val); std::vector> children; - auto childKeyType = MapType::getKeyType(type), - childValueType = MapType::getValueType(type); + auto childKeyType = MapType::getKeyType(type), childValueType = MapType::getValueType(type); for (auto child : dict) { // type construction is inefficient, we have to create duplicates because it asks for // a unique ptr std::vector fields; - fields.emplace_back( - InternalKeyword::MAP_KEY, std::make_unique(*childKeyType)); - fields.emplace_back( - InternalKeyword::MAP_VALUE, std::make_unique(*childValueType)); + fields.emplace_back(InternalKeyword::MAP_KEY, + std::make_unique(*childKeyType)); + fields.emplace_back(InternalKeyword::MAP_VALUE, + std::make_unique(*childValueType)); std::vector> structValues; - structValues.push_back(std::make_unique(transformPythonValueAs(child.first, childKeyType))); - structValues.push_back(std::make_unique(transformPythonValueAs(child.second, childValueType))); - children.push_back(std::make_unique( - LogicalType::STRUCT(std::move(fields)), + structValues.push_back( + std::make_unique(transformPythonValueAs(child.first, childKeyType))); + structValues.push_back( + std::make_unique(transformPythonValueAs(child.second, childValueType))); + children.push_back(std::make_unique(LogicalType::STRUCT(std::move(fields)), std::move(structValues))); } return Value(std::make_unique(*type), std::move(children)); @@ -377,7 +378,7 @@ static Value transformPythonValueAs(py::handle val, const LogicalType* type) { // LCOV_EXCL_START default: KU_UNREACHABLE; - // LCOV_EXCL_STOP + // LCOV_EXCL_STOP } } diff --git a/tools/python_api/src_cpp/py_conversion.cpp b/tools/python_api/src_cpp/py_conversion.cpp index bad439c29d..37b9a9eebe 100644 --- a/tools/python_api/src_cpp/py_conversion.cpp +++ b/tools/python_api/src_cpp/py_conversion.cpp @@ -1,7 +1,7 @@ #include "py_conversion.h" -#include "common/type_utils.h" #include "cached_import/py_cached_import.h" +#include "common/type_utils.h" namespace kuzu { diff --git a/tools/python_api/src_cpp/py_database.cpp b/tools/python_api/src_cpp/py_database.cpp index b99a5968b7..253130bc59 100644 --- a/tools/python_api/src_cpp/py_database.cpp +++ b/tools/python_api/src_cpp/py_database.cpp @@ -1,13 +1,11 @@ #include "include/py_database.h" -#include "include/cached_import/py_cached_import.h" -#include "pandas/pandas_scan.h" -#include "pyarrow/pyarrow_scan.h" - #include +#include "include/cached_import/py_cached_import.h" #include "main/version.h" #include "pandas/pandas_scan.h" +#include "pyarrow/pyarrow_scan.h" using namespace kuzu::common; @@ -50,7 +48,8 @@ PyDatabase::PyDatabase(const std::string& databasePath, uint64_t bufferPoolSize, auto systemConfig = SystemConfig(bufferPoolSize, maxNumThreads, compression, readOnly, maxDBSize); database = std::make_unique(databasePath, systemConfig); - database->addBuiltInFunction(kuzu::PandasScanFunction::name, kuzu::PandasScanFunction::getFunctionSet()); + database->addBuiltInFunction(kuzu::PandasScanFunction::name, + kuzu::PandasScanFunction::getFunctionSet()); storageDriver = std::make_unique(database.get()); py::gil_scoped_acquire acquire; if (kuzu::importCache.get() == nullptr) { diff --git a/tools/python_api/src_cpp/py_query_result.cpp b/tools/python_api/src_cpp/py_query_result.cpp index fd8eab765b..1765dad69a 100644 --- a/tools/python_api/src_cpp/py_query_result.cpp +++ b/tools/python_api/src_cpp/py_query_result.cpp @@ -2,6 +2,7 @@ #include +#include "cached_import/py_cached_import.h" #include "common/arrow/arrow_converter.h" #include "common/exception/not_implemented.h" #include "common/types/uuid.h" @@ -9,15 +10,14 @@ #include "common/types/value/node.h" #include "common/types/value/rel.h" #include "datetime.h" // python lib -#include "cached_import/py_cached_import.h" #include "include/py_query_result_converter.h" using namespace kuzu::common; using kuzu::importCache; #define PyDateTimeTZ_FromDateAndTime(year, month, day, hour, min, sec, usec, timezone) \ - PyDateTimeAPI->DateTime_FromDateAndTime( \ - year, month, day, hour, min, sec, usec, timezone, PyDateTimeAPI->DateTimeType) + PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, min, sec, usec, timezone, \ + PyDateTimeAPI->DateTimeType) void PyQueryResult::initialize(py::handle& m) { py::class_(m, "result") @@ -128,7 +128,7 @@ py::object convertRdfVariantToPyObject(const Value& value) { auto intervalVal = RdfVariant::getValue(&value); auto days = Interval::DAYS_PER_MONTH * intervalVal.months + intervalVal.days; return py::cast(importCache->datetime.timedelta()(py::arg("days") = days, - py::arg("microseconds") = intervalVal.micros)); + py::arg("microseconds") = intervalVal.micros)); } default: { KU_UNREACHABLE; @@ -173,7 +173,7 @@ py::object PyQueryResult::convertValueToPyObject(const Value& value) { case LogicalTypeID::INT128: { kuzu::common::int128_t result = value.getValue(); std::string int128_string = kuzu::common::Int128_t::ToString(result); - + auto Decimal = importCache->decimal.Decimal(); py::object largeInt = Decimal(int128_string); return largeInt; @@ -217,8 +217,8 @@ py::object PyQueryResult::convertValueToPyObject(const Value& value) { Date::convert(date, year, month, day); Time::convert(time, hour, min, sec, micros); - return py::cast(PyDateTimeTZ_FromDateAndTime( - year, month, day, hour, min, sec, micros, PyDateTime_TimeZone_UTC)); + return py::cast(PyDateTimeTZ_FromDateAndTime(year, month, day, hour, min, sec, + micros, PyDateTime_TimeZone_UTC)); } case LogicalTypeID::TIMESTAMP_NS: { timestamp_t timestampVal = @@ -238,9 +238,9 @@ py::object PyQueryResult::convertValueToPyObject(const Value& value) { case LogicalTypeID::INTERVAL: { auto intervalVal = value.getValue(); auto days = Interval::DAYS_PER_MONTH * intervalVal.months + intervalVal.days; - + return py::cast(importCache->datetime.timedelta()(py::arg("days") = days, - py::arg("microseconds") = intervalVal.micros)); + py::arg("microseconds") = intervalVal.micros)); } case LogicalTypeID::LIST: case LogicalTypeID::ARRAY: { @@ -333,7 +333,6 @@ bool PyQueryResult::getNextArrowChunk(const std::vectorpyarrow.lib.RecordBatch._import_from_c(); auto schema = ArrowConverter::toArrowSchema(types, names); diff --git a/tools/python_api/src_cpp/pyarrow/pyarrow_scan.cpp b/tools/python_api/src_cpp/pyarrow/pyarrow_scan.cpp index 0598c269cd..8774309c94 100644 --- a/tools/python_api/src_cpp/pyarrow/pyarrow_scan.cpp +++ b/tools/python_api/src_cpp/pyarrow/pyarrow_scan.cpp @@ -12,8 +12,8 @@ using namespace kuzu::catalog; namespace kuzu { -static std::unique_ptr bindFunc( - main::ClientContext* /*context*/, TableFuncBindInput* input) { +static std::unique_ptr bindFunc(main::ClientContext* /*context*/, + TableFuncBindInput* input) { py::gil_scoped_acquire acquire; py::object table(py::reinterpret_borrow( @@ -31,13 +31,13 @@ static std::unique_ptr bindFunc( py::list batches = table.attr("to_batches")(DEFAULT_VECTOR_CAPACITY); std::vector> arrowArrayBatches; - for (auto& i: batches) { + for (auto& i : batches) { arrowArrayBatches.push_back(std::make_shared()); i.attr("_export_to_c")(reinterpret_cast(arrowArrayBatches.back().get())); } - return std::make_unique( - std::move(returnTypes), std::move(schema), std::move(names), arrowArrayBatches, numRows); + return std::make_unique(std::move(returnTypes), std::move(schema), + std::move(names), arrowArrayBatches, numRows); } ArrowArrayWrapper* PyArrowTableScanSharedState::getNextChunk() { @@ -55,8 +55,8 @@ static std::unique_ptr initSharedState( PyArrowTableScanFunctionData* bindData = dynamic_cast(input.bindData); - return std::make_unique( - bindData->numRows, bindData->arrowArrayBatches); + return std::make_unique(bindData->numRows, + bindData->arrowArrayBatches); } static std::unique_ptr initLocalState( @@ -68,8 +68,8 @@ static std::unique_ptr initLocalState( return std::make_unique(pyArrowShared->getNextChunk()); } -static common::offset_t tableFunc( - function::TableFuncInput& input, function::TableFuncOutput& output) { +static common::offset_t tableFunc(function::TableFuncInput& input, + function::TableFuncOutput& output) { auto arrowScanData = dynamic_cast(input.bindData); auto arrowLocalState = dynamic_cast(input.localState); @@ -90,23 +90,23 @@ double progressFunc(function::TableFuncSharedState* sharedState) { PyArrowTableScanSharedState* state = ku_dynamic_cast(sharedState); if (state->chunks.size() == 0) { - return 0.0; - } + return 0.0; + } return static_cast(state->currentChunk) / state->chunks.size(); -} +} function::function_set PyArrowTableScanFunction::getFunctionSet() { function_set functionSet; functionSet.push_back( - std::make_unique(name, tableFunc, bindFunc, - initSharedState, initLocalState, progressFunc, std::vector{LogicalTypeID::POINTER})); + std::make_unique(name, tableFunc, bindFunc, initSharedState, initLocalState, + progressFunc, std::vector{LogicalTypeID::POINTER})); return functionSet; } TableFunction PyArrowTableScanFunction::getFunction() { - return TableFunction(name, tableFunc, bindFunc, initSharedState, - initLocalState, progressFunc, std::vector{LogicalTypeID::POINTER}); + return TableFunction(name, tableFunc, bindFunc, initSharedState, initLocalState, progressFunc, + std::vector{LogicalTypeID::POINTER}); } } // namespace kuzu diff --git a/tools/rust_api/include/kuzu_rs.h b/tools/rust_api/include/kuzu_rs.h index 0155aa4d97..5aa8211969 100644 --- a/tools/rust_api/include/kuzu_rs.h +++ b/tools/rust_api/include/kuzu_rs.h @@ -114,10 +114,10 @@ size_t rel_value_get_num_properties(const kuzu::common::Value& value); rust::String node_value_get_property_name(const kuzu::common::Value& value, size_t index); rust::String rel_value_get_property_name(const kuzu::common::Value& value, size_t index); -const kuzu::common::Value& node_value_get_property_value( - const kuzu::common::Value& value, size_t index); -const kuzu::common::Value& rel_value_get_property_value( - const kuzu::common::Value& value, size_t index); +const kuzu::common::Value& node_value_get_property_value(const kuzu::common::Value& value, + size_t index); +const kuzu::common::Value& rel_value_get_property_value(const kuzu::common::Value& value, + size_t index); /* NodeVal */ const kuzu::common::Value& node_value_get_node_id(const kuzu::common::Value& val); @@ -131,8 +131,8 @@ const kuzu::common::Value& recursive_rel_get_nodes(const kuzu::common::Value& va const kuzu::common::Value& recursive_rel_get_rels(const kuzu::common::Value& val); /* FlatTuple */ -const kuzu::common::Value& flat_tuple_get_value( - const kuzu::processor::FlatTuple& flatTuple, uint32_t index); +const kuzu::common::Value& flat_tuple_get_value(const kuzu::processor::FlatTuple& flatTuple, + uint32_t index); /* Value */ const std::string& value_get_string(const kuzu::common::Value& value); @@ -158,8 +158,8 @@ kuzu::common::LogicalTypeID value_get_data_type_id(const kuzu::common::Value& va const kuzu::common::LogicalType& value_get_data_type(const kuzu::common::Value& value); rust::String value_to_string(const kuzu::common::Value& val); -std::unique_ptr create_value_string( - kuzu::common::LogicalTypeID typ, const rust::Slice value); +std::unique_ptr create_value_string(kuzu::common::LogicalTypeID typ, + const rust::Slice value); std::unique_ptr create_value_timestamp(const int64_t timestamp); std::unique_ptr create_value_timestamp_tz(const int64_t timestamp); std::unique_ptr create_value_timestamp_ns(const int64_t timestamp); @@ -168,8 +168,8 @@ std::unique_ptr create_value_timestamp_sec(const int64_t ti inline std::unique_ptr create_value_date(const int32_t date) { return std::make_unique(kuzu::common::date_t(date)); } -std::unique_ptr create_value_interval( - const int32_t months, const int32_t days, const int64_t micros); +std::unique_ptr create_value_interval(const int32_t months, const int32_t days, + const int64_t micros); std::unique_ptr create_value_null( std::unique_ptr typ); std::unique_ptr create_value_int128_t(int64_t high, uint64_t low); @@ -191,8 +191,8 @@ struct ValueListBuilder { void insert(std::unique_ptr value) { values.push_back(std::move(value)); } }; -std::unique_ptr get_list_value( - std::unique_ptr typ, std::unique_ptr value); +std::unique_ptr get_list_value(std::unique_ptr typ, + std::unique_ptr value); std::unique_ptr create_list(); inline std::string_view string_view_from_str(rust::Str s) { diff --git a/tools/rust_api/src/kuzu_rs.cpp b/tools/rust_api/src/kuzu_rs.cpp index 545291d342..a53955580d 100644 --- a/tools/rust_api/src/kuzu_rs.cpp +++ b/tools/rust_api/src/kuzu_rs.cpp @@ -2,13 +2,13 @@ using kuzu::common::ArrayTypeInfo; using kuzu::common::Interval; +using kuzu::common::ListTypeInfo; using kuzu::common::LogicalType; using kuzu::common::LogicalTypeID; using kuzu::common::NodeVal; using kuzu::common::RelVal; using kuzu::common::StructField; using kuzu::common::Value; -using kuzu::common::ListTypeInfo; using kuzu::main::Connection; using kuzu::main::Database; using kuzu::main::SystemConfig; @@ -26,8 +26,8 @@ std::unique_ptr create_logical_type_list(std::unique_ptr create_logical_type_array( - std::unique_ptr childType, uint64_t numElements) { +std::unique_ptr create_logical_type_array(std::unique_ptr childType, + uint64_t numElements) { return LogicalType::ARRAY(std::move(childType), numElements); } @@ -175,8 +175,8 @@ rust::String value_to_string(const kuzu::common::Value& val) { uint32_t flat_tuple_len(const kuzu::processor::FlatTuple& flatTuple) { return flatTuple.len(); } -const kuzu::common::Value& flat_tuple_get_value( - const kuzu::processor::FlatTuple& flatTuple, uint32_t index) { +const kuzu::common::Value& flat_tuple_get_value(const kuzu::processor::FlatTuple& flatTuple, + uint32_t index) { return *flatTuple.getValue(index); } @@ -239,10 +239,10 @@ const LogicalType& value_get_data_type(const kuzu::common::Value& value) { return *value.getDataType(); } -std::unique_ptr create_value_string( - LogicalTypeID typ, const rust::Slice value) { - return std::make_unique( - std::make_unique(typ), std::string((const char*)value.data(), value.size())); +std::unique_ptr create_value_string(LogicalTypeID typ, + const rust::Slice value) { + return std::make_unique(std::make_unique(typ), + std::string((const char*)value.data(), value.size())); } std::unique_ptr create_value_timestamp(const int64_t timestamp) { return std::make_unique(kuzu::common::timestamp_t(timestamp)); @@ -259,8 +259,8 @@ std::unique_ptr create_value_timestamp_ms(const int64_t tim std::unique_ptr create_value_timestamp_sec(const int64_t timestamp) { return std::make_unique(kuzu::common::timestamp_sec_t(timestamp)); } -std::unique_ptr create_value_interval( - const int32_t months, const int32_t days, const int64_t micros) { +std::unique_ptr create_value_interval(const int32_t months, const int32_t days, + const int64_t micros) { return std::make_unique(kuzu::common::interval_t(months, days, micros)); } std::unique_ptr create_value_null( @@ -275,8 +275,8 @@ std::unique_ptr create_value_int128_t(int64_t high, uint64_ return std::make_unique(kuzu::common::int128_t(low, high)); } -std::unique_ptr get_list_value( - std::unique_ptr typ, std::unique_ptr value) { +std::unique_ptr get_list_value(std::unique_ptr typ, + std::unique_ptr value) { return std::make_unique(std::move(typ), std::move(value->values)); } diff --git a/tools/shell/embedded_shell.cpp b/tools/shell/embedded_shell.cpp index 7ea9103d9a..cc064ebbbe 100644 --- a/tools/shell/embedded_shell.cpp +++ b/tools/shell/embedded_shell.cpp @@ -14,12 +14,11 @@ #include "catalog/catalog.h" #include "catalog/catalog_entry/node_table_catalog_entry.h" #include "catalog/catalog_entry/rel_table_catalog_entry.h" +#include "common/task_system/progress_bar.h" #include "transaction/transaction.h" #include "utf8proc.h" #include "utf8proc_wrapper.h" -#include "common/task_system/progress_bar.h" - using namespace kuzu::common; using namespace kuzu::utf8proc; @@ -81,8 +80,8 @@ const int defaultMaxRows = 20; static Connection* globalConnection; #ifndef _WIN32 - struct termios orig_termios; - bool noEcho = false; +struct termios orig_termios; +bool noEcho = false; #endif void EmbeddedShell::updateTableNames() { @@ -98,8 +97,8 @@ void EmbeddedShell::updateTableNames() { } } -void addTableCompletion( - const std::string& buf, const std::string& tableName, linenoiseCompletions* lc) { +void addTableCompletion(const std::string& buf, const std::string& tableName, + linenoiseCompletions* lc) { std::string prefix, suffix; auto prefixPos = buf.rfind(':') + 1; prefix = buf.substr(0, prefixPos); @@ -205,12 +204,12 @@ void highlight(char* buffer, char* resultBuf, uint32_t renderWidth, uint32_t cur #ifndef _WIN32 if (token.find(' ') == std::string::npos) { for (const std::string& keyword : keywordList) { - if (regex_search( - token, std::regex("^" + keyword + "$", std::regex_constants::icase)) || - regex_search( - token, std::regex("^" + keyword + "\\(", std::regex_constants::icase)) || - regex_search( - token, std::regex("\\(" + keyword + "$", std::regex_constants::icase))) { + if (regex_search(token, + std::regex("^" + keyword + "$", std::regex_constants::icase)) || + regex_search(token, + std::regex("^" + keyword + "\\(", std::regex_constants::icase)) || + regex_search(token, + std::regex("\\(" + keyword + "$", std::regex_constants::icase))) { token = regex_replace(token, std::regex(std::string("(").append(keyword).append(")"), std::regex_constants::icase), @@ -240,15 +239,15 @@ uint64_t damerauLevenshteinDistance(const std::string& s1, const std::string& s2 for (uint64_t i = 1; i <= m; i++) { for (uint64_t j = 1; j <= n; j++) { if (s1[i - 1] == s2[j - 1]) { - dp[i][j] = dp[i - 1][j - 1]; + dp[i][j] = dp[i - 1][j - 1]; if (i > 1 && j > 1 && s1[i - 1] == s2[j - 2] && s1[i - 2] == s2[j - 1]) { - dp[i][j] = std::min(dp[i][j], dp[i - 2][j - 2]); - } + dp[i][j] = std::min(dp[i][j], dp[i - 2][j - 2]); + } } else { dp[i][j] = 1 + std::min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]}); if (i > 1 && j > 1 && s1[i - 1] == s2[j - 2] && s1[i - 2] == s2[j - 1]) { - dp[i][j] = std::min(dp[i][j], dp[i - 2][j - 2] + 1); - } + dp[i][j] = std::min(dp[i][j], dp[i - 2][j - 2] + 1); + } } } } @@ -286,8 +285,8 @@ int EmbeddedShell::processShellCommands(std::string lineStr) { return 0; } -EmbeddedShell::EmbeddedShell( - const std::string& databasePath, const SystemConfig& systemConfig, const char* pathToHistory) { +EmbeddedShell::EmbeddedShell(const std::string& databasePath, const SystemConfig& systemConfig, + const char* pathToHistory) { path_to_history = pathToHistory; linenoiseHistoryLoad(path_to_history); linenoiseSetCompletionCallback(completion); @@ -360,11 +359,14 @@ void EmbeddedShell::run() { printExecutionResult(*queryResult); } else { std::string lineStrTrimmed = lineStr; - lineStrTrimmed = lineStrTrimmed.erase(0, lineStr.find_first_not_of(" \t\n\r\f\v")); - if (lineStrTrimmed.find_first_of(" \t\n\r\f\v") == std::string::npos && lineStrTrimmed.length() > 1) { - printf("Error: \"%s\" is not a valid Cypher query. Did you mean to issue a CLI command, e.g., \"%s\"?\n", lineStr.c_str(), findClosestCommand(lineStrTrimmed).c_str()); - } - else { + lineStrTrimmed = + lineStrTrimmed.erase(0, lineStr.find_first_not_of(" \t\n\r\f\v")); + if (lineStrTrimmed.find_first_of(" \t\n\r\f\v") == std::string::npos && + lineStrTrimmed.length() > 1) { + printf("Error: \"%s\" is not a valid Cypher query. Did you mean to issue a " + "CLI command, e.g., \"%s\"?\n", + lineStr.c_str(), findClosestCommand(lineStrTrimmed).c_str()); + } else { printf("Error: %s\n", queryResult->getErrorMessage().c_str()); } } @@ -414,8 +416,8 @@ void EmbeddedShell::setMaxWidth(const std::string& maxWidthString) { try { parsedMaxWidth = stoul(maxWidthString); } catch (std::exception& e) { - printf( - "Cannot parse '%s' as number of characters. Expect integer.\n", maxWidthString.c_str()); + printf("Cannot parse '%s' as number of characters. Expect integer.\n", + maxWidthString.c_str()); return; } maxPrintWidth = parsedMaxWidth; @@ -484,12 +486,12 @@ void EmbeddedShell::printExecutionResult(QueryResult& queryResult) const { if (colsWidth.size() == 1) { uint32_t minDisplayWidth = minTruncatedWidth + SMALL_TABLE_SEPERATOR_LENGTH; if (maxPrintWidth > minDisplayWidth) { - sumGoal = maxPrintWidth - 2; + sumGoal = maxPrintWidth - 2; } else { sumGoal = std::max( (uint32_t)(getColumns(STDIN_FILENO, STDOUT_FILENO) - colsWidth.size() - 1), minDisplayWidth); - } + } } else if (colsWidth.size() > 1) { uint32_t minDisplayWidth = SMALL_TABLE_SEPERATOR_LENGTH + minTruncatedWidth * 2; if (maxPrintWidth > minDisplayWidth) { @@ -497,7 +499,8 @@ void EmbeddedShell::printExecutionResult(QueryResult& queryResult) const { } else { // make sure there is space for the first and last column sumGoal = std::max( - (uint32_t)(getColumns(STDIN_FILENO, STDOUT_FILENO) - colsWidth.size() - 1), minDisplayWidth); + (uint32_t)(getColumns(STDIN_FILENO, STDOUT_FILENO) - colsWidth.size() - 1), + minDisplayWidth); } } else if (maxPrintWidth > minTruncatedWidth) { sumGoal = maxPrintWidth; diff --git a/tools/shell/include/embedded_shell.h b/tools/shell/include/embedded_shell.h index 7b5171f455..ba99528412 100644 --- a/tools/shell/include/embedded_shell.h +++ b/tools/shell/include/embedded_shell.h @@ -12,8 +12,8 @@ namespace main { class EmbeddedShell { public: - EmbeddedShell( - const std::string& databasePath, const SystemConfig& systemConfig, const char* pathToHistory); + EmbeddedShell(const std::string& databasePath, const SystemConfig& systemConfig, + const char* pathToHistory); void run(); diff --git a/tools/shell/linenoise.cpp b/tools/shell/linenoise.cpp index a3f55c4a90..3cf2874786 100644 --- a/tools/shell/linenoise.cpp +++ b/tools/shell/linenoise.cpp @@ -236,7 +236,7 @@ struct linenoiseState { int history_index; /* The history index we are currently editing. */ bool search; /* Whether or not we are searching our history */ bool render; /* Whether or not to re-render */ - bool hasMoreData; /* Whether or not there is more data available in the buffer (copy+paste)*/ + bool hasMoreData; /* Whether or not there is more data available in the buffer (copy+paste)*/ std::string search_buf; //! The search buffer std::vector search_matches; //! The set of search matches in our history std::string prev_search_match; //! The previous search match @@ -245,22 +245,22 @@ struct linenoiseState { }; enum KEY_ACTION { - KEY_NULL = 0, /* NULL */ - CTRL_A = 1, /* Ctrl+a */ - CTRL_B = 2, /* Ctrl-b */ - CTRL_C = 3, /* Ctrl-c */ - CTRL_D = 4, /* Ctrl-d */ - CTRL_E = 5, /* Ctrl-e */ - CTRL_F = 6, /* Ctrl-f */ - CTRL_G = 7, /* Ctrl-g */ - CTRL_H = 8, /* Ctrl-h */ - TAB = 9, /* Tab */ - CTRL_K = 11, /* Ctrl+k */ - CTRL_L = 12, /* Ctrl+l */ - ENTER = 13, /* Enter */ - CTRL_N = 14, /* Ctrl-n */ - CTRL_P = 16, /* Ctrl-p */ - CTRL_R = 18, /* Ctrl-r */ + KEY_NULL = 0, /* NULL */ + CTRL_A = 1, /* Ctrl+a */ + CTRL_B = 2, /* Ctrl-b */ + CTRL_C = 3, /* Ctrl-c */ + CTRL_D = 4, /* Ctrl-d */ + CTRL_E = 5, /* Ctrl-e */ + CTRL_F = 6, /* Ctrl-f */ + CTRL_G = 7, /* Ctrl-g */ + CTRL_H = 8, /* Ctrl-h */ + TAB = 9, /* Tab */ + CTRL_K = 11, /* Ctrl+k */ + CTRL_L = 12, /* Ctrl+l */ + ENTER = 13, /* Enter */ + CTRL_N = 14, /* Ctrl-n */ + CTRL_P = 16, /* Ctrl-p */ + CTRL_R = 18, /* Ctrl-r */ CTRL_S = 19, CTRL_T = 20, /* Ctrl-t */ CTRL_U = 21, /* Ctrl+u */ @@ -867,7 +867,7 @@ static void refreshSingleLine(struct linenoiseState* l) { size_t renderPos = 0; truncateText(l->buf, len, pos, l->cols, plen, true, renderPos, buf); - + abInit(&ab); /* Cursor to left edge */ snprintf(seq, 64, "\r"); @@ -1094,12 +1094,13 @@ static void highlightSearchMatch(char* buffer, char* resultBuf, const char* sear } } -static void refreshSearchMultiLine(struct linenoiseState* l, const char* searchPrompt, const char* searchText) { +static void refreshSearchMultiLine(struct linenoiseState* l, const char* searchPrompt, + const char* searchText) { char seq[64]; uint32_t plen = linenoiseComputeRenderWidth(l->prompt, strlen(l->prompt)); - int rows = 1; /* Rows used by current buf. */ - int rpos = 1; /* Cursor relative row. */ - int rpos2; /* rpos after refresh. */ + int rows = 1; /* Rows used by current buf. */ + int rpos = 1; /* Cursor relative row. */ + int rpos2; /* rpos after refresh. */ int old_rows = l->maxrows; int fd = l->ofd, j; struct abuf ab; @@ -1173,7 +1174,7 @@ static void refreshSearchMultiLine(struct linenoiseState* l, const char* searchP refreshShowHints(&ab, l, plen); /* Move cursor to right position. */ - rpos2 = 1; /* current cursor relative row. */ + rpos2 = 1; /* current cursor relative row. */ lndebug("rpos2 %d", rpos2); /* Go up till we reach the expected positon. */ @@ -1213,14 +1214,15 @@ static void refreshSearch(struct linenoiseState* l) { search_prompt = "failing-bck-i-search: "; } - char* search_buf = (char*) search_text.c_str(); + char* search_buf = (char*)search_text.c_str(); size_t search_len = search_text.size(); - + size_t cols = l->cols - search_prompt.length() - 1; size_t render_pos = 0; char emptyHighlightBuf[LINENOISE_MAX_LINE]; - truncateText(search_buf, search_len, search_len, cols, false, 0, render_pos, emptyHighlightBuf); + truncateText(search_buf, search_len, search_len, cols, false, 0, render_pos, + emptyHighlightBuf); truncatedSearchText = std::string(search_buf, search_len); search_prompt += truncatedSearchText; search_prompt += "_"; @@ -1277,7 +1279,7 @@ static char acceptSearch(linenoiseState* l, char nextCommand) { while (history_len > 1 && history_index != (history_len - 1 - l->history_index)) { /* Update the current history entry before to - * overwrite it with the next one. */ + * overwrite it with the next one. */ free(history[history_len - 1 - l->history_index]); history[history_len - 1 - l->history_index] = strdup(l->buf); /* Show the new entry */ @@ -1351,7 +1353,7 @@ static void performSearch(linenoiseState* l) { l->search_matches.push_back(match); } } - } + } } static void searchPrev(linenoiseState* l) { @@ -1375,166 +1377,166 @@ bool pastedInput(int ifd) { return (isPasted != 0 && isPasted != SOCKET_ERROR); #else fd_set rfds; - FD_ZERO(&rfds); - FD_SET(ifd, &rfds); - - // no timeout: return immediately - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 0; - return select(1, &rfds, NULL, NULL, &tv); + FD_ZERO(&rfds); + FD_SET(ifd, &rfds); + + // no timeout: return immediately + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 0; + return select(1, &rfds, NULL, NULL, &tv); #endif } -static char linenoiseSearch(linenoiseState *l, char c) { +static char linenoiseSearch(linenoiseState* l, char c) { char seq[64]; - switch (c) { + switch (c) { case 10: - case ENTER: /* enter */ - // accept search and run - return acceptSearch(l, ENTER); + case ENTER: /* enter */ + // accept search and run + return acceptSearch(l, ENTER); case CTRL_N: - case CTRL_R: - // move to the next match index - searchNext(l); - break; + case CTRL_R: + // move to the next match index + searchNext(l); + break; case CTRL_P: case CTRL_S: // move to the prev match index searchPrev(l); break; - case ESC: /* escape sequence */ - /* Read the next two bytes representing the escape sequence. - * Use two calls to handle slow terminals returning the two - * chars at different times. */ - // note: in search mode we ignore almost all special commands - if (read(l->ifd, seq, 1) == -1) - break; - if (seq[0] == ESC) { - // double escape accepts search without any additional command - return acceptSearch(l, 0); - } - if (seq[0] == 'b' || seq[0] == 'f') { - break; - } - if (read(l->ifd, seq + 1, 1) == -1) - break; - - /* ESC [ sequences. */ - if (seq[0] == '[') { - if (seq[1] >= '0' && seq[1] <= '9') { - /* Extended escape, read additional byte. */ - if (read(l->ifd, seq + 2, 1) == -1) - break; - if (seq[2] == '~') { - switch (seq[1]) { - case '1': - return acceptSearch(l, CTRL_A); - case '4': - case '8': - return acceptSearch(l, CTRL_E); - default: - break; - } - } else if (seq[2] == ';') { - // read 2 extra bytes - if (read(l->ifd, seq + 3, 2) == -1) - break; - } - } else { - switch (seq[1]) { - case 'A': /* Up */ + case ESC: /* escape sequence */ + /* Read the next two bytes representing the escape sequence. + * Use two calls to handle slow terminals returning the two + * chars at different times. */ + // note: in search mode we ignore almost all special commands + if (read(l->ifd, seq, 1) == -1) + break; + if (seq[0] == ESC) { + // double escape accepts search without any additional command + return acceptSearch(l, 0); + } + if (seq[0] == 'b' || seq[0] == 'f') { + break; + } + if (read(l->ifd, seq + 1, 1) == -1) + break; + + /* ESC [ sequences. */ + if (seq[0] == '[') { + if (seq[1] >= '0' && seq[1] <= '9') { + /* Extended escape, read additional byte. */ + if (read(l->ifd, seq + 2, 1) == -1) + break; + if (seq[2] == '~') { + switch (seq[1]) { + case '1': + return acceptSearch(l, CTRL_A); + case '4': + case '8': + return acceptSearch(l, CTRL_E); + default: + break; + } + } else if (seq[2] == ';') { + // read 2 extra bytes + if (read(l->ifd, seq + 3, 2) == -1) + break; + } + } else { + switch (seq[1]) { + case 'A': /* Up */ // accepts search without any additional command c = acceptSearch(l, 0); linenoiseEditHistoryNext(l, LINENOISE_HISTORY_PREV); - return c; - case 'B': /* Down */ + return c; + case 'B': /* Down */ // accepts search without any additional command c = acceptSearch(l, 0); linenoiseEditHistoryNext(l, LINENOISE_HISTORY_NEXT); return c; - case 'D': /* Left */ - return acceptSearch(l, CTRL_B); - case 'C': /* Right */ - return acceptSearch(l, CTRL_F); - case 'H': /* Home */ - return acceptSearch(l, CTRL_A); - case 'F': /* End*/ - return acceptSearch(l, CTRL_E); - default: - break; - } - } - } - /* ESC O sequences. */ - else if (seq[0] == 'O') { - switch (seq[1]) { - case 'H': /* Home */ - return acceptSearch(l, CTRL_A); - case 'F': /* End*/ - return acceptSearch(l, CTRL_E); - default: - break; - } - } - break; - case CTRL_A: // accept search, move to start of line - return acceptSearch(l, CTRL_A); - case TAB: + case 'D': /* Left */ + return acceptSearch(l, CTRL_B); + case 'C': /* Right */ + return acceptSearch(l, CTRL_F); + case 'H': /* Home */ + return acceptSearch(l, CTRL_A); + case 'F': /* End*/ + return acceptSearch(l, CTRL_E); + default: + break; + } + } + } + /* ESC O sequences. */ + else if (seq[0] == 'O') { + switch (seq[1]) { + case 'H': /* Home */ + return acceptSearch(l, CTRL_A); + case 'F': /* End*/ + return acceptSearch(l, CTRL_E); + default: + break; + } + } + break; + case CTRL_A: // accept search, move to start of line + return acceptSearch(l, CTRL_A); + case TAB: if (l->hasMoreData) { l->search_buf += ' '; performSearch(l); break; } return acceptSearch(l, CTRL_E); - case CTRL_E: // accept search - move to end of line - return acceptSearch(l, CTRL_E); - case CTRL_B: // accept search - move cursor left - return acceptSearch(l, CTRL_B); - case CTRL_F: // accept search - move cursor right - return acceptSearch(l, CTRL_F); - case CTRL_T: // accept search: swap character - return acceptSearch(l, CTRL_T); - case CTRL_U: // accept search, clear buffer - return acceptSearch(l, CTRL_U); - case CTRL_K: // accept search, clear after cursor - return acceptSearch(l, CTRL_K); - case CTRL_D: // accept search, delete a character - return acceptSearch(l, CTRL_D); - case CTRL_L: - linenoiseClearScreen(); - break; - case CTRL_C: - case CTRL_G: - // abort search + case CTRL_E: // accept search - move to end of line + return acceptSearch(l, CTRL_E); + case CTRL_B: // accept search - move cursor left + return acceptSearch(l, CTRL_B); + case CTRL_F: // accept search - move cursor right + return acceptSearch(l, CTRL_F); + case CTRL_T: // accept search: swap character + return acceptSearch(l, CTRL_T); + case CTRL_U: // accept search, clear buffer + return acceptSearch(l, CTRL_U); + case CTRL_K: // accept search, clear after cursor + return acceptSearch(l, CTRL_K); + case CTRL_D: // accept search, delete a character + return acceptSearch(l, CTRL_D); + case CTRL_L: + linenoiseClearScreen(); + break; + case CTRL_C: + case CTRL_G: + // abort search l->buf[0] = '\0'; l->len = 0; l->pos = 0; - cancelSearch(l); - return 0; - case BACKSPACE: /* backspace */ - case 8: /* ctrl-h */ - case CTRL_W: /* ctrl-w */ - // remove trailing UTF-8 bytes (if any) - while (!l->search_buf.empty() && ((l->search_buf.back() & 0xc0) == 0x80)) { - l->search_buf.pop_back(); - } - // finally remove the first UTF-8 byte - if (!l->search_buf.empty()) { - l->search_buf.pop_back(); - } - performSearch(l); - break; - default: - // add input to search buffer - l->search_buf += c; - // perform the search - performSearch(l); - break; - } - refreshSearch(l); - return 0; + cancelSearch(l); + return 0; + case BACKSPACE: /* backspace */ + case 8: /* ctrl-h */ + case CTRL_W: /* ctrl-w */ + // remove trailing UTF-8 bytes (if any) + while (!l->search_buf.empty() && ((l->search_buf.back() & 0xc0) == 0x80)) { + l->search_buf.pop_back(); + } + // finally remove the first UTF-8 byte + if (!l->search_buf.empty()) { + l->search_buf.pop_back(); + } + performSearch(l); + break; + default: + // add input to search buffer + l->search_buf += c; + // perform the search + performSearch(l); + break; + } + refreshSearch(l); + return 0; } /* Insert the character 'c' at cursor current position. @@ -1718,8 +1720,8 @@ void linenoiseEditDeletePrevWord(struct linenoiseState* l) { * when ctrl+d is typed. * * The function returns the length of the current buffer. */ -static int linenoiseEdit( - int stdin_fd, int stdout_fd, char* buf, size_t buflen, const char* prompt) { +static int linenoiseEdit(int stdin_fd, int stdout_fd, char* buf, size_t buflen, + const char* prompt) { struct linenoiseState l; /* Populate the linenoise state that we pass to functions implementing @@ -1800,7 +1802,7 @@ static int linenoiseEdit( if (c == 0) continue; } - + switch (c) { case CTRL_G: case CTRL_C: /* ctrl-c */ @@ -1823,7 +1825,7 @@ static int linenoiseEdit( } return (int)l.len; case 10: - case ENTER: /* enter */ + case ENTER: /* enter */ history_len--; free(history[history_len]); if (mlmode) @@ -1887,7 +1889,7 @@ static int linenoiseEdit( break; case CTRL_P: /* ctrl-p */ linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV); - break; + break; case CTRL_N: /* ctrl-n */ linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT); break; @@ -2248,7 +2250,7 @@ int linenoiseHistoryAdd(const char* line) { free(linecopy); return 0; } - + if (history_len == history_max_len) { free(history[0]); memmove(history, history + 1, sizeof(char*) * (history_max_len - 1)); @@ -2331,7 +2333,7 @@ int linenoiseHistoryLoad(const char* filename) { buf[LINENOISE_MAX_LINE] = '\0'; if (fp == NULL) - return -1; + return -1; std::string result; while (fgets(buf, LINENOISE_MAX_LINE, fp) != NULL) { @@ -2361,8 +2363,8 @@ int linenoiseHistoryLoad(const char* filename) { result = std::string(); continue; } - // the result does not contain a full Cypher statement - add a newline deliminator and move on - // to the next line + // the result does not contain a full Cypher statement - add a newline deliminator and move + // on to the next line result += "\r\n"; } fclose(fp); diff --git a/tools/shell/shell_runner.cpp b/tools/shell/shell_runner.cpp index 4815f7da74..c5196e7927 100644 --- a/tools/shell/shell_runner.cpp +++ b/tools/shell/shell_runner.cpp @@ -1,6 +1,7 @@ -#include #include +#include + #include "args.hxx" #include "common/file_system/virtual_file_system.h" #include "embedded_shell.h" @@ -10,20 +11,19 @@ using namespace kuzu::common; int main(int argc, char* argv[]) { args::ArgumentParser parser("KuzuDB Shell"); - args::Positional inputDirFlag( - parser, "databasePath", "Database path.", args::Options::Required); + args::Positional inputDirFlag(parser, "databasePath", "Database path.", + args::Options::Required); args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"}); args::ValueFlag bpSizeInMBFlag(parser, "", "Size of buffer pool for default and large page sizes in megabytes", {'d', "defaultBPSize"}, -1u); - args::Flag disableCompression( - parser, "nocompression", "Disable compression", {"nocompression"}); - args::Flag readOnlyMode( - parser, "readOnly", "Open database at read-only mode.", {'r', "readOnly"}); - args::ValueFlag historyPathFlag( - parser, "", "Path to directory for shell history", {'p'}); - args::Flag version( - parser, "version", "Display current database version", {'v', "version"}); + args::Flag disableCompression(parser, "nocompression", "Disable compression", + {"nocompression"}); + args::Flag readOnlyMode(parser, "readOnly", "Open database at read-only mode.", + {'r', "readOnly"}); + args::ValueFlag historyPathFlag(parser, "", "Path to directory for shell history", + {'p'}); + args::Flag version(parser, "version", "Display current database version", {'v', "version"}); try { parser.ParseCLI(argc, argv); } catch (std::exception& e) {