Giter VIP home page Giter VIP logo

pyfirebirdsql's Introduction

PyfirebirdSQL

https://img.shields.io/pypi/v/firebirdsql.png

https://img.shields.io/pypi/l/firebirdsql.png

firebirdsql package is a set of Firebird RDBMS (https://firebirdsql.org/) bindings for Python (Written in pure Python : no C compiler needed or fbclient library)

see https://pyfirebirdsql.readthedocs.io/en/latest/

It works on Python 2.7 and 3.8+.

But if you want to use the timezone feature of Firebird 4.0 ...

Example

Python Database API Specification v2.0

https://peps.python.org/pep-0249/

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()

asyncio

In Python3, you can use asyncio to write the following.

This API is experimental. If there are any mistakes, please correct them in the pull request and send.

Use connect

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())

Use pool

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()

pyfirebirdsql's People

Contributors

jtasker avatar kai3341 avatar keeperds avatar kianmeng avatar mariuz avatar movermeyer avatar nakagami avatar pmakowski avatar tiran avatar tk0miya avatar tonal avatar trapwalker avatar xabbl4 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyfirebirdsql's Issues

pip issue ImportError: No module named utils

pip install --upgrade firebirdsql
Downloading/unpacking firebirdsql from https://pypi.python.org/packages/source/f/firebirdsql/firebirdsql-0.8.3.tar.gz#md5=f12e9030728d2819ea95ccf2fa31e077
Downloading firebirdsql-0.8.3.tar.gz
Running setup.py egg_info for package firebirdsql
Traceback (most recent call last):
File "", line 16, in
File "/tmp/pip_build_mariuz/firebirdsql/setup.py", line 15, in
import firebirdsql
File "firebirdsql/init.py", line 53, in
from firebirdsql.fbcore import ( version, apilevel, threadsafety,
File "firebirdsql/fbcore.py", line 16, in
from firebirdsql.utils import *
ImportError: No module named utils
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 16, in

File "/tmp/pip_build_mariuz/firebirdsql/setup.py", line 15, in

import firebirdsql

File "firebirdsql/init.py", line 53, in

from firebirdsql.fbcore import ( __version__, apilevel, threadsafety,

File "firebirdsql/fbcore.py", line 16, in

from firebirdsql.utils import *

ImportError: No module named utils

PEP 479

In Python3.5

/home/nakagami/pyfirebirdsql/firebirdsql/fbcore.py:350: PendingDeprecationWarning: generator '_fetch_generator' raised StopIteration
return tuple(next(self._fetch_records))
/home/nakagami/pyfirebirdsql/firebirdsql/fbcore.py:379: PendingDeprecationWarning: generator '_fetch_generator' raised StopIteration

AttributeError: 'Connection' object has no attribute 'port'

When there is no localhost specified then i get this error

Traceback (most recent call last):
File "example4.py", line 2, in
con = firebirdsql.connect(dsn='/tmp/test.db', user='sysdba', password='masterkey')
File "/usr/local/lib/python2.7/dist-packages/firebirdsql/init.py", line 61, in connect
database=database, charset=charset, port=port)
File "/usr/local/lib/python2.7/dist-packages/firebirdsql/fbcore.py", line 683, in init
self.sock.connect((self.hostname, self.port))
AttributeError: 'Connection' object has no attribute 'port

import firebirdsql
con = firebirdsql.connect(dsn='/tmp/test.db', user='sysdba', password='masterkey')
cur = con.cursor()
newLanguages = [
('Lisp', 1958),
('Dylan', 1995),
]
cur.executemany("insert into languages (name, year_released) values (?, ?)",newLanguages)
# The changes will not be saved unless the transaction is committed explicitly:
con.commit()

Authenticating with unknown user or wrong password yields unclear error message

Authenticating with an unknown user yields an unclear error message TypeError: a bytes-like object is required, not 'NoneType' instead of the Firebird error "Your user name and password are not defined. Ask your database administrator to set up a Firebird login."

For example

import firebirdsql

con = firebirdsql.connect(
    host='localhost', database='employee',
    user='doesnotexist', password='password'
  )

Yields

Traceback (most recent call last):
  File "simpleconnect.py", line 5, in <module>
    user='doesnotexist', password='password'
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\__init__.py", line 96, in connect
    return Connection(**kwargs)
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\fbcore.py", line 615, in __init__
    self._op_accept()
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\wireprotocol.py", line 534, in _op_accept
    p.pack_string(bytes_to_hex(auth_data))
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\utils.py", line 57, in bytes_to_hex
    s = binascii.b2a_hex(b)
TypeError: a bytes-like object is required, not 'NoneType'

In a similar vein, authenticating with the wrong password yields an error "firebirdsql.InternalError: InternalError" instead of the Firebird error "Your user name and password are not defined. Ask your database administrator to set up a Firebird login.":

import firebirdsql

con = firebirdsql.connect(
    host='localhost', database='employee',
    user='sysdba', password='wrongpassword'
  )

Yields:

Traceback (most recent call last):
  File "simpleconnect.py", line 5, in <module>
    user='sysdba', password='wrongpassword'
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\__init__.py", line 96, in connect
    return Connection(**kwargs)
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\fbcore.py", line 615, in __init__
    self._op_accept()
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\wireprotocol.py", line 539, in _op_accept
    (h, oid, buf) = self._op_response()
  File "C:\DevSoft\python\python-3.6.1\lib\site-packages\firebirdsql\wireprotocol.py", line 990, in _op_response
    raise InternalError
firebirdsql.InternalError: InternalError

Python 3.6.4
pyfirebirdsql: 1.1.0

ValueError: too many values to unpack

Traceback (most recent call last):
  <some lines elided for privacy>
  File "C:\Python27\lib\site-packages\firebirdsql\fbcore.py", line 367, in fetchall
    return [tuple(r) for r in self._fetch_records]
  File "C:\Python27\lib\site-packages\firebirdsql\fbcore.py", line 192, in _fetch_generator
    stmt.handle, stmt.xsqlda)
