Skip to content

Commit

Permalink
Merge pull request #1202 from Mytherin/pythonblobs
Browse files Browse the repository at this point in the history
Add blob support to the python api
  • Loading branch information
Mytherin committed Dec 8, 2020
2 parents 6bf2480 + 4c17f2a commit 4271182
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
14 changes: 13 additions & 1 deletion tools/pythonpkg/duckdb_python.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ struct StringConvert {
}
};

struct BlobConvert {
template <class DUCKDB_T, class NUMPY_T> static py::str convert_value(string_t val) {
return py::bytes(val.GetString());
}
};

struct IntegralConvert {
template <class DUCKDB_T, class NUMPY_T> static NUMPY_T convert_value(DUCKDB_T val) {
return NUMPY_T(val);
Expand Down Expand Up @@ -544,7 +550,9 @@ struct DuckDBPyResult {
case LogicalTypeId::VARCHAR:
res[col_idx] = val.GetValue<string>();
break;

case LogicalTypeId::BLOB:
res[col_idx] = py::bytes(val.GetValue<string>());
break;
case LogicalTypeId::TIMESTAMP: {
D_ASSERT(result->types[col_idx].InternalType() == PhysicalType::INT64);

Expand Down Expand Up @@ -660,6 +668,10 @@ struct DuckDBPyResult {
col_res = duckdb_py_convert::fetch_column<string_t, py::str, duckdb_py_convert::StringConvert>(
"object", mres->collection, col_idx);
break;
case LogicalTypeId::BLOB:
col_res = duckdb_py_convert::fetch_column<string_t, py::bytes, duckdb_py_convert::BlobConvert>(
"object", mres->collection, col_idx);
break;
default:
throw runtime_error("unsupported type " + mres->types[col_idx].ToString());
}
Expand Down
12 changes: 12 additions & 0 deletions tools/pythonpkg/tests/test_blob.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import duckdb
import numpy

class TestBlob(object):
def test_blob(self, duckdb_cursor):
duckdb_cursor.execute("SELECT BLOB 'hello'")
results = duckdb_cursor.fetchall()
assert results[0][0] == b'hello'

duckdb_cursor.execute("SELECT BLOB 'hello' AS a")
results = duckdb_cursor.fetchnumpy()
assert results['a'] == numpy.array([b'hello'], dtype=numpy.object)

0 comments on commit 4271182

Please sign in to comment.