Updated serach fix

This commit is contained in:
Amit Salunke 2026-09-26 22:13:04 +05:30
parent 0cf0022f59
commit 92c29dd673
19 changed files with 3431 additions and 9 deletions

39
alembic.ini Normal file
View File

@ -0,0 +1,39 @@
[alembic]
script_location = alembic
prepend_sys_path = .
path_separator = os
sqlalchemy.url = postgresql+asyncpg://placeholder:placeholder@localhost/placeholder
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

50
alembic/README.txt Normal file
View File

@ -0,0 +1,50 @@
AccuPedia Alembic bootstrap
============================
Files:
env.py
versions/20260924_0001_baseline_existing_schema.py
versions/20260924_0002_add_template_search_flags.py
Expected project placement:
<repo-root>/
├── alembic.ini
├── alembic/
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
│ ├── 20260924_0001_baseline_existing_schema.py
│ └── 20260924_0002_add_template_search_flags.py
└── app/
Initialization sequence:
1. From repo root:
alembic init alembic
2. Replace generated alembic/env.py with this env.py.
3. Copy both revision files into alembic/versions/.
4. Ensure alembic.ini keeps a sqlalchemy.url key.
Its literal value is not used as the authoritative source because env.py
overwrites it from app.core.config.settings.database_url.
5. Existing database only:
alembic stamp 20260924_0001
6. Apply new schema change:
alembic upgrade head
7. Verify:
alembic current
alembic heads
Important:
- Do NOT run `alembic stamp head` before applying 20260924_0002. That would mark
the search-flag migration as applied without actually adding the columns.
- For a brand-new empty database, this two-file baseline approach does not
create the historical schema. Continue using your existing schema bootstrap
until the complete historical schema is migrated into Alembic, or create a
dedicated initial-schema migration later.

87
alembic/env.py Normal file
View File

@ -0,0 +1,87 @@
from __future__ import annotations
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from app.core.config import settings
from app.db.base import Base
import app.db.models
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option(
"sqlalchemy.url",
settings.database_url.replace("%", "%%"),
)
target_metadata = Base.metadata
def include_object(object_, name, type_, reflected, compare_to):
schemas = {"auth", "content", "commerce", "platform"}
schema = getattr(object_, "schema", None)
if type_ == "table":
return schema in schemas
table = getattr(object_, "table", None)
if table is not None:
return getattr(table, "schema", None) in schemas
return True
def configure(connection=None, url=None):
context.configure(
connection=connection,
url=url,
target_metadata=target_metadata,
include_schemas=True,
include_object=include_object,
compare_type=True,
compare_server_default=True,
literal_binds=connection is None,
dialect_opts={"paramstyle": "named"} if connection is None else None,
version_table="alembic_version",
version_table_schema="public",
)
def run_migrations_offline():
configure(url=config.get_main_option("sqlalchemy.url"))
with context.begin_transaction():
context.run_migrations()
def run_migrations_sync(connection: Connection):
configure(connection=connection)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_async():
engine = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
try:
async with engine.connect() as connection:
await connection.run_sync(run_migrations_sync)
finally:
await engine.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_async())

View File

