### Setup Development Environment (Python) Source: https://github.com/tursodatabase/libsql-python/blob/main/CONTRIBUTING.md Installs necessary dependencies for developing the libSQL Python SDK using Python's virtual environment and pip. ```shell python3 -m venv .env source .env/bin/activate pip3 install maturin pyperf pytest ``` -------------------------------- ### Setup Development Environment (NIX) Source: https://github.com/tursodatabase/libsql-python/blob/main/CONTRIBUTING.md Sets up the development environment for the libSQL Python SDK using NIX, providing a pre-configured shell with all necessary tools. ```shell nix-shell ``` -------------------------------- ### Vector Search Setup with libSQL Vector Extension in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Provides an example of setting up a table and index for vector search using the libSQL vector extension in Python. This enables semantic similarity searches on data with vector embeddings. ```python import libsql conn = libsql.connect("vectors.db") # Create vector-enabled table conn.execute("DROP TABLE IF EXISTS movies") conn.execute(""" CREATE TABLE movies ( title TEXT, year INTEGER, embedding F32_BLOB(3) ) """) # Create vector index for fast similarity search conn.execute("CREATE INDEX movies_idx ON movies (libsql_vector_idx(embedding))") ``` -------------------------------- ### Build and Run Development Version (Python) Source: https://github.com/tursodatabase/libsql-python/blob/main/CONTRIBUTING.md Builds the development version of the libSQL Python SDK using Maturin and then executes an example Python script. ```shell maturin develop && python3 example.py ``` -------------------------------- ### Encrypted Database Creation in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Demonstrates creating and interacting with an encrypted libsql-python database using an encryption key. This ensures data at rest protection. The example shows successful access with the correct key and failure with an incorrect one. ```python import libsql import os # Use environment variable for production, hardcoded for demo only encryption_key = os.getenv("ENCRYPTION_KEY", "my-safe-encryption-key-32chars!") # Create encrypted database conn = libsql.connect("secure.db", encryption_key=encryption_key) # Normal operations on encrypted database conn.execute("CREATE TABLE IF NOT EXISTS secrets (id INTEGER PRIMARY KEY, data TEXT)") conn.execute("INSERT INTO secrets (data) VALUES (?)", ("confidential information",)) conn.execute("INSERT INTO secrets (data) VALUES (?)", ("sensitive data",)) secrets = conn.execute("SELECT * FROM secrets").fetchall() print(f"Stored {len(secrets)} encrypted records") conn.close() # Attempting to open without correct key will fail try: wrong_conn = libsql.connect("secure.db", encryption_key="wrong-key") wrong_conn.execute("SELECT * FROM secrets").fetchall() except Exception as e: print(f"Access denied with wrong key: {e}") # Reopen with correct key valid_conn = libsql.connect("secure.db", encryption_key=encryption_key) data = valid_conn.execute("SELECT data FROM secrets").fetchall() print("Decrypted data:", data) valid_conn.close() ``` -------------------------------- ### Setup Embedded Replica with Sync using libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Configures a local database to synchronize with a remote Turso database. This provides low-latency local reads while maintaining a backup and enabling synchronization. Supports periodic syncing and manual sync operations. ```python import libsql import os url = os.getenv("TURSO_DATABASE_URL") auth_token = os.getenv("TURSO_AUTH_TOKEN") # Create embedded replica with sync conn = libsql.connect( "local_replica.db", sync_url=url, auth_token=auth_token, sync_interval=5.0 # Sync every 5 seconds ) # Sync from remote before operations conn.sync() # Local operations conn.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)") conn.execute("INSERT OR REPLACE INTO settings VALUES (?, ?)", ("theme", "dark")) conn.execute("INSERT OR REPLACE INTO settings VALUES (?, ?)", ("language", "en")) # Sync to remote conn.sync() # Read local data (fast) settings = conn.execute("SELECT * FROM settings").fetchall() print(settings) # [('theme', 'dark'), ('language', 'en')] conn.close() ``` -------------------------------- ### Execute Queries with Cursor in Libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Shows how to use cursor objects in libsql-python for detailed control over query execution and result fetching. Supports fetching single rows, multiple rows, inspecting column descriptions, and getting row counts. ```python import libsql conn = libsql.connect("app.db") cur = conn.cursor() # Execute query via cursor cur.execute("CREATE TABLE IF NOT EXISTS logs (timestamp INTEGER, message TEXT)") cur.execute("INSERT INTO logs VALUES (?, ?)", (1234567890, "System started")) cur.execute("INSERT INTO logs VALUES (?, ?)", (1234567900, "User logged in")) cur.execute("INSERT INTO logs VALUES (?, ?)", (1234567910, "Data processed")) # Fetch one result at a time cur.execute("SELECT * FROM logs ORDER BY timestamp") first_log = cur.fetchone() print(first_log) # (1234567890, 'System started') # Fetch multiple results next_logs = cur.fetchmany(2) print(next_logs) # [(1234567900, 'User logged in'), (1234567910, 'Data processed')] # Get column information cur.execute("SELECT timestamp, message FROM logs LIMIT 1") print(cur.description) # (('timestamp', None, ...), ('message', None, ...)) # Get row count for DML operations cur.execute("DELETE FROM logs WHERE timestamp < ?", (1234567895,)) print(f"Deleted {cur.rowcount} rows") # Deleted 1 rows # Get last inserted row ID cur.execute("INSERT INTO logs VALUES (?, ?)", (1234567920, "Shutdown initiated")) print(f"Last inserted ID: {cur.lastrowid}") cur.close() conn.close() ``` -------------------------------- ### Database Connection Management using Context Manager in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Shows how to use a context manager (`with` statement) for managing database connections, ensuring automatic cleanup even if errors occur. This is a more concise way to handle resource management compared to traditional try-finally blocks. ```python import libsql # Alternative: use context manager for connection try: with libsql.connect("app.db") as conn: conn.execute("SELECT * FROM nonexistent_table").fetchall() except Exception as e: print(f"Caught error: {type(e).__name__}") ``` -------------------------------- ### Connect to Local Database Source: https://context7.com/tursodatabase/libsql-python/llms.txt Establishes a connection to a local SQLite database file. Supports basic CRUD operations and parameterized queries. ```APIDOC ## Connect to Local Database ### Description Creates a connection to a local SQLite database file on disk, with optional encryption support. ### Method `libsql.connect()` ### Parameters #### Path Parameters - **db_path** (string) - Required - The path to the local SQLite database file. - **encryption_key** (string) - Optional - The encryption key for the database file. #### Query Parameters None #### Request Body None ### Request Example ```python import libsql conn = libsql.connect("local.db") cur = conn.cursor() conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)") conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com")) results = conn.execute("SELECT * FROM users WHERE name = ?", ("Alice",)).fetchall() print(results) conn.close() ``` ### Response #### Success Response (Connection Object) - **conn** (object) - A connection object implementing the DB-API 2.0 specification. #### Response Example ```json { "connection_status": "connected", "database": "local.db" } ``` ``` -------------------------------- ### Embedded Replica with Sync Source: https://context7.com/tursodatabase/libsql-python/llms.txt Creates a local database that synchronizes with a remote Turso database. Supports periodic syncing. ```APIDOC ## Embedded Replica with Sync ### Description Creates a local database that synchronizes with a remote Turso database, providing low-latency local reads with remote backup and sync capabilities. ### Method `libsql.connect()` ### Parameters #### Path Parameters - **db_path** (string) - Required - The path for the local replica database file. - **sync_url** (string) - Required - The URL of the remote Turso database to sync with. - **auth_token** (string) - Required - The authentication token for the remote Turso database. - **sync_interval** (float) - Optional - The interval in seconds between automatic synchronization attempts. Defaults to 5.0 seconds. #### Query Parameters None #### Request Body None ### Request Example ```python import libsql import os url = os.getenv("TURSO_DATABASE_URL") auth_token = os.getenv("TURSO_AUTH_TOKEN") conn = libsql.connect( "local_replica.db", sync_url=url, auth_token=auth_token, sync_interval=5.0 ) conn.sync() # Sync from remote before operations conn.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)") conn.execute("INSERT OR REPLACE INTO settings VALUES (?, ?)", ("theme", "dark")) conn.sync() # Sync to remote settings = conn.execute("SELECT * FROM settings").fetchall() print(settings) conn.close() ``` ### Response #### Success Response (Connection Object) - **conn** (object) - A connection object for the embedded replica database. #### Response Example ```json { "connection_status": "connected", "database": "local_replica.db", "sync_enabled": true } ``` ``` -------------------------------- ### Run Benchmarks (Python) Source: https://github.com/tursodatabase/libsql-python/blob/main/CONTRIBUTING.md Runs the libSQL Python SDK benchmarks using a dedicated Python script. ```shell python3 perf-libsql.py ``` -------------------------------- ### Work Offline with Libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Demonstrates how to perform database operations without network calls using libsql-python's offline mode. Changes are staged locally and applied later. This is useful for performance optimization and ensuring availability. ```python import libsql conn = libsql.connect("app.db") # Work offline (no network calls during queries) users = conn.execute("SELECT * FROM users").fetchall() print(f"Found {len(users)} users locally") # Changes stay local until offline mode is disabled conn.execute("INSERT INTO users VALUES (999, 'offline@example.com')") local_result = conn.execute("SELECT * FROM users WHERE id = 999").fetchone() print(local_result) # (999, 'offline@example.com') conn.close() ``` -------------------------------- ### Connect to Remote Turso Database with libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Establishes a connection to a remote Turso database using HTTP/HTTPS. Requires database URL and authentication token, typically retrieved from environment variables. Supports standard SQL operations and requires explicit commits for remote changes. ```python import libsql import os # Connect to remote Turso database url = os.getenv("TURSO_DATABASE_URL") # e.g., "libsql://your-db.turso.io" auth_token = os.getenv("TURSO_AUTH_TOKEN") conn = libsql.connect(url, auth_token=auth_token) # Remote operations work the same as local conn.execute("DROP TABLE IF EXISTS products") conn.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)") conn.execute("INSERT INTO products (name, price) VALUES (?, ?)", ("Widget", 19.99)) conn.execute("INSERT INTO products (name, price) VALUES (?, ?)", ("Gadget", 29.99)) # Commit changes to remote database conn.commit() # Query remote data products = conn.execute("SELECT name, price FROM products WHERE price < ?", (25.0,)).fetchall() print(products) # [('Widget', 19.99)] conn.close() ``` -------------------------------- ### Connect to In-Memory Database Source: https://context7.com/tursodatabase/libsql-python/llms.txt Creates an ephemeral in-memory database. Data is lost when the connection is closed. Ideal for testing and temporary data. ```APIDOC ## Connect to In-Memory Database ### Description Creates an ephemeral in-memory database that exists only for the duration of the connection, ideal for testing or temporary data processing. ### Method `libsql.connect()` ### Parameters #### Path Parameters - **db_path** (string) - Required - Use ":memory:" to create an in-memory database. #### Query Parameters None #### Request Body None ### Request Example ```python import libsql conn = libsql.connect(":memory:") conn.execute("CREATE TABLE temp_data (id INTEGER, value TEXT)") conn.execute("INSERT INTO temp_data VALUES (1, 'temporary')") result = conn.execute("SELECT * FROM temp_data").fetchall() print(result) conn.close() ``` ### Response #### Success Response (Connection Object) - **conn** (object) - A connection object for the in-memory database. #### Response Example ```json { "connection_status": "connected", "database": ":memory:" } ``` ``` -------------------------------- ### Run Tests (Python) Source: https://github.com/tursodatabase/libsql-python/blob/main/CONTRIBUTING.md Executes the test suite for the libSQL Python SDK using pytest. ```shell pytest ``` -------------------------------- ### Connect to Local SQLite Database with libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Establishes a connection to a local SQLite database file, allowing for standard SQL operations including table creation, data insertion, and querying. Supports optional encryption. Uses the Python DB-API 2.0 specification. ```python import libsql # Basic local connection conn = libsql.connect("local.db") cur = conn.cursor() # Create and populate table conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)") conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com")) conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Bob", "bob@example.com")) # Query data results = conn.execute("SELECT * FROM users WHERE name = ?", ("Alice",)).fetchall() print(results) # [(1, 'Alice', 'alice@example.com')] # Multiple results all_users = conn.execute("SELECT name, email FROM users ORDER BY name").fetchall() for name, email in all_users: print(f"{name}: {email}") conn.close() ``` -------------------------------- ### Transaction State and Autocommit Mode in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Shows how to inspect the transaction state (e.g., `in_transaction`) and autocommit mode of a libsql-python connection. Understanding these states is crucial for controlling data consistency and managing operations. ```python import libsql # Default mode: transactions required conn = libsql.connect("txn_state.db", isolation_level="DEFERRED") print(f"Isolation level: {conn.isolation_level}") print(f"In transaction: {conn.in_transaction}") conn.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER)") conn.execute("INSERT INTO test VALUES (1)") print(f"In transaction after DML: {conn.in_transaction}") conn.commit() print(f"In transaction after commit: {conn.in_transaction}") # Autocommit mode autoconn = libsql.connect("autocommit.db", isolation_level=None) print(f"Isolation level: {autoconn.isolation_level}") print(f"In transaction: {autoconn.in_transaction}") autoconn.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER)") autoconn.execute("INSERT INTO test VALUES (1)") print(f"In transaction after DML: {autoconn.in_transaction}") autoconn.close() conn.close() ``` -------------------------------- ### Safe Database Operations with Error Handling in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Demonstrates robust error handling and resource management for database operations using a try-except-finally block. It includes connection with a timeout, transaction rollback on error, and safe connection closure. This is crucial for production environments. ```python import libsql def safe_database_operation(): conn = None try: # Connect with timeout conn = libsql.connect("production.db", timeout=10.0) # Attempt operation conn.execute("CREATE TABLE IF NOT EXISTS audit_log (timestamp INTEGER, action TEXT)") conn.execute("INSERT INTO audit_log VALUES (?, ?)", (1234567890, "user_login")) # Query with error handling result = conn.execute("SELECT * FROM audit_log WHERE timestamp > ?", (0,)).fetchall() if not result: print("No audit logs found") else: print(f"Found {len(result)} audit log entries") return result except Exception as e: print(f"Database error: {e}") if conn: conn.rollback() return None finally: if conn: conn.close() print("Connection closed safely") # Execute with automatic cleanup logs = safe_database_operation() ``` -------------------------------- ### libsql Connection API Source: https://github.com/tursodatabase/libsql-python/blob/main/docs/api.md This section details the functions for creating and managing database connections using the libsql-python library. ```APIDOC ## `libsql` Module Functions ### connect(database) Creates a new database connection. #### Parameters - **database** (string) - Required - Path to the database file ### Connection Objects #### cursor() Creates a new database cursor. #### blobopen() Unimplemented. #### commit() Commits the current transaction and starts a new one. #### rollback() Rolls back the current transaction and starts a new one. #### close() Closes the database connection. #### with statement Connection objects can be used as context managers to ensure that transactions are properly committed or rolled back. #### execute(sql, parameters=()) Create a new cursor object and executes the SQL statement. #### executemany(sql, parameters) Create a new cursor object and Execute the SQL statement for every item in `parameters` array. ##### Parameters - **sql** (string) - Required - Path to the database file - **parameters** (array) - Required - Array of parameter tuples to execute SQL with. #### executescript() Unimplemented. #### create_function() Unimplemented. #### create_aggregate() Unimplemented. #### create_window_function() Unimplemented. #### create_collation() Unimplemented. #### interrupt() Unimplemented. #### set_authorizer() Unimplemented. #### set_progress_handler() Unimplemented. #### set_trace_callback() Unimplemented. #### enable_load_extension() Unimplemented. #### load_extension() Unimplemented. #### iterdump() Unimplemented. #### backup() Unimplemented. #### getlimit() Unimplemented. #### setlimit() Unimplemented. #### getconfig() Unimplemented. #### setconfig() Unimplemented. #### serialize() Unimplemented. #### deserialize() Unimplemented. #### autocommit Controls PEP 249 transaction handling behavior. #### in_transaction Returns `True` if there's an active transaction with uncommitted changes; otherwise returns `False`. #### isolation_level Transaction handling mode configuration. Possible values are `"DEFERRED"`, `"IMMEDIATE"`, `"EXCLUSIVE"`, or `None` for auto-commit mode. #### row_factory Unimplemented. #### text_factory Unimplemented. #### total_changes Unimplemented. ``` -------------------------------- ### Run SQLite Benchmarks (Python) Source: https://github.com/tursodatabase/libsql-python/blob/main/CONTRIBUTING.md Runs the standard SQLite benchmarks for comparison with libSQL benchmarks using a Python script. ```shell python3 perf-sqlite3.py ``` -------------------------------- ### Context Manager for Automatic Transaction Handling in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Illustrates using Python's context manager protocol (`with conn:`) for automatic transaction management. The transaction commits upon successful exit of the 'with' block or rolls back if an exception occurs. This simplifies transaction handling and reduces boilerplate code. ```python import libsql conn = libsql.connect("context.db") # Setup test data conn.execute("DROP TABLE IF EXISTS inventory") conn.execute("CREATE TABLE inventory (item TEXT PRIMARY KEY, quantity INTEGER)") conn.execute("INSERT INTO inventory VALUES ('apples', 100)") conn.execute("INSERT INTO inventory VALUES ('oranges', 75)") # Successful transaction (auto-commits) try: with conn: conn.execute("UPDATE inventory SET quantity = quantity - 10 WHERE item = 'apples'") conn.execute("UPDATE inventory SET quantity = quantity + 5 WHERE item = 'oranges'") print("Success:", conn.execute("SELECT * FROM inventory").fetchall()) except Exception as e: print(f"Error: {e}") # Failed transaction (auto-rollback) try: with conn: conn.execute("UPDATE inventory SET quantity = quantity - 20 WHERE item = 'apples'") # Simulate an error raise ValueError("Simulated error during transaction") conn.execute("UPDATE inventory SET quantity = quantity + 20 WHERE item = 'oranges'") except ValueError as e: print(f"Caught error: {e}") print("After rollback:", conn.execute("SELECT * FROM inventory").fetchall()) conn.close() ``` -------------------------------- ### libsql Cursor API Source: https://github.com/tursodatabase/libsql-python/blob/main/docs/api.md This section details the functions for interacting with database cursors using the libsql-python library. ```APIDOC ## `Cursor` objects ### execute(sql, parameters=()) Execute one SQL statement. ### executemany(sql, parameters) Execute the SQL statement for every item in `parameters` array. #### Parameters - **sql** (string) - Required - Path to the database file - **parameters** (array) - Required - Array of parameter tuples to execute SQL with. ### executescript() Unimplemented. ### fetchone() Return next row in result set. ### fetchmany(size = cursor.arraysize) Return `size` next rows in result set. If there are no more rows left, returns an empty list. ### fetchall() Return all rows in result set. ### close() Unimplemented. ### setinputsizes() Unimplemented. ### setoutputsize() Unimplemented. ### arraysize The number of rows returned by `fetchmany()` by default. ### connection Unimplemented. ### description Column names of the query that was run last. ### lastrowid Returns the row ID of the last inserted row. ### rowcount Returns the number of rows changed by `INSERT`, `UPDATE`, `DELETE`, and `REPLACE` statements. For other types of statements, returns -1. ### row_factory Unimplemented. ``` -------------------------------- ### Manual Transaction Rollback in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Demonstrates how to manually execute a rollback operation in libsql-python. This is useful when a transaction's operations need to be undone before committing. It requires explicit calls to execute() and rollback(). ```python import libsql conn = libsql.connect("example.db") # Perform an update operation conn.execute("UPDATE accounts SET balance = balance - 500 WHERE id = 1") print("Before rollback:", conn.execute("SELECT * FROM accounts").fetchall()) # Rollback the transaction to revert changes conn.rollback() print("After rollback:", conn.execute("SELECT * FROM accounts").fetchall()) conn.close() ``` -------------------------------- ### Connect to In-Memory Database with libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Creates an ephemeral in-memory database connection. Data stored in this database is lost when the connection is closed, making it suitable for temporary data processing or testing scenarios. Implements standard SQL operations. ```python import libsql # In-memory database (lost when connection closes) conn = libsql.connect(":memory:") conn.execute("CREATE TABLE temp_data (id INTEGER, value TEXT)") conn.execute("INSERT INTO temp_data VALUES (1, 'temporary')") conn.execute("INSERT INTO temp_data VALUES (2, 'ephemeral')") result = conn.execute("SELECT * FROM temp_data").fetchall() print(result) # [(1, 'temporary'), (2, 'ephemeral')] conn.close() # Data is now gone ``` -------------------------------- ### Execute Multiple Statements with executescript in Libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Employs the `executescript` method in libsql-python to run multiple SQL statements sequentially in a single batch. This is particularly useful for complex schema initializations or database migrations. ```python import libsql conn = libsql.connect("schema.db") cur = conn.cursor() # Execute multiple statements at once cur.executescript(""" DROP TABLE IF EXISTS departments; DROP TABLE IF EXISTS employees; CREATE TABLE departments ( id INTEGER PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE employees ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, department_id INTEGER, FOREIGN KEY (department_id) REFERENCES departments(id) ); INSERT INTO departments (id, name) VALUES (1, 'Engineering'); INSERT INTO departments (id, name) VALUES (2, 'Sales'); INSERT INTO departments (id, name) VALUES (3, 'Marketing'); INSERT INTO employees (name, department_id) VALUES ('Alice', 1); INSERT INTO employees (name, department_id) VALUES ('Bob', 1); INSERT INTO employees (name, department_id) VALUES ('Charlie', 2); """) # Query the initialized schema result = conn.execute(""" SELECT e.name, d.name as department FROM employees e JOIN departments d ON e.department_id = d.id ORDER BY e.name """).fetchall() for emp_name, dept_name in result: print(f"{emp_name} works in {dept_name}") conn.close() ``` -------------------------------- ### Connect to Remote Turso Database Source: https://context7.com/tursodatabase/libsql-python/llms.txt Connects to a remote Turso database using HTTP/HTTPS. Requires database URL and authentication token. ```APIDOC ## Connect to Remote Turso Database ### Description Establishes a connection to a remote Turso database using HTTP/HTTPS protocol with authentication. ### Method `libsql.connect()` ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the remote Turso database (e.g., "libsql://your-db.turso.io"). - **auth_token** (string) - Required - The authentication token for accessing the Turso database. #### Query Parameters None #### Request Body None ### Request Example ```python import libsql import os url = os.getenv("TURSO_DATABASE_URL") auth_token = os.getenv("TURSO_AUTH_TOKEN") conn = libsql.connect(url, auth_token=auth_token) conn.execute("DROP TABLE IF EXISTS products") conn.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)") conn.execute("INSERT INTO products (name, price) VALUES (?, ?)", ("Widget", 19.99)) conn.commit() # Commit changes to remote database products = conn.execute("SELECT name, price FROM products WHERE price < ?", (25.0,)).fetchall() print(products) conn.close() ``` ### Response #### Success Response (Connection Object) - **conn** (object) - A connection object for the remote Turso database. #### Response Example ```json { "connection_status": "connected", "database": "libsql://your-db.turso.io" } ``` ``` -------------------------------- ### Transaction Management in Libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Demonstrates explicit transaction control in libsql-python using `commit()` and `rollback()` methods to ensure ACID compliance. This allows for atomic operations, guaranteeing data consistency. ```python import libsql conn = libsql.connect("transactions.db") # Create test table conn.execute("DROP TABLE IF EXISTS accounts") conn.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, balance REAL)") conn.execute("INSERT INTO accounts VALUES (1, 'Alice', 1000.0)") conn.execute("INSERT INTO accounts VALUES (2, 'Bob', 500.0)") # Transaction that commits print("Before transaction:", conn.execute("SELECT * FROM accounts").fetchall()) conn.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1") conn.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2") conn.commit() print("After commit:", conn.execute("SELECT * FROM accounts").fetchall()) # [('Alice', 900.0), ('Bob', 600.0)] # Example of a rollback (not executed in this snippet, but demonstrates usage) # conn.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1") # conn.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2") # conn.rollback() # print("After rollback:", conn.execute("SELECT * FROM accounts").fetchall()) ``` -------------------------------- ### Batch Operations with executemany in Libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Utilizes the `executemany` method in libsql-python for efficient execution of the same SQL statement with varying parameters. Ideal for bulk inserts or updates, significantly improving performance for large datasets. ```python import libsql conn = libsql.connect("batch.db") # Prepare batch data users_data = [ ("user1@example.com", "John", "Doe"), ("user2@example.com", "Jane", "Smith"), ("user3@example.com", "Bob", "Johnson"), ("user4@example.com", "Alice", "Williams"), ] # Create table conn.execute("DROP TABLE IF EXISTS contacts") conn.execute("CREATE TABLE contacts (email TEXT PRIMARY KEY, first_name TEXT, last_name TEXT)") # Batch insert cur = conn.cursor() cur.executemany( "INSERT INTO contacts (email, first_name, last_name) VALUES (?, ?, ?)", users_data ) print(f"Inserted {cur.rowcount} rows") # Verify results all_contacts = conn.execute("SELECT * FROM contacts ORDER BY last_name").fetchall() for email, first, last in all_contacts: print(f"{first} {last} <{email}>") conn.close() ``` -------------------------------- ### Find Similar Movies using Vector Search in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Finds the top 3 most similar movies to a given query vector '[4,5,6]' using the `vector_top_k` function. The results are joined with the 'movies' table and ordered by year. This demonstrates a vector similarity search. ```python query_vector = '[4,5,6]' results = conn.execute(""" SELECT title, year FROM vector_top_k('movies_idx', ?, 3) JOIN movies ON movies.rowid = id ORDER BY year """, (query_vector,)).fetchall() print("Most similar movies:") for title, year in results: print(f" {title} ({year})") ``` -------------------------------- ### Configure Offline Mode Embedded Replica with libsql-python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Creates an embedded replica that operates exclusively in offline mode. It reads data from the local database but does not attempt any remote writes or synchronization. An initial sync operation is required to populate the local database. ```python import libsql import os url = os.getenv("TURSO_DATABASE_URL") auth_token = os.getenv("TURSO_AUTH_TOKEN") # Offline mode: reads from local, no remote writes conn = libsql.connect( "offline_replica.db", sync_url=url, auth_token=auth_token, offline=True ) # Initial sync to pull data conn.sync() ``` -------------------------------- ### Offline Mode Embedded Replica Source: https://context7.com/tursodatabase/libsql-python/llms.txt Creates an embedded replica that operates in offline mode, only reading from the local database without remote writes. ```APIDOC ## Offline Mode Embedded Replica ### Description Creates an embedded replica that operates in offline mode, only reading from the local database without attempting remote writes. ### Method `libsql.connect()` ### Parameters #### Path Parameters - **db_path** (string) - Required - The path for the local replica database file. - **sync_url** (string) - Required - The URL of the remote Turso database to sync with. - **auth_token** (string) - Required - The authentication token for the remote Turso database. - **offline** (boolean) - Required - Set to `True` to enable offline mode. #### Query Parameters None #### Request Body None ### Request Example ```python import libsql import os url = os.getenv("TURSO_DATABASE_URL") auth_token = os.getenv("TURSO_AUTH_TOKEN") conn = libsql.connect( "offline_replica.db", sync_url=url, auth_token=auth_token, offline=True ) conn.sync() # Initial sync to pull data # Perform read operations on the local database # Writes will not be synced remotely conn.close() ``` ### Response #### Success Response (Connection Object) - **conn** (object) - A connection object for the offline embedded replica database. #### Response Example ```json { "connection_status": "connected", "database": "offline_replica.db", "offline_mode": true } ``` ``` -------------------------------- ### Insert Movies with Vector Embeddings in Python Source: https://context7.com/tursodatabase/libsql-python/llms.txt Inserts movie data, including 3-dimensional vector embeddings, into a 'movies' table. The `vector32` function is used to initialize the embeddings. This snippet demonstrates basic data insertion with vector types. ```python conn.execute(""" INSERT INTO movies (title, year, embedding) VALUES ('Napoleon', 2023, vector32('[1,2,3]')), ('Black Hawk Down', 2001, vector32('[10,11,12]')), ('Gladiator', 2000, vector32('[7,8,9]')), ('Blade Runner', 1982, vector32('[4,5,6]')) """) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.