Home:ALL Converter>SQLAlchemy compiled statement without percent signs conditionally escaped

SQLAlchemy compiled statement without percent signs conditionally escaped

Ask Time:2018-06-12T14:21:31         Author:John

Json Formatter

Is there a way to obtain the compiled SQLAlchemy statement without having the percentage signs conditionally escaped?

The following MySQL example:

from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import select  


Base = declarative_base()


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer(), primary_key=True)
    name = Column(String(80), unique=True)


statement = select([User.name]).where(User.name.like('bob%')).limit(10)
query = str(statement.compile(dialect=mysql.dialect(), compile_kwargs={'literal_binds': True}))
print(query)

generates a compiled statement with the percent sign escaped:

SELECT users.name 
FROM users 
WHERE users.name LIKE 'bob%%' 
  LIMIT 10

rather than:

SELECT users.name 
FROM users 
WHERE users.name LIKE 'bob%' 
  LIMIT 10

I gather this is to ensure that the string can correctly be formatted using the MySQL pyformat parameter style. Is the correct logic for obtaining the later statement simply:

print(query % {})

Author:John,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50810439/sqlalchemy-compiled-statement-without-percent-signs-conditionally-escaped
yy