@ -0,0 +1,174 @@
from __future__ import annotations
from collections.abc import Sequence
from pathlib import Path
import re
from alembic import op
revision: str = "0001_baseline_schema"
down_revision: str | None = None
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None
def _split_sql(text: str) -> list[str]:
statements = []
buffer = []
i = 0
dollar_tag = None
in_single = False
in_double = False
in_line_comment = False
in_block_comment = False
block_depth = 0
while i < len(text):
ch = text[i]
nxt = text[i + 1] if i + 1 < len(text) else ""
if in_line_comment:
buffer.append(ch)
if ch == "\n":
in_line_comment = False
i += 1
continue
if in_block_comment:
buffer.append(ch)
if ch == "/" and nxt == "*":
block_depth += 1
buffer.append(nxt)
i += 2
continue
if ch == "*" and nxt == "/":
if block_depth == 0:
buffer.append(nxt)
i += 2
in_block_comment = False
continue
block_depth -= 1
buffer.append(nxt)
i += 2
continue
i += 1
continue
if dollar_tag is not None:
if text.startswith(dollar_tag, i):
buffer.append(dollar_tag)
i += len(dollar_tag)
dollar_tag = None
else:
buffer.append(ch)
i += 1
continue
if in_single:
buffer.append(ch)
if ch == "'":
if nxt == "'":
buffer.append(nxt)
i += 2
continue
in_single = False
i += 1
continue
if in_double:
buffer.append(ch)
if ch == '"':
if nxt == '"':
buffer.append(nxt)
i += 2
continue
in_double = False
i += 1
continue
if ch == "-" and nxt == "-":
buffer.extend([ch, nxt])
i += 2
in_line_comment = True
continue
if ch == "/" and nxt == "*":
buffer.extend([ch, nxt])
i += 2
in_block_comment = True
block_depth = 0
continue
if ch == "'":
buffer.append(ch)
i += 1
in_single = True
continue
if ch == '"':
buffer.append(ch)
i += 1
in_double = True
continue
if ch == "$":
match = re.match(r"\$[A-Za-z_][A-Za-z0-9_]*\$|\$\$", text[i:])
if match:
tag = match.group(0)
buffer.append(tag)
i += len(tag)
dollar_tag = tag
continue
if ch == ";":
statement = "".join(buffer).strip()
if statement:
statements.append(statement)
buffer = []
i += 1
continue
buffer.append(ch)
i += 1
statement = "".join(buffer).strip()
if statement:
statements.append(statement)
return statements
def _is_transaction_statement(statement: str) -> bool:
lines = [
line.strip()
for line in statement.splitlines()
if line.strip() and not line.strip().startswith("--")
]
if not lines:
return True
value = "\n".join(lines).strip().lower()
return value in {
"begin",
"begin transaction",
"commit",
"commit transaction",
}
def upgrade() -> None:
path = Path(__file__).parent / "sql" / "acupedia_schema_v5.sql"
sql = path.read_text(encoding="utf-8")
connection = op.get_bind()
for statement in _split_sql(sql):
if not _is_transaction_statement(statement):
connection.exec_driver_sql(statement)
def downgrade() -> None:
connection = op.get_bind()
connection.exec_driver_sql("DROP SCHEMA IF EXISTS platform CASCADE")
connection.exec_driver_sql("DROP SCHEMA IF EXISTS commerce CASCADE")
connection.exec_driver_sql("DROP SCHEMA IF EXISTS content CASCADE")
connection.exec_driver_sql("DROP SCHEMA IF EXISTS auth CASCADE")

View File

@ -0,0 +1,61 @@
"""add template searchability and filterability flags
Revision ID: 0002_add_template_search_flags
Revises: 0001_baseline_schema
Create Date: 2026-09-24
"""
from __future__ import annotations
from collections.abc import Sequence
from alembic import op
import sqlalchemy as sa
revision: str = "0002_add_template_search_flags"
down_revision: str | None = "0001_baseline_schema"
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None
CONTENT_SCHEMA = "content"
TABLE_NAME = "attribute_definition_sets"
def upgrade() -> None:
op.add_column(
TABLE_NAME,
sa.Column(
"is_searchable",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
schema=CONTENT_SCHEMA,
)
op.add_column(
TABLE_NAME,
sa.Column(
"is_filterable",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
schema=CONTENT_SCHEMA,
)
def downgrade() -> None:
op.drop_column(
TABLE_NAME,
"is_filterable",
schema=CONTENT_SCHEMA,
)
op.drop_column(
TABLE_NAME,
"is_searchable",
schema=CONTENT_SCHEMA,
)

File diff suppressed because it is too large Load Diff

View File

@ -153,6 +153,9 @@ class AttributeDefinitionSeeder:
"description"
)
is_searchable = document["is_searchable"]
is_filterable = document["is_filterable"]
metadata = json.dumps(
document.get("metadata")
or {}
@ -273,6 +276,12 @@ class AttributeDefinitionSeeder:
is_active =
true,
is_searchable =
:is_searchable,
is_filterable =
:is_filterable,
metadata =
cast(
:metadata
@ -314,6 +323,8 @@ class AttributeDefinitionSeeder:
"description": (
description
),
"is_searchable": is_searchable,
"is_filterable": is_filterable,
"metadata": metadata,
},
)
@ -381,6 +392,8 @@ class AttributeDefinitionSeeder:
content_kind,
description,
is_active,
is_searchable,
is_filterable,
metadata
)
values (
@ -396,6 +409,8 @@ class AttributeDefinitionSeeder:
:description,
true,
:is_searchable,
:is_filterable,
cast(
:metadata
@ -425,6 +440,8 @@ class AttributeDefinitionSeeder:
),
"content_kind": content_kind,
"description": description,
"is_searchable": is_searchable,
"is_filterable": is_filterable,
"metadata": metadata,
},
)

