From 593a19eaa99ca38e8ff771c25e4b92a820d9db4d Mon Sep 17 00:00:00 2001 From: Satyam Tiwary Date: Thu, 14 Mar 2024 01:17:21 +0530 Subject: [PATCH] feat: implement missing executescript method --- examples/execute_script.py | 25 +++++++++++++++++++++++++ examples/statements.sql | 14 ++++++++++++++ src/lib.rs | 14 ++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 examples/execute_script.py create mode 100644 examples/statements.sql diff --git a/examples/execute_script.py b/examples/execute_script.py new file mode 100644 index 0000000..3ac3be2 --- /dev/null +++ b/examples/execute_script.py @@ -0,0 +1,25 @@ +""" +A short example showing how to execute a script containing a bunch of sql statements. +""" +import os + +import libsql_experimental as libsql + +def execute_script(conn, file_path: os.PathLike): + with open(file_path, 'r') as file: + script = file.read() + + conn.executescript(script) + conn.commit() + +conn = libsql.connect(':memory:') +script_path = os.path.join(os.path.dirname(__file__), 'statements.sql') +execute_script(conn, script_path) + +# Retrieve the data from the 'users' table and print it +cursor = conn.cursor() +cursor.execute("SELECT * FROM users") +rows = cursor.fetchall() +print("Data in the 'users' table:") +for row in rows: + print(row) diff --git a/examples/statements.sql b/examples/statements.sql new file mode 100644 index 0000000..281acea --- /dev/null +++ b/examples/statements.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY, + name TEXT, + age INTEGER +); + +INSERT INTO users (name, age) VALUES ('Alice', 25); +INSERT INTO users (name, age) VALUES ('Bob', 30); + +SELECT * FROM users; + +UPDATE users SET age = 26 WHERE name = 'Alice'; + +SELECT * FROM users; diff --git a/src/lib.rs b/src/lib.rs index 35366f8..b68dbf6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -184,6 +184,20 @@ impl Connection { Ok(cursor) } + fn executescript(self_: PyRef<'_, Self>, script: String) -> PyResult<()> { + let statements = script.split(';'); + for statement in statements { + let statement = statement.trim(); + if !statement.is_empty() { + let cursor = Connection::cursor(&self_)?; + self_ + .rt + .block_on(async { execute(&cursor, statement.to_string(), None).await })?; + } + } + Ok(()) + } + #[getter] fn isolation_level(self_: PyRef<'_, Self>) -> Option { self_.isolation_level.clone()