1#include "duckdb/main/capi/capi_internal.hpp"
2
3using duckdb::Connection;
4using duckdb::DatabaseData;
5using duckdb::DBConfig;
6using duckdb::DuckDB;
7
8duckdb_state duckdb_open_ext(const char *path, duckdb_database *out, duckdb_config config, char **error) {
9 auto wrapper = new DatabaseData();
10 try {
11 auto db_config = (DBConfig *)config;
12 wrapper->database = duckdb::make_uniq<DuckDB>(args&: path, args&: db_config);
13 } catch (std::exception &ex) {
14 if (error) {
15 *error = strdup(s: ex.what());
16 }
17 delete wrapper;
18 return DuckDBError;
19 } catch (...) { // LCOV_EXCL_START
20 if (error) {
21 *error = strdup(s: "Unknown error");
22 }
23 delete wrapper;
24 return DuckDBError;
25 } // LCOV_EXCL_STOP
26 *out = (duckdb_database)wrapper;
27 return DuckDBSuccess;
28}
29
30duckdb_state duckdb_open(const char *path, duckdb_database *out) {
31 return duckdb_open_ext(path, out, config: nullptr, error: nullptr);
32}
33
34void duckdb_close(duckdb_database *database) {
35 if (database && *database) {
36 auto wrapper = reinterpret_cast<DatabaseData *>(*database);
37 delete wrapper;
38 *database = nullptr;
39 }
40}
41
42duckdb_state duckdb_connect(duckdb_database database, duckdb_connection *out) {
43 if (!database || !out) {
44 return DuckDBError;
45 }
46 auto wrapper = reinterpret_cast<DatabaseData *>(database);
47 Connection *connection;
48 try {
49 connection = new Connection(*wrapper->database);
50 } catch (...) { // LCOV_EXCL_START
51 return DuckDBError;
52 } // LCOV_EXCL_STOP
53 *out = (duckdb_connection)connection;
54 return DuckDBSuccess;
55}
56
57void duckdb_disconnect(duckdb_connection *connection) {
58 if (connection && *connection) {
59 Connection *conn = reinterpret_cast<Connection *>(*connection);
60 delete conn;
61 *connection = nullptr;
62 }
63}
64
65duckdb_state duckdb_query(duckdb_connection connection, const char *query, duckdb_result *out) {
66 Connection *conn = reinterpret_cast<Connection *>(connection);
67 auto result = conn->Query(query);
68 return duckdb_translate_result(result: std::move(result), out);
69}
70
71const char *duckdb_library_version() {
72 return DuckDB::LibraryVersion();
73}
74