File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 )
Original file line number Diff line number Diff line change 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;
Original file line number Diff line number Diff 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 ( )
You can’t perform that action at this time.
0 commit comments