Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support python binding #112

Merged
merged 21 commits into from
May 25, 2023
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ members = [
"core",
"driver",
"cli",
"bindings/python"
]
75 changes: 75 additions & 0 deletions bindings/python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/target

# Byte-compiled / optimized / DLL files
__pycache__/
.pytest_cache/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
.venv/
env/
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
include/
man/
venv/
*.egg-info/
.installed.cfg
*.egg

# Installer logs
pip-log.txt
pip-delete-this-directory.txt
pip-selfcheck.json

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# Rope
.ropeproject

# Django stuff:
*.log
*.pot

.DS_Store

# Sphinx documentation
docs/_build/

# PyCharm
.idea/

# VSCode
.vscode/

# Pyenv
.python-version

# Generated docs
docs
36 changes: 36 additions & 0 deletions bindings/python/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

[package]
name = "databend-python"
version = "0.0.1"
edition = "2021"
license = "Apache-2.0"
publish = false

[lib]
crate-type = ["cdylib"]
doc = false

[dependencies]
chrono = { version = "0.4.24", default-features = false, features = ["std"] }
futures = "0.3.28"
databend-driver = { path = "../../driver", version = "0.2.20", features = ["rustls", "flight-sql"] }
databend-client = { version = "0.1.15", path = "../../core" }
pyo3 = { version = "0.18", features = ["chrono"] }
pyo3-asyncio = { version = "0.18", features = ["tokio-runtime"] }
tokio = "1"
Empty file added bindings/python/README.md
Empty file.
1 change: 1 addition & 0 deletions bindings/python/databend_python/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from ._databend_python import *
4 changes: 4 additions & 0 deletions bindings/python/databend_python/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class AsyncDatabendDriver:
def __init__(self, dsn: str): ...

async def read(self, sql: str) -> int: ...
54 changes: 54 additions & 0 deletions bindings/python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

[build-system]
build-backend = "maturin"
requires = ["maturin>=0.14.16,<0.15"]

[project]
classifiers = [
"Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
description = "Databend Driver Python Binding"
license = { text = "Apache-2.0" }
name = "databend-python"
readme = "README.md"
requires-python = ">=3.7"

[project.optional-dependencies]
benchmark = [
"gevent",
"greenify",
"greenlet",
"boto3",
"pydantic",
"boto3-stubs[essential]",
]
docs = ["pdoc"]
test = ["behave"]

[project.urls]
Documentation = ""
Homepage = ""
Repository = "https://github.com/datafuselabs/bendsql"

[tool.maturin]
features = ["pyo3/extension-module"]
module-name = "databend_python._databend_python"
python-source = "python"
62 changes: 62 additions & 0 deletions bindings/python/src/asyncio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use databend_client;
use databend_driver::rest_api::RestAPIConnection;
use pyo3::prelude::*;
use pyo3_asyncio::tokio::future_into_py;
use databend_driver::Connection;
use std::{
collections::{HashMap, HashSet},
sync::{Arc, RwLock},
};
use std::fs::Metadata;
use pyo3::pyobject_native_type;

use crate::{build_rest_api_client};
use crate::format_pyerr;

/// `AsyncDatabendDriver` is the entry for all public async API
#[pyclass(module = "databend_python")]
pub struct AsyncDatabendDriver(RestAPIConnection);
hantmac marked this conversation as resolved.
Show resolved Hide resolved

#[pymethods]
impl AsyncDatabendDriver {
#[new]
#[pyo3(signature = (dsn))]
pub fn new(dsn: &str) -> PyResult<Self> {
Ok(AsyncDatabendDriver(build_rest_api_client(dsn)?))
}

/// exec
pub fn exec<'p>(&'p self, py: Python<'p>, sql: String) -> PyResult<&'p PyAny> {
let this = self.0.clone();
future_into_py(py, async move {
let res = this.exec(&sql).await.unwrap();
Ok(res)
})
}

// pub fn query_row<'p>(&'p self, py: Python<'p>, sql: String) -> PyResult<&'p PyAny> {
// let this = self.0.clone();
// future_into_py(py, async move {
// let row = this.query_row(&sql).await.unwrap();
// let row = row.unwrap();
// let res = row.clone().try_into().unwrap();
// // let py_res: PyObject = Python::with_gil(|py| PyObject::new(py, &res).into());
// Ok(res)
// },
// )
// }
}
40 changes: 40 additions & 0 deletions bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod asyncio;

use databend_client::APIClient;
use databend_driver::rest_api::RestAPIConnection;
use futures::future::ok;
use pyo3::create_exception;
use crate::asyncio::*;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
create_exception!(databend_client, Error, PyException, "databend_client related errors");
fn build_rest_api_client(dsn: &str) -> PyResult<RestAPIConnection> {
hantmac marked this conversation as resolved.
Show resolved Hide resolved
let conn = RestAPIConnection::try_create(dsn).unwrap();
Ok(conn)
}

fn format_pyerr(err: &str) -> PyErr {
match !err.is_empty() {
_ => Error::new_err(err.to_string()),
}
}

#[pymodule]
fn _databend_python(py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<AsyncDatabendDriver>()?;
Ok(())
}
2 changes: 1 addition & 1 deletion driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ mod conn;
mod error;
#[cfg(feature = "flight-sql")]
mod flight_sql;
mod rest_api;
pub mod rest_api;
hantmac marked this conversation as resolved.
Show resolved Hide resolved
mod rows;
mod schema;
mod value;
Expand Down
2 changes: 1 addition & 1 deletion driver/src/rest_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crate::QueryProgress;

#[derive(Clone)]
pub struct RestAPIConnection {
client: APIClient,
pub client: APIClient,
hantmac marked this conversation as resolved.
Show resolved Hide resolved
}

#[async_trait]
Expand Down