Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8558243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T15:46:03+00:00 2026-06-11T15:46:03+00:00

I’d like to use regexp query in sqlalchemy as well as is done in

  • 0

I’d like to use regexp query in “sqlalchemy” as well as is done in “python sqlite”, code below..

Unfinished sandbox script is this:

import os
import re
import sqlite3

#
# python sqlite
#

DB_PATH = __name__ + '.db'

try:
    os.remove(DB_PATH)
except:
    pass


def re_fn(expr, item):
    reg = re.compile(expr, re.I)
    return reg.search(item) is not None

conn = sqlite3.connect(':memory:')
conn = sqlite3.connect(DB_PATH)
conn.create_function("REGEXP", 2, re_fn)
cursor = conn.cursor()

cursor.execute(
    'CREATE TABLE t1 (id INTEGER PRIMARY KEY, c1 TEXT)'
)
cursor.executemany(
    #'INSERT INTO t1 (c1) VALUES (?)', [('aaa"test"',),('blah',)]
    'INSERT INTO t1 (c1) VALUES (?)', [
        ('dupa / 1st Part',), ('cycki / 2nd Part',), ('fiut / 3rd Part',)
    ]
)
cursor.execute(
    #'SELECT c1 FROM t1 WHERE c1 REGEXP ?',['2|3\w+part']
    'SELECT c1 FROM t1 WHERE c1 REGEXP ?',['\d\w+ part']
)
conn.commit()
data=cursor.fetchall()
print(data)



#
# sqlalchemy
#

import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base

DSN = 'sqlite:///' + DB_PATH
engine = sa.create_engine(DSN, convert_unicode=True)
db = orm.scoped_session(orm.sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base = declarative_base(bind=engine)
meta = Base.metadata

class T1(Base):
    __table__ = sa.Table('t1', meta, autoload=True)

print(db.query(T1).all())

I’ve found that regexp function should be registered on each thread:

http://permalink.gmane.org/gmane.comp.web.pylons.general/12742

but I’m not able to adopt link’s solution to my script + it’s deprecated.

Update

I’d like to query this:

cursor.execute(
    #'SELECT c1 FROM t1 WHERE c1 REGEXP ?',['2|3\w+part']
    'SELECT c1 FROM t1 WHERE c1 REGEXP ?',['\d\w+ part']
)

but in sqlalchemy.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T15:46:05+00:00Added an answer on June 11, 2026 at 3:46 pm

    I’ve got the answer..
    Complete working script with missing one line is this:

    import os
    import re
    import sqlite3
    
    DB_PATH = __name__ + '.db'
    
    try:
        os.remove(DB_PATH)
    except:
        pass
    
    
    def re_fn(expr, item):
        reg = re.compile(expr, re.I)
        return reg.search(item) is not None
    
    conn = sqlite3.connect(':memory:')
    conn = sqlite3.connect(DB_PATH)
    conn.create_function("REGEXP", 2, re_fn)
    cursor = conn.cursor()
    
    cursor.execute(
        'CREATE TABLE t1 (id INTEGER PRIMARY KEY, c1 TEXT)'
    )
    cursor.executemany(
        #'INSERT INTO t1 (c1) VALUES (?)', [('aaa"test"',),('blah',)]
        'INSERT INTO t1 (c1) VALUES (?)', [
            ('dupa / 1st Part',), ('cycki / 2nd Part',), ('fiut / 3rd Part',)
        ]
    )
    SEARCH_TERM = '3rd part'
    cursor.execute(
        #'SELECT c1 FROM t1 WHERE c1 REGEXP ?',['2|3\w+part']
        'SELECT c1 FROM t1 WHERE c1 REGEXP ?',[SEARCH_TERM]
    )
    conn.commit()
    data=cursor.fetchall()
    print(data)
    
    
    
    #
    # sqlalchemy
    #
    
    import sqlalchemy as sa
    import sqlalchemy.orm as orm
    from sqlalchemy.ext.declarative import declarative_base
    
    DSN = 'sqlite:///' + DB_PATH
    
    engine = sa.create_engine(DSN, convert_unicode=True)
    
    conn = engine.connect()
    conn.connection.create_function('regexp', 2, re_fn)
    
    db = orm.scoped_session(orm.sessionmaker(autocommit=False,
                                             autoflush=False,
                                             bind=engine))
    
    Base = declarative_base(bind=engine)
    meta = Base.metadata
    
    class T1(Base):
        __table__ = sa.Table('t1', meta, autoload=True)
    
    print(db.query(T1.c1).filter(T1.c1.op('regexp')(SEARCH_TERM)).all())
    

    Above works in sqlalchemy=0.6.3

    In sqlalchemy=0.7.8 i got error:

    “sqlalchemy.exc.OperationalError: (OperationalError) no such function:
    regexp ..”

    maybe because of this change:

    When a file-based database is specified, the dialect will use NullPool
    as the source of connections. This pool closes and discards
    connections which are returned to the pool immediately. SQLite
    file-based connections have extremely low overhead, so pooling is not
    necessary
    . The scheme also prevents a connection from being used again
    in a different thread and works best with SQLite’s coarse-grained file
    locking.
    Changed in version 0.7: Default selection of NullPool for SQLite
    file-based databases. Previous versions select SingletonThreadPool by
    default for all SQLite databases.

    from: http://docs.sqlalchemy.org/en/rel_0_7/dialects/sqlite.html?highlight=isolation_level#threading-pooling-behavior

    and solution for that was:
    to add regexp fn in ‘begin’ event like this:

    ...
    
    conn = engine.connect()
    @sa.event.listens_for(engine, "begin")
    def do_begin(conn):
        conn.connection.create_function('regexp', 2, re_fn)
    
    db = orm.scoped_session(orm.sessionmaker(autocommit=False,
                                             autoflush=False,
                                             bind=engine))
    
    ...
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have two tables with like below codes: Table: Accounts id | username |
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I've got a string that has curly quotes in it. I'd like to replace
I would like to run a str_replace or preg_replace which looks for certain words
I am trying to render a haml file in a javascript response like so:
I have this code to decode numeric html entities to the UTF8 equivalent character.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.