Skip to content

Commit 09b0198

Browse files
authored
Merge pull request #43 from Technoculture/feat-executescript
implement missing `executescript` method
2 parents 9eb9404 + 593a19e commit 09b0198

3 files changed

Lines changed: 53 additions & 0 deletions

File tree

examples/execute_script.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
A short example showing how to execute a script containing a bunch of sql statements.
3+
"""
4+
import os
5+
6+
import libsql_experimental as libsql
7+
8+
def execute_script(conn, file_path: os.PathLike):
9+
with open(file_path, 'r') as file:
10+
script = file.read()
11+
12+
conn.executescript(script)
13+
conn.commit()
14+
15+
conn = libsql.connect(':memory:')
16+
script_path = os.path.join(os.path.dirname(__file__), 'statements.sql')
17+
execute_script(conn, script_path)
18+
19+
# Retrieve the data from the 'users' table and print it
20+
cursor = conn.cursor()
21+
cursor.execute("SELECT * FROM users")
22+
rows = cursor.fetchall()
23+
print("Data in the 'users' table:")
24+
for row in rows:
25+
print(row)

examples/statements.sql

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
CREATE TABLE IF NOT EXISTS users (
2+
id INTEGER PRIMARY KEY,
3+
name TEXT,
4+
age INTEGER
5+
);
6+
7+
INSERT INTO users (name, age) VALUES ('Alice', 25);
8+
INSERT INTO users (name, age) VALUES ('Bob', 30);
9+
10+
SELECT * FROM users;
11+
12+
UPDATE users SET age = 26 WHERE name = 'Alice';
13+
14+
SELECT * FROM users;

src/lib.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,20 @@ impl Connection {
184184
Ok(cursor)
185185
}
186186

187+
fn executescript(self_: PyRef<'_, Self>, script: String) -> PyResult<()> {
188+
let statements = script.split(';');
189+
for statement in statements {
190+
let statement = statement.trim();
191+
if !statement.is_empty() {
192+
let cursor = Connection::cursor(&self_)?;
193+
self_
194+
.rt
195+
.block_on(async { execute(&cursor, statement.to_string(), None).await })?;
196+
}
197+
}
198+
Ok(())
199+
}
200+
187201
#[getter]
188202
fn isolation_level(self_: PyRef<'_, Self>) -> Option<String> {
189203
self_.isolation_level.clone()

0 commit comments

Comments
 (0)