0

I have a custom function on oracle database called create_identifier. It acccept a string and a column and concatenate the abbreviated form of the string to the column.

I am trying to get the python sqlalchemy orm equivalent of

select(select create_identifer("Name", u.name) from dual), u.id from User u

I am not sure how to get the oracle default table in python sqlalchemy orm.

I tried

select(select(func.create_identifier("Name", User.name) from dual), User.id) from User 

I also tried the SQLCompiler.default_from, it is not working I guess it is more compatible with raw sql than orm.

1
  • For future reference: Oracle Database 23ai queries don't need a FROM DUAL clause. Commented May 22, 2024 at 21:07

1 Answer 1

1

From the Using Textual SQL documentation:

Our last example really became a handful to type. Going from what one understands to be a textual SQL expression into a Python construct which groups components together in a programmatic style can be hard. That’s why SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged. Below, we create a text() object and execute it:

>>> from sqlalchemy.sql import text
>>> s = text(
...     "SELECT users.fullname || ', ' || addresses.email_address AS title "
...     "FROM users, addresses "
...     "WHERE users.id = addresses.user_id "
...     "AND users.name BETWEEN :x AND :y "
...     "AND (addresses.email_address LIKE :e1 "
...     "OR addresses.email_address LIKE :e2)"
... )
>>> conn.execute(s, {"x": "m", "y": "z", "e1": "%@aol.com", "e2": "%@msn.com"}).fetchall()
SELECT users.fullname || ', ' || addresses.email_address AS title
FROM users, addresses
WHERE users.id = addresses.user_id AND users.name BETWEEN ? AND ? AND
(addresses.email_address LIKE ? OR addresses.email_address LIKE ?)
[...] ('m', 'z', '%@aol.com', '%@msn.com')
[(u'Wendy Williams, [email protected]',)]

Your code would be:

from sqlalchemy.sql import text
sql = text("select create_identifer('Name', u.name), u.id from User u")
results = conn.execute(sql).fetchall()

Note: In Oracle, string literals use single ' quotes whereas double " quotes are for (quoted) identifiers. So 'Name' would be a string literal but "Name" would refer to a column called Name (with that exact capitalisation).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.