ValueError: too many values to unpack

This is a result of this line in fbcore.py:

(rows, more_data) = connection._op_fetch_response(stmt.handle, stmt.xsqlda)

Which assumes that there are only 2 values returned. However, _op_fetch_response() can return 3 values since it can return the result of _parse_op_response() (line 780 of wireprotocol.py).

Support for kinterbasdb's fetch*map() API?

kinterbasdb has an extended set of fetch methods that return a dict like RowMapping. We use the feature a lot at work. How do you feel about adding the fetch*map() functions? I could provide a patch.

Why did you choosed UNICODE_FSS to be the default encoding

Hi M. Nakagami,

I want to congtatulate you for this amazing piece of code. I plan to write a new Ruby driver for FirebirdSQL and face the alternative to write a native driver of a driver that relies on the Firebird client library. FFI seems to be an excellent technology to be able to write a driver that could be used by different flavors of Rubies...

As I read your code I would like to ask you why you choosed UNICODE_FSS to be the default character set encoding. I seems that UNICODE_FSS is the worst choice in terms of character encoding with FirebirdSQL. Why did'nt you choosed "standard" UTF8 instead ?

With all my encouragements.

alternative to crypt on windows

Carlos installed this driver with all versions of Python from 3.x and always shows this error

File “H:\python33\lib\site-packages\firebirdsql\wireprotocol.py”, line 523, in _op_attach
s = self.str_to_bytes(crypt.crypt(self.password, ’9z’)[2:])
AttributeError: ‘NoneType’ object has no attribute ‘crypt’

Win XP SP3
Python 3.x
Firebird 2.5.x

Custom TPB not supported?

The documentation suggests there is a possibility to have customized TPB, however, I guess this is not the case since REL_0_9_1 ; see this commit . I tried to quickly reverse-engineer the current version (python is not my language #1) and I do not see how to have a custom TPB without some hacking around. Am I missing something? Is there an updated documentation for the library?

issue can't connect to file containing dash'-'

I try connect to file containing dash e.g. /data/g-database.fdb and got error

File "C:\Dev\Projects\Galvo-apps\Galvo-msaccess-firebird-python\venv\lib\site-packages\firebirdsql_init_.py", line 96, in connect
conn = Connection(**kwargs)
File "C:\Dev\Projects\Galvo-apps\Galvo-msaccess-firebird-python\venv\lib\site-packages\firebirdsql\fbcore.py", line 624, in init
raise e
File "C:\Dev\Projects\Galvo-apps\Galvo-msaccess-firebird-python\venv\lib\site-packages\firebirdsql\fbcore.py", line 620, in init
self._parse_connect_response()
File "C:\Dev\Projects\Galvo-apps\Galvo-msaccess-firebird-python\venv\lib\site-packages\firebirdsql\wireprotocol.py", line 545, in _parse_connect_response
raise OperationalError('Connection is rejected')
firebirdsql.OperationalError: Connection is rejected

Problem if is there a db error during fetch

create or alter procedure TEST_ERROR_DURING_FETCH
returns (
MSG varchar(200))
AS
declare variable dbpath lib100;
declare variable dbpass lib100;
begin
msg = 'oupsss';
suspend;
exception raiseexception('bug');
end

for exemple if you do a select on this proc you get

wireprotocol.py", line 820, in _op_fetch_response
raise InternalError

i have have this problem on node-firebird also, and the solution is to heck the op code after each line :

        b = self.recv_channel(12)
        # op = bytes_to_bint(b[:4]) // this op is set to op_response when there is an errror
        status = bytes_to_bint(b[4:8])
        count = bytes_to_bint(b[8:])

Commit 02dfb473fb6bf70bca6f08f1e069c73512857f70 broke Windows compatibility

The change made in commit 02dfb473fb6bf70bca6f08f1e069c73512857f70 broke Windows compatibility.

Before, if crypt was not found, get_crypt returned None. That 'if' statement was removed.

Steps to reproduce:

Use the example code given on the Github page:

import firebirdsql

FIREBIRD_HOST = "localhost"
FIREBIRD_DB = "D:\\Repos\\GWS\\FirebirdLoader\\Databases\\2015-08-06\\LOCALCONFIG.fdb"
FIREBIRD_USER = "SYSDBA"
FIREBIRD_PASS = "masterkey"

conn = firebirdsql.connect(host=FIREBIRD_HOST, database=FIREBIRD_DB, user=FIREBIRD_USER, password=FIREBIRD_PASS)
cur = conn.cursor()

cur.execute("select * from GHUSRCFG")
for c in cur.fetchall():
    print(c)
    conn.close()

Gives the following error:

Traceback (most recent call last):
  File "test3.py", line 8, in <module>
    conn = firebirdsql.connect(host=FIREBIRD_HOST, database=FIREBIRD_DB, user=FIREBIRD_USER,
  File "C:\Python27\lib\site-packages\firebirdsql\__init__.py", line 62, in connect
    return Connection(**kwargs)
  File "C:\Python27\lib\site-packages\firebirdsql\fbcore.py", line 589, in __init__
    self._op_attach()
  File "C:\Python27\lib\site-packages\firebirdsql\wireprotocol.py", line 532, in _op_attach
    enc_pass = get_crypt(self.password)
  File "C:\Python27\lib\site-packages\firebirdsql\wireprotocol.py", line 56, in get_crypt
    return crypt.crypt(plain, '9z')[2:]
AttributeError: 'NoneType' object has no attribute 'crypt'

Tested using:
pyfirebirdsql 0.9.9
Firebird SQL 2.5.4.26856, 64 bit
Windows 7 Pro

fbcore.Connection.close() bug or not?

fbcore.Connection.close()

    def close(self):
        DEBUG_OUTPUT("Connection::close()")
        if self.sock is None:
            return
        if self.db_handle:           # <= this condition
            if self.is_services:
                self._op_service_detach()
            else:
                self._op_detach()
            (h, oid, buf) = self._op_response()
        self.sock.close()
        self.sock = None
        self.db_handle = None

maybe there should be:

        if not self.db_handle is None:

In later case exception is raising when open transactions are left. But when self.db_handle is zero, self._op_detach() is skipped quiet. I don't know is that a bug or not?

Problem with double precision fields

double precision fields are not converted, only change is in value method of XSQLVAR class:

def value( self, raw_value ):
if self.sqltype in ( SQL_TYPE_TEXT, SQL_TYPE_VARYING ):
return self.bytes_to_str( raw_value )
elif self.sqltype in ( SQL_TYPE_SHORT, SQL_TYPE_LONG, SQL_TYPE_INT64 ):
n = bytes_to_bint( raw_value )
if self.sqlscale:
return decimal.Decimal( str( n ) + 'e' + str( self.sqlscale ) )
else:
return n
elif self.sqltype == SQL_TYPE_DATE:
yyyy, mm, dd = self._parse_date( raw_value )
return datetime.date( yyyy, mm, dd )
elif self.sqltype == SQL_TYPE_TIME:
h, m, s, ms = self._parse_time( raw_value )
return datetime.time( h, m, s, ms )
elif self.sqltype == SQL_TYPE_TIMESTAMP:
yyyy, mm, dd = self._parse_date( raw_value[:4] )
h, m, s, ms = self._parse_time( raw_value[4:] )
return datetime.datetime( yyyy, mm, dd, h, m, s, ms )
elif self.sqltype == SQL_TYPE_DOUBLE:
return unpack( "!d", raw_value )[0]
else:
return raw_value

count error in calc_blr(xsqlda)

I think there is "probably" an error in "calc_blr" function in "fbcore.py".
if you read the PARSE_messages function in parser.cpp from firebird
you should replace
ln = len(xsqlda) *2
with
ln = len(xsqlda)

I apology if I'am wrong.

Documentation incorrect about dialect argument for "connection"

The documentation claims you can pass dialect=? to control the dialect level of the connection.
https://pyfirebirdsql.readthedocs.org/en/latest/python-db-api-compliance.html?highlight=dialect#firebirdsql.connect

However, if you try to actually do this, the Connection object raises an exception:

TypeError: __init__() got an unexpected keyword arguments 'dialect'

From a quick grep of the git repo, it appears the dialect is hard-coded to 3

firebirdsql/wireprotocol.py:702: p.pack_int(3) # dialect = 3
firebirdsql/wireprotocol.py:770: p.pack_int(3) # dialect = 3

Connection error

whenever I try to connect to the DB with any user other than sysdba this error appears "Invalid bytes length:0"
can anyone help please?

InternalError after commit

When I try to retrieve data (fetchone or fetchall) after commit from resultset(cursor) I get InternalError.
Works fine with commit(True).

How to set timeout in conduit.wait()?

When I point timeout option
result = conduit.wait(timeout=5)
i get an error:
TypeError: wait() got an unexpected keyword argument 'timeout'
What to do?
Thanks!

OperationalError when execute SELECT statement with parameters

When I try to .execute() a SELECT query using parameters, I get

OperationalError: Dynamic SQL Error
SQL error code = -504
Invalid cursor reference

example code:

import firebirdsql
assert firebirdsql.__version__ == "0.7.2"

# Firebird 1.5.6.5026 32bit, Windows 7 Professional SP1 64 bit
# Python 2.7.3, 32 bit

conn_conf = {
    'database': './issue.fdb',
    'user': 'sysdba',
    'password': 'masterkey',
    'host': 'localhost',
    'port': 3050,
}

con = firebirdsql.create_database(**conn_conf)
con = firebirdsql.connect(**conn_conf)

# good code 1
cur = con.cursor()
res = cur.execute("SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$INDEX_NAME LIKE 'RDB$INDEX_%'")
index_name = cur.fetchone()
print index_name

# good code 2
cur = con.cursor()
res = cur.execute("SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$INDEX_NAME LIKE 'RDB$INDEX_%'")
for index_name in cur.fetchall():
    print index_name

# bad code 1, fetchone raises OperationalError
cur = con.cursor()
res = cur.execute("SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$INDEX_NAME LIKE ?",('RDB$INDEX_%'))
con.commit()
index_name = cur.fetchone()
print index_name

# bad code 2, fetchall raises OperationalError
cur = con.cursor()
res = cur.execute("SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$INDEX_NAME LIKE ?",('RDB$INDEX_%'))
con.commit()
for index_name in cur.fetchall():
    print index_name

# Result to expect:
# fetchone / fetchall after execute a SELECT stmt returns same result when
#   stmt is execute with parameters as when stmt is execute without parameters

Firebird event support

fetchone() should return None if no row

PEP 249 says that fetchone() should return None when no more data is available. The current code does not do that. Also, the second statement will never execute:

def fetchone(self):
    return self.rows[self.cur_row]
    self.cur_row += 1

Here is my suggested update:

def fetchone(self):
    if self.cur_row < len(self.rows):
        row = self.rows[self.cur_row]
        self.cur_row += 1
        return row
    else:
        return None

Wrong logic for handling large BLOBs?

Shouldn't line 204 of fbcore.py be

while n != 2:

instead of

while n == 1:

I'm finding that the protocol will return a 0 instead of a 1 every 507873 bytes (strange number).
As a result of this logic, my BLOB is being truncated.

I haven't been able to prove that 0 is an OK response as I can't find the spec and reading the C++ code isn't my strong suit. But changing the Python to 'n != 2' seems to work.

Your input would help a lot.

P.S: I noticed that the same logic is also found in your Go version
I've filed a similar issue there.

How to diagnose connection problems?

Hi,

I'm trying to connect to a remote Firebird Server, version 3.0.10, I passed all parameters, but I'm getting the Unauthorized message, even knowing that all info are correct.

I can connect to this server using the firebird-driver and command line utility using the same credentials, but not using firebirdsql:

import firebirdsql
con1 = firebirdsql.connect(host="x.x.x.x", port=xyz, database="ALIAS", user="USER", password="PASS", charset="UTF-8")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "APP_PATH/api/venv/lib64/python3.9/site-packages/firebirdsql/__init__.py", line 95, in connect
    conn = Connection(**kwargs)
  File "APP_PATH/api/venv/lib64/python3.9/site-packages/firebirdsql/fbcore.py", line 649, in __init__
    raise e
  File "APP_PATH/api/venv/lib64/python3.9/site-packages/firebirdsql/fbcore.py", line 645, in __init__
    self._parse_connect_response()
  File "APP_PATH/api/venv/lib64/python3.9/site-packages/firebirdsql/wireprotocol.py", line 670, in _parse_connect_response
    (h, oid, buf) = self._op_response()
  File "APP_PATH/api/venv/lib64/python3.9/site-packages/firebirdsql/wireprotocol.py", line 1143, in _op_response
    raise OperationalError('Unauthorized')
firebirdsql.OperationalError: Unauthorized
  • Firebird Server version 3.0.10 on Windows
  • pyfirebirdsql version 1.2.2
  • Python 3.9

There is any parameter to better diagnose this problem?

Add support for case sensitive user names

Firebird 3 introduced case sensitive user names, this is currently not supported by pyfirebirdsql. For case sensitive user names, Firebird applies the same rules as for case sensitive object names: they are quoted in double quotes.

Example

create user "CaseSensitive" password 'password' using plugin Srp;
create user caseinsensitive password 'password' using plugin Srp;

This creates two user, the case sensitive username CaseSensitive and the case insensitive caseinsensitive (or more correct: CASEINSENSITIVE).

Current attempts to use case sensitive usernames (eg as user='"CaseSensitive"' in a connect) yield error "TypeError: a bytes-like object is required, not 'NoneType'" (see also #75). This is because pyfirebirdsql upper cases the user names in various places.

Instead, the following rules should be applied:

  • CNCT_login: pass user name as is (preserve quotes if present)
  • isc_dpb_user_name: pass user name as is (preserve quotes if present)
  • isc_spb_user_name: pass user name as is (preserve quotes if present)
  • Usage in SRP client proof: unquoted usernames: uppercase, quoted usernames: strip and unescape double quotes and preserve current case (that is caseinsensitive -> CASEINSENSITIVE, "CaseSensitive" -> CaseSensitive and "Contains""Quote" -> Contains"Quote

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 5: invalid continuation byte

Hello.

the following code

import firebirdsql

#con = fdb.connect(dsn='/home/operations/dev/HLT.FDB', user='sysdba', password='masterkey')

conn = firebirdsql.connect(
    host='localhost',
    database='HLT',
    port=3050,
    user='SYSDBA',
    password='masterkey'
)

#SQLX = "SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME='FECHAMENTO_CAIXA';"
SQLX = "SELECT * FROM FECHAMENTO_CAIXA;"
cur = conn.cursor()
cur.execute(SQLX)
response_tables = cur.fetchall()

print(response_tables)

conn.close()

gives the following error

Traceback (most recent call last):
  File "table.py", line 15, in <module>
    response_tables = cur.fetchall()
  File "/home/operations/.local/lib/python3.6/site-packages/firebirdsql/fbcore.py", line 392, in fetchall
    return [tuple(r) for r in self._fetch_records]
  File "/home/operations/.local/lib/python3.6/site-packages/firebirdsql/fbcore.py", line 392, in <listcomp>
    return [tuple(r) for r in self._fetch_records]
  File "/home/operations/.local/lib/python3.6/site-packages/firebirdsql/fbcore.py", line 228, in _fetch_generator
    (rows, more_data) = connection._op_fetch_response(stmt.handle, stmt.xsqlda)
  File "/home/operations/.local/lib/python3.6/site-packages/firebirdsql/wireprotocol.py", line 1002, in _op_fetch_response
    r[i] = x.value(raw_value)
  File "/home/operations/.local/lib/python3.6/site-packages/firebirdsql/xsqlvar.py", line 159, in value
    return self.bytes_to_str(raw_value)
  File "/home/operations/.local/lib/python3.6/site-packages/firebirdsql/wireprotocol.py", line 251, in bytes_to_str
    return b.decode(charset_map.get(self.charset, self.charset))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 5: invalid continuation byte

however, if SQLX is defined according to the commented line, instead, then it works.
what am i doing wrong, please?
my best guess is that i need to set chartset in the connect method, however i am not sure what do do.

any help is much appreciated.
best regards.

_op_response:op_code = 97 after possible update of firebird server

Hi,

we have firebirdsql since a while in use - customer did updated his "Orgamax" - which does use the firebird server. Since this update we can't connect any more. The test script does deliver an op_code = 97 on connect. I assume that the Orgamax Update also did an firebase Server Update - and maybe the firebasesql driver is not able to connect to the new server version.

I've tried to connect use the "firebird-driver" with the same dsn - does work as expected...

Here is the backtrace from my connect attempt

File "/root/test.py", line 2, in
conn = firebirdsql.connect(
File "/usr/local/lib/python3.9/dist-packages/firebirdsql/init.py", line 141, in connect
conn = Connection(**kwargs)
File "/usr/local/lib/python3.9/dist-packages/firebirdsql/fbcore.py", line 973, in init
(h, oid, buf) = self._op_response()
File "/usr/local/lib/python3.9/dist-packages/firebirdsql/fbcore.py", line 646, in _op_response
raise InternalError("_op_response:op_code = %d" % (op_code,))
firebirdsql.InternalError: _op_response:op_code = 97

Truncated Column Names

When querying a FireBird database using isql I can get the column names with no problem:

SQL> SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME='SUSERS';

RDB$FIELD_NAME                  
=============================== 

FID                             
FLOGIN                          
FPASSWORD                       
FFULLNAME                       
FPOSITION                       
FEMAIL                          
FNOTES                          
FROLE                           
FTRIGHTS                        
FORIGHTS                        
FAGENCIES                       
FUOPTS                          
FMOPTS                          
FTODORIGHTS                     
FISDISABLED                     
FDENIEDOPERATIONS               
FRRIGHTS                        
FPHONE                          
FFAX                            
FMAILSIGNS  

BUT when I do the same thing using firebirdsql this is what I get:

>>> query = "SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME='%s';" % ('SUSERS')
>>> cur.execute(query)
>>> _field_names = cur.fetchall()
>>> print _field_names

[['FID       '], ['FLOGIN    '], ['FPASSWORD '], ['FFULLNAME '], ['FPOSITION '], ['FEMAIL    '], ['FNOTES    '], ['FROLE     '], ['FTRIGHTS  '], ['FORIGHTS  '], ['FAGENCIES '], ['FUOPTS    '], ['FMOPTS    '], ['FTODORIGHT'], ['FISDISABLE'],

as you can see the python implementation has a field name ['FDENIEDOPE'], but this field name does not exist in the direct query implementation. There is a field in the direct query called FDENIEDOPERATIONS

How do I keep python from truncating the field names?

FWIW the truncated field_names are truncated at 10 chars, always.

cursor.execute() returns None

Hi there.

I'm using pyfirebirdsql 0.9.3 with Python 3.4.1 and all queries are returning None.

When testing with the "fdb" module everything worked.

stuck on socket receive when inserting blob data

I'm currently working on a Firebird 2.5 database with Python 3.6.4 and have trouble inserting image data into a binary blob field.

You should be able to observe the behaviour I'm getting by changing the test_blob() function in test_basic.py from
cur.execute("update blob0_test set b = ?", (b'x' * (MAX_CHAR_LENGTH+1), ))
to
cur.execute("update blob0_test set b = ?", (b'x' * (MAX_CHAR_LENGTH+2), ))

Incorrect handling empty row for RowMapping

Problem with fetchonemap (and probably: fetchallmap, fetchmanymap)
When fetch (fetchone and probably: fetchall, fetchmany) return None, RowMapping raise Exception

Exception:

Traceback (most recent call last):
  File "firebirdsql_issue_30.py", line 28, in <module>
    for key, val in cur.fetchonemap().items():
  File "build\bdist.win32\egg\firebirdsql\fbcore.py", line 598, in fetchonemap
  File "build\bdist.win32\egg\firebirdsql\fbcore.py", line 994, in __init__
TypeError: 'NoneType' object is unsubscriptable

Example code:

import firebirdsql
assert firebirdsql.__version__ == "0.6.5"

# Firebird 2.5 64bit, Windows 7 Home Premium SP1 64 bit 
# Python 2.6, 32 bit

conn_conf = {
    'database': './issue_30.fdb',
    'user': 'sysdba',
    'password': 'masterke',
    'host': 'localhost',
    'port': 3050,
}

con = firebirdsql.create_database(**conn_conf)
con = firebirdsql.connect(**conn_conf)

# ok
cur = con.cursor()
res = cur.execute("SELECT * FROM RDB$ROLES")
for key, val in cur.fetchonemap().items():
    print key, val

# error
cur = con.cursor()
res = cur.execute("SELECT * FROM RDB$PROCEDURES")
con.commit(True)
for key, val in cur.fetchonemap().items():
    print key, val

AttributeError when accessing cursor.description

When I try to access .description attribute of cursor before .execute() has run, I get
AttributeError: Cursor instance has no attribute '_xsqlda'

example code:

import firebirdsql
assert firebirdsql.__version__ == "0.7.2"

# Firebird 1.5.6.5026 32bit, Windows 7 Professional SP1 64 bit
# Python 2.7.3, 32 bit

conn_conf = {
    'database': './issue.fdb',
    'user': 'sysdba',
    'password': 'masterkey',
    'host': 'localhost',
    'port': 3050,
}

con = firebirdsql.create_database(**conn_conf)
con = firebirdsql.connect(**conn_conf)

# good code
cur = con.cursor()
res = cur.execute("SELECT RDB$INDEX_NAME FROM RDB$INDICES")
print cur.description

# bad code, .description raises AttributeError
cur = con.cursor()
print cur.description

# Result to expect:
# .description attribute should be None when .execute has not run yet

UPDATE statements using parameters don't match certain INTEGER values

When I try to .execute() an UPDATE query with an integer field in the WHERE clause, if the value of the field is outside of the range of Firebird's SMALLINT (-32768 to 32767) it will not match. Firebird's INTEGER datatype can hold values from -2,147,483,648 through 2,147,483,647...

example code:

import firebirdsql
assert firebirdsql.__version__ == "0.7.2"

# Firebird 1.5.6.5026 32bit, Windows 7 Professional SP1 64 bit
# Python 2.7.3, 32 bit

conn_conf = {
    'database': './issue.fdb',
    'user': 'sysdba',
    'password': 'masterkey',
    'host': 'localhost',
    'port': 3050,
}

con = firebirdsql.create_database(**conn_conf)
con = firebirdsql.connect(**conn_conf)

# put the following multiline string in createtable.sql and execute on server
createtable = """
              create table t1
              (
                  a       integer,
                  b       varchar(20)
              );

              insert into t1 (a, b) values (32767, 'FOO');
              insert into t1 (a, b) values (32768, 'BAR');
              """

# good code
cur = con.cursor()
res = cur.execute("UPDATE T1 SET B=? WHERE A=?",('FOO2',32767))
con.commit()
cur = cursor()
res = cur.execute("SELECT A, B FROM T1 WHERE B='FOO2'")
con.commit()
for row in cur.fetchall():
    print row

# bad code, update doesn't match any rows
cur = con.cursor()
res = cur.execute("UPDATE T1 SET B=? WHERE A=?",('BAR2',32768))
res = cur.execute("SELECT A, B FROM T1 WHERE B='BAR2'")
con.commit()
for row in cur.fetchall():
    print row

# Result to expect:
# update works for integer fieldtypes with any
#   value from -2,147,483,648 through 2,147,483,647

fbcore error in event_conduit with firebird 3.0.4

system

Windows server 2012.r2x64 - fb 3.0.4
Windows client w10x64 - fb 3.0.4 - py 3.7.1 32bit - fbcore.py 1.1.1 - 2.0

error

Traceback (most recent call last):
  File "H:\_Python\Python\IXS_M2S\fb-test.py", line 150, in doEvent
    conduit = conn.event_conduit(aEvent)
  File "C:\Python37\lib\site-packages\firebirdsql\fbcore.py", line 806, in event_conduit
    return EventConduit(self, event_names, timeout)
  File "C:\Python37\lib\site-packages\firebirdsql\fbcore.py", line 490, in __init__
   self.sock = SocketStream(ip_address, port, timeout)
UnboundLocalError: local variable 'ip_address' referenced before assignment

i put some printing in the code between line 485 and 489 with these results

buffer    : b'1700c8d60000000000000000000000000000ffffc0a8025100000000'
family    : b'1700'
port      : 51495

and here is the code:

476         if family == b'\x02\x00':     # IPv4
477            ip_address = '.'.join([str(byte_to_int(c)) for c in buf[4:8]])
478        elif family == b'\x0a\x00':  # IPv6
479            address = bytes_to_hex(buf[8:24])
480            if not isinstance(address, str):    # Py3
481                address = address.decode('ascii')
482            ip_address = ':'.join(
483                [address[i: i+4] for i in range(0, len(address), 4)]
484            )
485        ## family == b'\x17\x00':     2018.11.30.uc - unknown IP family ???
486        print('buffer    : ' + str(bytes_to_hex(buf )))
487        print('family    : ' + str(bytes_to_hex(family )))
488        print('port      : ' + str(port))
489        ## family == b'\x17\x00':     2018.11.30.uc - unknown IP family ???
490        self.sock = SocketStream(ip_address, port, timeout)

Role required in connection string

Could not connect to remote Firebird 1.5 server as database required role to define the privileges for the user and the connection string did not accept a 'role' parameter.

Cursor.itermap method request

Now we have a method:

def fetchallmap(self):
    desc = self.description
    return [RowMapping(row, desc) for row in self.fetchall()]

but kinterbasdb has a method itermap
Please, include that for compatibility.
Example:

def itermap(self):
    r = self.fetchonemap()
    while r:
        yield r
        r = self.fetchonemap()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.