### Install pyfirebirdsql from source distribution Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/installation.rst This method installs pyfirebirdsql from its source distribution. It involves decompressing the source, running the setup script, and verifying the installation by importing the library. ```Shell (decompress pyfirebirdsql into *temp_dir*) cd *temp_dir* python setup.py install python -c "import firebirdsql" (delete *temp_dir*) ``` -------------------------------- ### Install pyfirebirdsql using pip Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/installation.rst This command installs the pyfirebirdsql library using the pip package installer. Ensure you have pip installed and a stable internet connection. ```Shell pip install firebirdsql ``` -------------------------------- ### Install pyfirebirdsql from FreeBSD ports Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/installation.rst This command sequence installs pyfirebirdsql on FreeBSD systems using the ports collection. It navigates to the port directory, then builds and installs the package. ```Shell # cd /usr/ports/databases/py-firebirdsql/ # make install clean ``` -------------------------------- ### Test pyfirebirdsql installation Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/installation.rst This command verifies a successful pyfirebirdsql installation by importing the library as 'fb' and printing its version number. Ensure you are not in the source directory to avoid conflicts. ```Python python -c "import firebirdsql as fb; print fb.__version__" ``` -------------------------------- ### Create and Populate Languages Table Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst SQL code to create a 'languages' table with 'name' and 'year_released' columns and insert sample data. ```sql create table languages ( name varchar(20), year_released integer ); insert into languages (name, year_released) values ('C', 1972); insert into languages (name, year_released) values ('Python', 1991); ``` -------------------------------- ### Connect to Firebird Database Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Establishes a connection to a Firebird database using pyfirebirdsql. Demonstrates connecting with a DSN string or by specifying host and database path separately. Includes options for user and password. ```python import firebirdsql # The server is named 'bison'; the database file is at '/temp/test.fdb'. con = firebirdsql.connect(dsn='bison:/temp/test.fdb', user='sysdba', password='pass') # Or, equivalently: con = firebirdsql.connect( host='bison', database='/temp/test.fdb', user='sysdba', password='pass' ) ``` -------------------------------- ### Python Database Info API Call Example Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates a specific call to the database_info method for retrieving user names, demonstrating the expected input for string results. ```python con.database_info(firebirdsql.isc_info_user_names, 's') ``` -------------------------------- ### Fetch All Rows from Languages Table Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Connects to the database, executes a SELECT statement to retrieve all rows from the 'languages' table ordered by release year, and prints the fetched rows. ```python import firebirdsql con = firebirdsql.connect(dsn='/temp/test.fdb', user='sysdba', password='masterkey') # Create a Cursor object that operates in the context of Connection con: cur = con.cursor() # Execute the SELECT statement: cur.execute("select * from languages order by year_released") # Retrieve all rows as a sequence and print that sequence: print cur.fetchall() ``` -------------------------------- ### Python Database Info API Usage Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Shows how to use the Connection.database_info method to retrieve server and database information. It includes examples for getting memory usage (integer) and database ID/hostname (string). ```python import firebirdsql con = firebirdsql.connect(dsn='localhost:/temp/test.db', user='sysdba', password='pass') # Retrieving an integer info item is quite simple. bytesInUse = con.database_info(firebirdsql.isc_info_current_memory, 'i') print 'The server is currently using %d bytes of memory.' % bytesInUse # Retrieving a string info item is somewhat more involved, because the # information is returned in a raw binary buffer that must be parsed # according to the rules defined in the Interbase® 6 API Guide section # entitled "Requesting buffer items and result buffer values" (page 51). # # Often, the buffer contains a succession of length-string pairs # (one byte telling the length of s, followed by s itself). # Function firebirdsql.raw_byte_to_int is provided to convert a raw # byte to a Python integer (see examples below). buf = con.database_info(firebirdsql.isc_info_db_id, 's') # Parse the filename from the buffer. beginningOfFilename = 2 # The second byte in the buffer contains the size of the database filename # in bytes. lengthOfFilename = firebirdsql.raw_byte_to_int(buf[1]) filename = buf[beginningOfFilename:beginningOfFilename + lengthOfFilename] # Parse the host name from the buffer. beginningOfHostName = (beginningOfFilename + lengthOfFilename) + 1 # The first byte after the end of the database filename contains the size # of the host name in bytes. lengthOfHostName = firebirdsql.raw_byte_to_int(buf[beginningOfHostName - 1]) host = buf[beginningOfHostName:beginningOfHostName + lengthOfHostName] print 'We are connected to the database at %s on host %s.' % (filename, host) ``` -------------------------------- ### Python Event Handler Output Example Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates the output of an event handler waiting for specific events and receiving notifications. It highlights how only registered events are processed. ```python HANDLER: About to wait for the occurrence of one of ['test_event_a', 'test_event_b']... HANDLER: An event notification has arrived: {'test_event_a': 2, 'test_event_b': 1} ``` -------------------------------- ### Print Languages Table with Formatting Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst A simplistic table printer for the 'languages' table. It fetches data, prints a header based on cursor description, and then iterates through rows, printing each field left-justified within its maximum width. ```python import firebirdsql as fb TABLE_NAME = 'languages' SELECT = 'select * from %s order by year_released' % TABLE_NAME con = fb.connect(dsn='/temp/test.fdb', user='sysdba', password='masterkey') cur = con.cursor() cur.execute(SELECT) # Print a header. for fieldDesc in cur.description: # Description name print fieldDesc[0] , print # Finish the header with a newline. print '-' * 78 # For each row, print the value of each field left-justified within # the maximum possible width of that field. fieldIndices = range(len(cur.description)) for row in cur: for fieldIndex in fieldIndices: fieldValue = str(row[fieldIndex]) #DESCRIPTION_DISPLAY_SIZE fieldMaxWidth = cur.description[fieldIndex][2] print fieldValue.ljust(fieldMaxWidth) , print # Finish the row with a newline. ``` -------------------------------- ### Connect to Firebird Database with UTF-8 Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Connects to a Firebird database using SQL Dialect 1 and specifies UTF-8 as the character set for the connection. Requires user and password credentials. ```python import firebirdsql con = firebirdsql.connect( dsn='bison:/temp/test.fdb', user='sysdba', password='pass', charset='UTF8' # specify a character set for the connection ) ``` -------------------------------- ### Get User Connections with db_info Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates using `Connection.db_info()` to retrieve the number of open connections per user. It establishes multiple connections and then queries `isc_info_user_names` to get a dictionary mapping usernames to connection counts. ```python import os.path import firebirdsql DB_FILENAME = r'D:\\temp\\test-20.firebird' DSN = 'localhost:' + DB_FILENAME ############################################################################### # Querying an isc_info_* item that has a complex result: ############################################################################### # Establish three connections to the test database as TEST_USER_1, and one # connection as SYSDBA. Then use the Connection.db_info method to query the # number of attachments by each user to the test database. testUserCons = [] for i in range(3): tCon = firebirdsql.connect(dsn=DSN, user='test_user_1', password='pass') testUserCons.append(tCon) con = firebirdsql.connect(dsn=DSN, user='sysdba', password='masterkey') print 'Open connections to this database:' print con.db_info(firebirdsql.isc_info_user_names) ############################################################################### # Querying multiple isc_info_* items at once: ############################################################################### # Request multiple db_info items at once, specifically the page size of the # database and the number of pages currently allocated. Compare the size # computed by that method with the size reported by the file system. # The advantages of using db_info instead of the file system to compute # database size are: # - db_info works seamlessly on connections to remote databases that reside # in file systems to which the client program lacks access. # - If the database is split across multiple files, db_info includes all of # them. res = con.db_info( [firebirdsql.isc_info_page_size, firebirdsql.isc_info_allocation] ) pagesAllocated = res[firebirdsql.isc_info_allocation] pageSize = res[firebirdsql.isc_info_page_size] print '\ndb_info indicates database size is', pageSize * pagesAllocated, 'bytes' print 'os.path.getsize indicates size is ', os.path.getsize(DB_FILENAME), 'bytes' ``` -------------------------------- ### Insert New Languages into Table Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Demonstrates inserting multiple new language records into the 'languages' table using pyfirebirdsql. It prepares a list of tuples, each representing a language with its name and release year. ```python import firebirdsql con = firebirdsql.connect(dsn='/temp/test.fdb', user='sysdba', password='masterkey') cur = con.cursor() newLanguages = [ ('Lisp', 1958), ``` -------------------------------- ### Execute Stored Procedure and Get Output Parameters with pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Illustrates how to execute a Firebird stored procedure and retrieve its output parameters using `cur.callproc`. The output parameters are fetched as the first row of a result set, and the transaction should be committed if side effects occurred. ```python cur.callproc("the_proc", (input1, input2)) # If there are output parameters, retrieve them as though they were the # first row of a result set. For example: outputParams = cur.fetchone() con.commit() # If the procedure had any side effects, commit them. ``` -------------------------------- ### Fetch Single Row Iteratively Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Demonstrates fetching single rows from the 'languages' table one at a time using a cursor. Shows two methods: unpacking row elements directly and accessing elements by index. ```python import firebirdsql con = firebirdsql.connect(dsn='/temp/test.fdb', user='sysdba', password='masterkey') cur = con.cursor() SELECT = "select name, year_released from languages order by year_released" # 1. Iterate over the rows available from the cursor, unpacking the # resulting sequences to yield their elements (name, year_released): cur.execute(SELECT) for (name, year_released) in cur: print '%s has been publicly available since %d.' % (name, year_released) # 2. Equivalently: cur.execute(SELECT) for row in cur: print '%s has been publicly available since %d.' % (row[0], row[1]) ``` -------------------------------- ### Get Firebird Home Directory using pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Retrieves the 'RootDirectory' setting from firebird.conf using the Connection.getHomeDir() method. This shows the directory where Firebird is installed. ```python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getHomeDir() ``` -------------------------------- ### Python: Handle Backup Error with Invalid Path Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates how the backup method raises an exception when an invalid backup path is provided. This example shows a typical traceback when the engine cannot open the specified backup file. ```python from firebirdsql import services con = services.connect(user='sysdba', password='masterkey') # Pass an invalid backup path to the engine: backupLog = con.backup('C:/temp/test.db', 'BOGUS/PATH/test_backup.fbk') print backupLog ``` -------------------------------- ### Get Database Statistics with pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates how to use the getStatistics method to retrieve database statistics, mimicking the functionality of the gstat command-line utility. It shows examples of calling getStatistics with various boolean parameters to control the output. ```python from firebirdsql import services con = services.connect(user='sysdba', password='masterkey') # Equivalent to 'gstat -u sysdba -p masterkey C:/temp/test.db': print con.getStatistics('C:/temp/test.db') # Equivalent to 'gstat -u sysdba -p masterkey -header C:/temp/test.db': print con.getStatistics('C:/temp/test.db', showOnlyDatabaseHeaderPages=True) # Equivalent to 'gstat -u sysdba -p masterkey -log C:/temp/test.db': print con.getStatistics('C:/temp/test.db', showOnlyDatabaseLogPages=True) # Equivalent to 'gstat -u sysdba -p masterkey -data -index -system C:/temp/test.db': print con.getStatistics('C:/temp/test.db', showUserDataPages=True, showUserIndexPages=True, showSystemTablesAndIndexes=True ) ``` -------------------------------- ### Query Database Size with db_info Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates querying multiple database information items simultaneously using `Connection.db_info()`. This example retrieves the page size and allocated pages to calculate the database size, comparing it with the size reported by the file system. ```python res = con.db_info( [firebirdsql.isc_info_page_size, firebirdsql.isc_info_allocation] ) pagesAllocated = res[firebirdsql.isc_info_allocation] pageSize = res[firebirdsql.isc_info_page_size] print '\ndb_info indicates database size is', pageSize * pagesAllocated, 'bytes' print 'os.path.getsize indicates size is ', os.path.getsize(DB_FILENAME), 'bytes' ``` -------------------------------- ### Install Input Translator for Fixed Point Types Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Installs an input translator for fixed point types (NUMERIC/DECIMAL SQL types) into a pyfirebirdsql connection. This allows custom conversion of these data types. ```python con.set_type_trans_in( {'FIXED': fixed_input_translator_function} ) ``` -------------------------------- ### Get Firebird Server Architecture Information Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates how to retrieve platform information, including hardware architecture and operating system family, for the Firebird server using the getArchitecture() method. ```Python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getArchitecture() ``` -------------------------------- ### Asyncio Connection and Query Firebird SQL (Python) Source: https://github.com/nakagami/pyfirebirdsql/blob/master/README.rst Provides an example of using the asyncio API for asynchronous database operations with Firebird. It shows how to create an asynchronous connection, execute a query, fetch results, and run the coroutine. ```Python import asyncio import firebirdsql async def conn_example(): conn = await firebirdsql.aio.connect( host='localhost', database='/foo/bar.fdb', port=3050, user='alice', password='secret' ) cur = conn.cursor() await cur.execute("select * from baz") print(await cur.fetchall()) asyncio.run(conn_example()) ``` -------------------------------- ### Python: Named Cursors for Scrolling Updates Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Example of using named cursors with `SELECT ... FOR UPDATE` to perform scrolling updates. ```python import firebirdsql con = firebirdsql.connect(dsn='localhost:/temp/test.db', user='sysdba', password='pass') curScroll = con.cursor() curUpdate = con.cursor() curScroll.execute("select city from addresses for update") curScroll.name = 'city_scroller' update = "update addresses set city=? where current of " + curScroll.name for (city,) in curScroll: city = ... # make some changes to city curUpdate.execute( update, (city,) ) con.commit() ``` -------------------------------- ### Insert Multiple Rows with pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Demonstrates inserting multiple rows into a 'languages' table using `executemany` with parameterized SQL. It highlights the importance of committing the transaction to save changes. ```python cur.executemany("insert into languages (name, year_released) values (?, ?)", newLanguages ) # The changes will not be saved unless the transaction is committed explicitly: con.commit() ``` -------------------------------- ### Python: Demonstrate pyfirebirdsql Savepoint Manipulation Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst This example demonstrates how to use the pyfirebirdsql API to manage transaction savepoints. It shows creating savepoints, inserting data, and rolling back to specific savepoints or the entire transaction. ```python import firebirdsql con = firebirdsql.connect(dsn='localhost:/temp/test.db', user='sysdba', password='pass') cur = con.cursor() cur.execute("recreate table test_savepoints (a integer)") con.commit() print 'Before the first savepoint, the contents of the table are:' cur.execute("select * from test_savepoints") print ' ', cur.fetchall() cur.execute("insert into test_savepoints values (?)", [1]) con.savepoint('A') print 'After savepoint A, the contents of the table are:' cur.execute("select * from test_savepoints") print ' ', cur.fetchall() cur.execute("insert into test_savepoints values (?)", [2]) con.savepoint('B') print 'After savepoint B, the contents of the table are:' cur.execute("select * from test_savepoints") print ' ', cur.fetchall() cur.execute("insert into test_savepoints values (?)", [3]) con.savepoint('C') print 'After savepoint C, the contents of the table are:' cur.execute("select * from test_savepoints") print ' ', cur.fetchall() con.rollback(savepoint='A') print 'After rolling back to savepoint A, the contents of the table are:' cur.execute("select * from test_savepoints") print ' ', cur.fetchall() con.rollback() print 'After rolling back entirely, the contents of the table are:' cur.execute("select * from test_savepoints") print ' ', cur.fetchall() ``` -------------------------------- ### PyFirebirdSQL CT_ROLLBACK Timeout Example Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates handling connection timeouts with firebirdsql.CT_ROLLBACK. This example shows how an unresolved transaction is rolled back when the connection times out, and the connection is closed transparently. ```python import threading, time import firebirdsql import timeout_authorizer authorizer = timeout_authorizer.TimeoutAuthorizer(firebirdsql.CT_ROLLBACK) connectionTimedOut = threading.Event() def callback_after(info): print print 'The unresolved transaction was rolled back; the connection has been' print ' closed transparently.' print connectionTimedOut.set() con = firebirdsql.connect(dsn=r'localhost:D:\temp\test.db', user='sysdba', password='masterkey', timeout={ 'period': 3.0, 'callback_before': authorizer, 'callback_after': callback_after, } ) cur = con.cursor() cur.execute("recreate table test (a int, b char(1))") con.commit() cur.executemany("insert into test (a, b) values (?, ?)", [(1, 'A'), (2, 'B'), (3, 'C')] ) con.commit() cur.execute("select * from test") print 'BEFORE:', cur.fetchall() cur.execute("update test set b = 'X' where a = 2") authorizer.authorize() connectionTimedOut.wait() # The value of the second column of the second row of the table will have # reverted to 'B' when the transaction that changed it to 'X' was rolled back. # The cur.execute call on the next line will transparently reactivate the # connection, which was timed out transparently. cur.execute("select * from test") rows = cur.fetchall() assert rows[1][1] == 'B' print 'AFTER: ', rows ``` -------------------------------- ### PyFirebirdSQL CT_COMMIT Timeout Example Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates handling connection timeouts with firebirdsql.CT_COMMIT. This example shows how an unresolved transaction is committed when the connection times out, and the connection is closed transparently, persisting changes. ```python import threading, time import firebirdsql import timeout_authorizer authorizer = timeout_authorizer.TimeoutAuthorizer(firebirdsql.CT_COMMIT) connectionTimedOut = threading.Event() def callback_after(info): print print 'The unresolved transaction was committed; the connection has been' print ' closed transparently.' print connectionTimedOut.set() con = firebirdsql.connect(dsn=r'localhost:D:\temp\test.db', user='sysdba', password='masterkey', timeout={ 'period': 3.0, 'callback_before': authorizer, 'callback_after': callback_after, } ) cur = con.cursor() cur.execute("recreate table test (a int, b char(1))") con.commit() cur.executemany("insert into test (a, b) values (?, ?)", [(1, 'A'), (2, 'B'), (3, 'C')] ) con.commit() cur.execute("select * from test") print 'BEFORE:', cur.fetchall() cur.execute("update test set b = 'X' where a = 2") authorizer.authorize() connectionTimedOut.wait() # The modification of the value of the second column of the second row of the # table from 'B' to 'X' will have persisted, because the TimeoutThread # committed the transaction before it timed the connection out. # The cur.execute call on the next line will transparently reactivate the # connection, which was timed out transparently. cur.execute("select * from test") rows = cur.fetchall() assert rows[1][1] == 'X' print 'AFTER: ', rows ``` -------------------------------- ### Fix Install Problem Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/changelog.rst Resolves an installation problem reported in issue #109. This update ensures a smoother and more reliable installation process for the library. ```Python # Conceptual fix for installation issues # setup.py or pyproject.toml modifications to resolve dependencies or build steps ``` -------------------------------- ### PyFirebirdSQL CT_NONTRANSPARENT Timeout Example Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates a connection timeout scenario using firebirdsql.CT_NONTRANSPARENT. The code shows how a transaction is handled when the connection times out and is reactivated transparently. ```python import firebirdsql # before callback returned firebirdsql.CT_NONTRANSPARENT: cur.execute("select * from test") ``` -------------------------------- ### Event Notification Example Output Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Shows the expected output from the Python event handler program after the producer commits a transaction, indicating that events 'test_event_a' and 'test_event_b' have occurred. ```python PRODUCER: Committing transaction that will cause event notification to be sent. ``` -------------------------------- ### Example pyfirebirdsql Database Array Handling Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates inserting a nested Python list (representing a database array) into a table field and then retrieving it using pyfirebirdsql. It includes table creation, data insertion, and data retrieval. ```python import firebirdsql con = firebirdsql.connect(dsn='localhost:/temp/test.db', user='sysdba', password='pass') con.execute_immediate("recreate table array_table (a int[3,4])") con.commit() cur = con.cursor() arrayIn = [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] print 'arrayIn: %s' % arrayIn cur.execute("insert into array_table values (?)", (arrayIn,)) cur.execute("select a from array_table") arrayOut = cur.fetchone()[0] print 'arrayOut: %s' % arrayOut con.commit() ``` -------------------------------- ### Python: Execute SQL Insert Statements Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst This snippet shows basic SQL INSERT operations using a database cursor. It's presented as an example of statements that could benefit from prepared statements for performance. ```python cur.execute("insert into the_table (a,b,c) values ('aardvark', 1, 0.1)") ... cur.execute("insert into the_table (a,b,c) values ('zymurgy', 2147483647, 99999.999)") ``` -------------------------------- ### Insert and Retrieve BLOBs in Materialized Mode Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates inserting string data as BLOBs and retrieving them. In materialized mode, BLOBs are treated as Python strings. The example shows basic table creation, insertion, and retrieval using SELECT. ```python import firebirdsql con = firebirdsql.connect(dsn=r'localhost:D:\temp\test-20.firebird', user='sysdba', password='masterkey' ) cur = con.cursor() cur.execute("recreate table blob_test (a blob)") con.commit() # --- Materialized mode (str objects for both input and output) --- # Insertion: cur.execute("insert into blob_test values (?)", ('abcdef',)) cur.execute("insert into blob_test values (?)", ('ghijklmnop',)) # Retrieval: cur.execute("select * from blob_test") print 'Materialized retrieval (as str):' print cur.fetchall() cur.execute("delete from blob_test") ``` -------------------------------- ### Get Firebird Security Database Path using pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Retrieves the location of the server's security database using Connection.getSecurityDatabasePath(). This database stores user definitions. ```python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getSecurityDatabasePath() ``` -------------------------------- ### Get Firebird Server Version Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates how to obtain the server's true version string using the getServerVersion() method from the Services API. This differs from the server_version property which uses an older API. ```Python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getServerVersion() ``` -------------------------------- ### Retrieve Result Set from Stored Procedure with pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/tutorial.rst Shows how to retrieve a result set from a Firebird stored procedure using `cur.execute` with a `SELECT` statement and parameterized inputs. It includes a note on committing transactions if the procedure has side effects. ```python cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) # Ordinary fetch code here, such as: for row in cur: ... # process row con.commit() # If the procedure had any side effects, commit them. ``` -------------------------------- ### Handle Connection Timeout Race Condition in Python Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates a scenario where a connection timeout might occur while a transaction is still active. This example shows how to set a short timeout and perform operations, then waits to observe the effect on subsequent queries. ```python import time import firebirdsql con = firebirdsql.connect(dsn=r'localhost:D:\temp\test.db', user='sysdba', password='masterkey', timeout={'period': 3.0} ) cur = con.cursor() cur.execute("recreate table test (a int, b char(1))") con.commit() cur.executemany("insert into test (a, b) values (?, ?)", [(1, 'A'), (2, 'B'), (3, 'C')] ) con.commit() cur.execute("select * from test") print 'BEFORE:', cur.fetchall() cur.execute("update test set b = 'X' where a = 2") time.sleep(6.0) cur.execute("select * from test") print 'AFTER: ', cur.fetchall() ``` -------------------------------- ### Python: Create Simple Database Backup Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates the simplest form of the backup method to create a single backup file from database content. It connects to the database and initiates the backup process, printing the resulting log. ```python from firebirdsql import services con = services.connect(user='sysdba', password='masterkey') backupLog = con.backup('C:/temp/test.db', 'C:/temp/test_backup.fbk') print backupLog ``` -------------------------------- ### Python: Prepare and inspect SQL statement Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Illustrates preparing an SQL INSERT statement using `cur.prep()` and then inspecting its properties such as the SQL string, statement type, number of parameters, and execution plan. ```python import time import firebirdsql con = firebirdsql.connect(dsn=r'localhost:D:\\temp\\test-20.firebird', user='sysdba', password='masterkey' ) cur = con.cursor() # Create supporting database entities: cur.execute("recreate table t (a int, b varchar(50))") con.commit() cur.execute("create unique index unique_t_a on t(a)") con.commit() # Explicitly prepare the insert statement: psIns = cur.prep("insert into t (a,b) values (?,?)") print 'psIns.sql: "%s"' % psIns.sql print 'psIns.statement_type == firebirdsql.isc_info_sql_stmt_insert:', ( psIns.statement_type == firebirdsql.isc_info_sql_stmt_insert ) print 'psIns.n_input_params: %d' % psIns.n_input_params print 'psIns.n_output_params: %d' % psIns.n_output_params print 'psIns.plan: %s' % psIns.plan print N = 10000 iStart = 0 # The client programmer uses a PreparedStatement explicitly: ``` -------------------------------- ### Python: Create Multi-file Database Backup Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Shows how to split a database backup into multiple files using the destFilenames and destFileSizes parameters. This is useful for managing file size limits or distributing backups across different storage media. ```python from firebirdsql import services con = services.connect(user='sysdba', password='masterkey') con.backup('C:/temp/test.db', ('C:/temp/back01.fbk', 'C:/temp/back02.fbk', 'C:/temp/back03.fbk'), destFileSizes=(4096, 16384) ) ``` -------------------------------- ### pyfirebirdsql Exception Hierarchy Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/Python-DB-API-2.0.rst Illustrates the inheritance structure of database-related exceptions in pyfirebirdsql, starting from StandardError down to specific error types like OperationalError and ProgrammingError. ```python StandardError |__Warning |__Error |__InterfaceError |__DatabaseError |__DataError |__OperationalError |__IntegrityError |__InternalError |__ProgrammingError |__NotSupportedError ``` -------------------------------- ### pyfirebirdsql Module Synopsis Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/index.rst Provides a synopsis for the firebirdsql module, indicating its role as a Python Database API 2.0 compliant driver for Firebird. ```Python .. module:: firebirdsql :synopsis: Python Database API 2.0 Compliant driver for Firebird ``` -------------------------------- ### Create and Drop Firebird Database using pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates how to programmatically create a new Firebird database file and then delete it using the `firebirdsql` library. It utilizes `firebirdsql.create_database` for creation and `Connection.drop_database` for deletion, handling potential operational errors. ```Python import firebirdsql con = firebirdsql.create_database( "create database '/temp/db.db' user 'sysdba' password 'pass'" ) con.drop_database() ``` -------------------------------- ### Connect and Query Firebird SQL (Python) Source: https://github.com/nakagami/pyfirebirdsql/blob/master/README.rst Demonstrates how to establish a connection to a Firebird database using firebirdsql, execute a SQL query, fetch all results, and close the connection. This follows the Python Database API Specification v2.0. ```Python import firebirdsql conn = firebirdsql.connect( host='localhost', database='/foo/bar.fdb', port=3050, user='alice', password='secret' ) cur = conn.cursor() cur.execute("select * from baz") for c in cur.fetchall(): print(c) conn.close() ``` -------------------------------- ### Python DB API 2.0 Module Interface: paramstyle Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/Python-DB-API-2.0.rst A string constant defining the expected parameter marker formatting. Possible values include 'qmark', 'numeric', 'named', 'format', and 'pyformat'. ```Python paramstyle = 'pyformat' # Example: String constant stating the type of parameter marker formatting. ``` -------------------------------- ### Compare Firebird Version Retrieval Methods Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Compares the output of the standard firebirdsql.Connection.server_version property with the Services API's Connection.getServerVersion() method, highlighting the difference in version reporting for compatibility. ```Python import firebirdsql con = firebirdsql.connect(dsn='localhost:C:/temp/test.db', user='sysdba', password='masterkey') print 'Interbase-compatible version string:', con.server_version import firebirdsql.services svcCon = firebirdsql.services.connect(host='localhost', user='sysdba', password='masterkey') print 'Actual Firebird version string: ', svcCon.getServerVersion() ``` -------------------------------- ### Get Firebird Lock File Directory using pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Returns the directory where the database engine's lock file resides, used for interprocess communication, via Connection.getLockFileDir(). ```python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getLockFileDir() ``` -------------------------------- ### Update PrepareStatement.__init__ parameter name Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/changelog.rst Changes the parameter name 'explain_plan' in the PrepareStatement class's __init__ method. Also addresses issues related to character set decoding and statement allocation. ```Python # Version 0.7.0 # - change parameter name 'explain_plan' in class PrepareStatement.__init__(). # - issue #32 don't decode character set OCTETS # - issue #33 op_allocate_statement do not require a transaction handle. # - add event notification ``` -------------------------------- ### Establish pyfirebirdsql Services Connection Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates how to establish a connection to a Firebird database server's Services API using different parameter combinations. The connection is represented by a firebirdsql.services.Connection object. ```Python from firebirdsql import services con = services.connect(password='masterkey') con = services.connect(user='sysdba', password='masterkey') con = services.connect(host='localhost', user='sysdba', password='masterkey') ``` -------------------------------- ### Get Firebird Connection Count using pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Returns the number of active database connections to the server using Connection.getConnectionCount(). This method counts database connections, not service manager connections. ```python import firebirdsql, firebirdsql.services svcCon = firebirdsql.services.connect(host='localhost', user='sysdba', password='masterkey') print 'A:', svcCon.getConnectionCount() con1 = firebirdsql.connect(dsn='localhost:C:/temp/test.db', user='sysdba', password='masterkey') print 'B:', svcCon.getConnectionCount() con2 = firebirdsql.connect(dsn='localhost:C:/temp/test.db', user='sysdba', password='masterkey') print 'C:', svcCon.getConnectionCount() con1.close() print 'D:', svcCon.getConnectionCount() con2.close() print 'E:', svcCon.getConnectionCount() ``` -------------------------------- ### Python: Insert data using prepared statement Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates inserting multiple rows into a table using a pre-compiled SQL INSERT statement with parameter markers. This method is efficient as the statement is prepared only once. ```python insertStatement = "insert into the_table (a,b,c) values (?,?,?)" cur.execute(insertStatement, ('aardvark', 1, 0.1)) ... cur.execute(insertStatement, ('zymurgy', 2147483647, 99999.999)) ``` -------------------------------- ### Asyncio Connection Pool for Firebird SQL (Python) Source: https://github.com/nakagami/pyfirebirdsql/blob/master/README.rst Illustrates how to create and use an asynchronous connection pool with firebirdsql for managing database connections efficiently in an asyncio application. It demonstrates acquiring a connection, executing a query, and releasing the connection back to the pool. ```Python import asyncio import firebirdsql async def pool_example(loop): pool = await firebirdsql.aio.create_pool( host='localhost', database='/foo/bar.fdb', port=3050, user='alice', password='secret' loop=loop, ) async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute("select * from baz") print(await cur.fetchall()) pool.close() await pool.wait_closed() loop = asyncio.get_event_loop() loop.run_until_complete(pool_example(loop)) loop.close() ``` -------------------------------- ### Get Firebird Message File Directory using pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Determines the directory containing the database engine's message file (e.g., firebird.msg) used for internationalized error messages, using Connection.getMessageFileDir(). ```python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getMessageFileDir() ``` -------------------------------- ### Add license file and update documents Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/changelog.rst Includes a license file for the project and updates the documentation to reflect recent changes and improvements. ```Python # Version 1.0.0 # - refactoring # - Add license file. # - Documents update. ``` -------------------------------- ### Get Firebird Service Manager Version Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Shows how to retrieve the version number of the Firebird Service Manager using the getServiceManagerVersion() method. This helps client programs adapt to version changes in the service manager. ```Python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getServiceManagerVersion() ``` -------------------------------- ### Python: Prepare and Inspect SELECT Statement Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Prepares a SELECT statement and inspects its properties like SQL string, statement type, parameter counts, and execution plan. ```python psSel = cur.prep("select * from t where a = ?") print 'psSel.sql: "%s"' % psSel.sql print 'psSel.statement_type == firebirdsql.isc_info_sql_stmt_select:', ( psSel.statement_type == firebirdsql.isc_info_sql_stmt_select ) print 'psSel.n_input_params: %d' % psSel.n_input_params print 'psSel.n_output_params: %d' % psSel.n_output_params print 'psSel.plan: %s' % psSel.plan ``` -------------------------------- ### Connect with Role - pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/python-db-api-compliance.rst Demonstrates connecting to a Firebird database using a specific SQL role. This is an extension beyond the standard DB API connection parameters. ```python firebirdsql.connect(dsn='host:/path/database.db', user='limited_user', password='pass', role='MORE_POWERFUL_ROLE') ``` -------------------------------- ### Connect and Manage Databases with pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates how to connect to a Firebird database using pyfirebirdsql, manage attached databases via a service connection, and observe changes in the attached database list as connections are opened and closed. ```python import firebirdsql, firebirdsql.services svcCon = firebirdsql.services.connect(host='localhost', user='sysdba', password='masterkey') print 'A:', svcCon.getAttachedDatabaseNames() con1 = firebirdsql.connect(dsn='localhost:C:/temp/test.db', user='sysdba', password='masterkey') print 'B:', svcCon.getAttachedDatabaseNames() con2 = firebirdsql.connect(dsn='localhost:C:/temp/test2.db', user='sysdba', password='masterkey') print 'C:', svcCon.getAttachedDatabaseNames() con3 = firebirdsql.connect(dsn='localhost:C:/temp/test2.db', user='sysdba', password='masterkey') print 'D:', svcCon.getAttachedDatabaseNames() con1.close() print 'E:', svcCon.getAttachedDatabaseNames() con2.close() print 'F:', svcCon.getAttachedDatabaseNames() con3.close() print 'G:', svcCon.getAttachedDatabaseNames() ``` -------------------------------- ### Python DB API 2.0 Module Interface: connect() Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/Python-DB-API-2.0.rst Defines the constructor for creating a connection to the database. It accepts database-dependent parameters and returns a Connection Object. ```Python def connect(parameters...): # Constructor for creating a connection to the database. # Returns a Connection Object. pass ``` -------------------------------- ### Python: Execute many with prepared statement Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Shows how to execute a pre-prepared SQL statement multiple times with different sets of values using Cursor.executemany. This is an optimized way to insert or update many rows. ```python insertStatement = cur.prep("insert into the_table (a,b,c) values (?,?,?)") inputRows = [ ('aardvark', 1, 0.1), ... ('zymurgy', 2147483647, 99999.999) ] cur.executemany(insertStatement, inputRows) ``` -------------------------------- ### Python: Attempt to Execute Prepared Statement on Different Cursor Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates that PreparedStatements are not transferable between different cursors, resulting in a ProgrammingError. ```python print print 'Note that PreparedStatements are not transferrable from one cursor to another:' cur2 = con.cursor() cur2.execute(psSel) ``` -------------------------------- ### Execute SQL Operation with Parameters Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/Python-DB-API-2.0.rst Prepares and executes a database operation (query or command) with optional parameters. Parameters can be bound to variables in the operation using a database-specific notation. The method can retain a reference to the operation for optimization. ```Python cursor.execute(operation, parameters) ``` -------------------------------- ### Restore Database (Single File) - pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Demonstrates the simplest form of restoring a database from a backup file into a single file using pyfirebirdsql. It shows how to connect to the database service and call the restore method with source and destination file paths. ```python from firebirdsql import services con = services.connect(user='sysdba', password='masterkey') restoreLog = con.restore('C:/temp/test_backup.fbk', 'C:/temp/test_restored.db') print restoreLog ``` -------------------------------- ### Retrieve Firebird Server Log with pyfirebirdsql Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/beyond-python-db-api.rst Shows how to connect to the Firebird server using the services module and retrieve the contents of the server's log file using the getLog() method. ```python from firebirdsql import services con = services.connect(host='localhost', user='sysdba', password='masterkey') print con.getLog() ``` -------------------------------- ### Python DB API 2.0 Module Interface: apilevel Source: https://github.com/nakagami/pyfirebirdsql/blob/master/sphinx/Python-DB-API-2.0.rst A string constant indicating the supported DB API level. Allowed values are '1.0' and '2.0'. Defaults to '1.0' if not provided. ```Python apilevel = "2.0" # Example: String constant stating the supported DB API level. ```