View File

@ -141,6 +141,8 @@ class SearchFacetSeeder:
join {self.schema}.attribute_definition_sets ads
on ads.id = ad.attribute_definition_set_id
where ads.code = :template_code
and ads.is_active = true
and ads.is_filterable = true
and ad.attribute_key = :attribute_key
and ad.is_active = true
"""
@ -153,7 +155,8 @@ class SearchFacetSeeder:
attribute_definition_id = definition_result.scalar_one_or_none()
if attribute_definition_id is None:
raise SearchFacetSeedError(
f"Active attribute definition not found: {template_code}/{attribute_key}"
f"Active filterable template attribute definition not found: "
f"{template_code}/{attribute_key}"
)
mapping_module_id = (

View File

@ -116,6 +116,14 @@ def validate_definition_document(document: Mapping[str, Any]) -> None:
require_non_empty_string(document["attribute_prefix_code"], "attribute_prefix_code")
require_non_empty_string(document["attribute_prefix_name"], "attribute_prefix_name")
# Template-level search participation is an explicit contract.
# There are intentionally no compatibility defaults.
for flag in ("is_searchable", "is_filterable"):
if flag not in document:
raise DefinitionValidationError(f"Missing required field: {flag}")
if not isinstance(document[flag], bool):
raise DefinitionValidationError(f"{flag} must be a boolean")
defs = document["attribute_defs"]
if not isinstance(defs, list) or not defs:
raise DefinitionValidationError("attribute_defs must be a non-empty array")

View File

@ -108,6 +108,7 @@ async def _resolve_user(
assert email is not None
normalized = email.strip().lower()
stmt = select(AppUser).where(AppUser.email == normalized)
user = (await session.execute(stmt)).scalar_one_or_none()
if user is None:

View File

@ -0,0 +1,6 @@
-- Template-level search/filter participation.
-- Strict new contract: both flags default false; template JSON must declare both.
alter table content.attribute_definition_sets
add column if not exists is_searchable boolean not null default false,
add column if not exists is_filterable boolean not null default false;

View File

@ -76,6 +76,8 @@ class AttributeDefinitionSet(Base):
content_kind: Mapped[ContentKind | None] = mapped_column(CONTENT_KIND_ENUM)
description: Mapped[str | None] = mapped_column(Text)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
is_searchable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
is_filterable: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
metadata_json: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))

View File

@ -103,7 +103,7 @@ class AuthService:
country=country,
password_hash=hash_password(request.password),
)
role = await self.repository.get_role_by_name(PRACTITIONER_ROLE)
if role is not None:
await self.repository.assign_role(
@ -111,6 +111,7 @@ class AuthService:
role_id=role.id,
)
# Preserve current registration response semantics.
roles = [PRACTITIONER_ROLE]

View File

@ -149,7 +149,7 @@ class SearchRepository:
where = ["is_active = true", "status = 'active'"]
if effective_scope.module_codes:
params["capability_module_codes"] = [
code.strip() for code in effective_scope.module_codes if code and code.strip()
code.strip().lower() for code in effective_scope.module_codes if code and code.strip()
]
where.append("code = any(cast(:capability_module_codes as text[]))")
@ -319,19 +319,26 @@ class SearchRepository:
text(
f"""
select ci.id, ci.title, ci.summary, ci.content_kind::text as content_kind,
ads.code as template_code
ads.code as template_code, ads.is_filterable
from {self.schema}.content_items ci
join {self.schema}.attribute_definition_sets ads
on ads.id = ci.attribute_definition_set_id
where ci.id = :content_id
and ci.is_active = true
and ci.status = 'published'
and ads.is_searchable = true
"""
),
{"content_id": content_id},
)
content = content_result.mappings().one_or_none()
if content is None:
# A non-searchable/unpublished/inactive template must leave no stale
# search document or facet projection behind.
await self.session.execute(
text(f"delete from {self.schema}.content_search_facets where content_id = :content_id"),
{"content_id": content_id},
)
await self.session.execute(
text(f"delete from {self.schema}.content_search_documents where content_id = :content_id"),
{"content_id": content_id},
@ -386,7 +393,11 @@ class SearchRepository:
{"content_id": content_id},
)
mappings = await self.list_mappings_for_content(content_id)
mappings = (
await self.list_mappings_for_content(content_id)
if content["is_filterable"]
else []
)
inserted = 0
for mapping in mappings:
raw_rows = await self._attribute_values_for_mapping(
@ -442,7 +453,7 @@ class SearchRepository:
module_clause = ""
if module_codes:
params["module_codes"] = [
code.strip() for code in module_codes if code and code.strip()
code.strip().lower() for code in module_codes if code and code.strip()
]
module_clause = f"""
and exists (
@ -476,7 +487,7 @@ class SearchRepository:
clauses: list[str] = []
if scope.module_codes:
params["scope_module_codes"] = [
code.strip() for code in scope.module_codes if code and code.strip()
code.strip().lower() for code in scope.module_codes if code and code.strip()
]
clauses.append(
f"""exists (

View File

@ -46,7 +46,7 @@ class SearchScope(StrictModel):
@model_validator(mode="after")
def normalize(self) -> "SearchScope":
if self.module_codes is not None:
values = [value.strip() for value in self.module_codes if value.strip()]
values = [value.strip().lower() for value in self.module_codes if value.strip()]
self.module_codes = list(dict.fromkeys(values)) or None
if self.content_kinds is not None:
values = [value.strip().lower() for value in self.content_kinds if value.strip()]

View File

@ -14,6 +14,45 @@ from .schema import (
SearchScope,
)
_DISPLAY_ACRONYMS = {
"tcm": "TCM",
"lu": "LU", "li": "LI", "st": "ST", "sp": "SP",
"ht": "HT", "si": "SI", "bl": "BL", "ki": "KI",
"pc": "PC", "sj": "SJ", "gb": "GB", "lr": "LR",
"cv": "CV", "gv": "GV",
}
_DISPLAY_MINOR_WORDS = {"a", "an", "and", "as", "at", "by", "for", "from", "in", "of", "on", "or", "the", "to", "with"}
def _facet_display_label(value: str) -> str:
"""Return a consistent UI label without changing the canonical value_key."""
text = " ".join(value.strip().split())
if not text:
return text
def format_token(token: str, index: int) -> str:
# Preserve punctuation around a word while normalizing its casing.
start = 0
end = len(token)
while start < end and not token[start].isalnum():
start += 1
while end > start and not token[end - 1].isalnum():
end -= 1
prefix, core, suffix = token[:start], token[start:end], token[end:]
if not core:
return token
lower = core.lower()
if lower in _DISPLAY_ACRONYMS:
display = _DISPLAY_ACRONYMS[lower]
elif index > 0 and lower in _DISPLAY_MINOR_WORDS:
display = lower
else:
display = lower[:1].upper() + lower[1:]
return f"{prefix}{display}{suffix}"
return " ".join(format_token(token, index) for index, token in enumerate(text.split(" ")))
class SearchService:
def __init__(self, repository: SearchRepository) -> None:
@ -63,7 +102,7 @@ class SearchService:
items=[
FacetValueResponse(
value_key=row["value_key"],
label=row["label"],
label=_facet_display_label(row["label"]),
result_count=row["result_count"],
)
for row in rows

View File

@ -343,6 +343,8 @@ create table if not exists content.attribute_definition_sets (
description text,
is_active boolean not null default true,
is_searchable boolean not null default false,
is_filterable boolean not null default false,
metadata jsonb not null default '{}'::jsonb,