1 year ago

#388314

test-img

Fred

Python SQLite3 user-defined function does not pass expression as parameter

I wanted to construct a general purpose Python wrapper for feeding parameter values into single statement SQLite queries. A further complexity was to provide a user-defined function to concatenate the results of a subquery assembled from its parameters to denormalize 1:many relationships. It appears impossible to pass values of other columns into the function for, say, building a where clause without dedicating function parameters for each of these. In the code below, the final demonstration fails to handle a simple expression of a literal prefix to a column's value being passed as a single parameter to the trivial function. Test data is taken from The Standard Python Library "11.13. sqlite3 — DB-API 2.0 interface for SQLite databases". Can anyone help me understand what is going on and how to work around this?

import sqlite3

#Create a user-defined function.
def fred(t):
    return t

#Create a small in-memory SQLite database.
con = sqlite3.connect(":memory:")
con.create_function("fred", 1, fred)
cur = con.cursor()

#Demonstrate the user-defined function in a select statement.
cur.execute("select fred(?)", ("foo",))
print(cur.fetchone()[0])  
''' prints
foo
'''
#Create and populate a table in the database.
cur.execute('''CREATE TABLE stocks
             (date_text, trans_text, symbol_text, qty_real, price_real)''')
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
cur.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

#Demonstrate the user-defined function in a select statement.
for row in cur.execute("select fred(?), * from stocks",("foo",)):
  print(row)
''' prints
('foo', '2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('foo', '2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('foo', '2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
('foo', '2006-04-06', 'SELL', 'IBM', 500, 53.0)
'''
#Demonstrate the user-defined function with table column as parameter.
for row in cur.execute("select fred(s.symbol_text), * from stocks AS s"):
  print(row)
''' prints
('RHAT', '2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('IBM', '2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('MSFT', '2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
('IBM', '2006-04-06', 'SELL', 'IBM', 500, 53.0)
'''
#Demonstrate the user-defined function with expression containing table column as parameter.
for row in cur.execute("select fred('x' +s.symbol_text), * from stocks AS s"):
  print(row)
''' prints
(0, '2006-01-05', 'BUY', 'RHAT', 100, 35.14)
(0, '2006-03-28', 'BUY', 'IBM', 1000, 45.0)
(0, '2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
(0, '2006-04-06', 'SELL', 'IBM', 500, 53.0)
'''

python

sqlite

user-defined-functions

0 Answers

Your Answer

Accepted video resources