Here's an example usage of the get_data_w_like_2 method with sample output, using a SQLAlchemy User model:
1. Define the Model
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
created_at = Column(DateTime, default=datetime.now)
updated_at = Column(DateTime)
2. Setup and Sample Data
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
with Session(engine) as session:
# Add sample data
session.add_all([
User(name="John Doe", age=25, updated_at=datetime(2023, 1, 15)),
User(name="Jane Smith", age=30, updated_at=datetime(2023, 2, 10)),
User(name="Alice Johnson", age=25, updated_at=None),
User(name="Bob Brown", age=35, updated_at=datetime(2023, 3, 5)),
User(name="Charlie Lee", age=25, updated_at=None)
])
session.commit()
3. Example Queries
# Example 1: Simple equality filter
results = get_data_w_like_2(
session=session,
table=User,
age=25
)
print([(u.name, u.age) for u in results])
# Output: [('John Doe', 25), ('Alice Johnson', 25), ('Charlie Lee', 25)]
# Example 2: LIKE operation + multiple filters
results = get_data_w_like_2(
session=session,
table=User,
name_like='%ohn%', # Special _like operation
name_op='like', # Operation specifier
age=25
)
print([u.name for u in results])
# Output: ['John Doe', 'Alice Johnson']
# Example 3: Greater than operation + NULL check
results = get_data_w_like_2(
session=session,
table=User,
age_op='>', # Special operation
age=25, # Value for comparison
datetime_column=User.updated_at,
datetime_switch=True # Show only NULL updated_at
)
print([(u.name, u.age) for u in results])
# Output: [('Alice Johnson', 25), ('Charlie Lee', 25)]
# Example 4: Sorting with multiple columns
results = get_data_w_like_2(
session=session,
table=User,
sort_columns=[User.age, User.name],
sort_orders=['desc', 'asc']
)
print([(u.age, u.name) for u in results])
# Output: [(35, 'Bob Brown'), (30, 'Jane Smith'), (25, 'Alice Johnson'), (25, 'Charlie Lee'), (25, 'John Doe')]
# Example 5: Combination of operations
results = get_data_w_like_2(
session=session,
table=User,
age_op='!=', # Not equals operation
age=30,
name_like='%a%',
name_op='like'
)
print([(u.name, u.age) for u in results])
# Output: [('Alice Johnson', 25), ('Charlie Lee', 25), ('Bob Brown', 35)]
Key Features Demonstrated: