basic-memory 0.17.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- basic_memory/__init__.py +7 -0
- basic_memory/alembic/alembic.ini +119 -0
- basic_memory/alembic/env.py +185 -0
- basic_memory/alembic/migrations.py +24 -0
- basic_memory/alembic/script.py.mako +26 -0
- basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
- basic_memory/alembic/versions/3dae7c7b1564_initial_schema.py +93 -0
- basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
- basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
- basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
- basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
- basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
- basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
- basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
- basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
- basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
- basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
- basic_memory/api/__init__.py +5 -0
- basic_memory/api/app.py +131 -0
- basic_memory/api/routers/__init__.py +11 -0
- basic_memory/api/routers/directory_router.py +84 -0
- basic_memory/api/routers/importer_router.py +152 -0
- basic_memory/api/routers/knowledge_router.py +318 -0
- basic_memory/api/routers/management_router.py +80 -0
- basic_memory/api/routers/memory_router.py +90 -0
- basic_memory/api/routers/project_router.py +448 -0
- basic_memory/api/routers/prompt_router.py +260 -0
- basic_memory/api/routers/resource_router.py +249 -0
- basic_memory/api/routers/search_router.py +36 -0
- basic_memory/api/routers/utils.py +169 -0
- basic_memory/api/template_loader.py +292 -0
- basic_memory/api/v2/__init__.py +35 -0
- basic_memory/api/v2/routers/__init__.py +21 -0
- basic_memory/api/v2/routers/directory_router.py +93 -0
- basic_memory/api/v2/routers/importer_router.py +182 -0
- basic_memory/api/v2/routers/knowledge_router.py +413 -0
- basic_memory/api/v2/routers/memory_router.py +130 -0
- basic_memory/api/v2/routers/project_router.py +342 -0
- basic_memory/api/v2/routers/prompt_router.py +270 -0
- basic_memory/api/v2/routers/resource_router.py +286 -0
- basic_memory/api/v2/routers/search_router.py +73 -0
- basic_memory/cli/__init__.py +1 -0
- basic_memory/cli/app.py +84 -0
- basic_memory/cli/auth.py +277 -0
- basic_memory/cli/commands/__init__.py +18 -0
- basic_memory/cli/commands/cloud/__init__.py +6 -0
- basic_memory/cli/commands/cloud/api_client.py +112 -0
- basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
- basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
- basic_memory/cli/commands/cloud/core_commands.py +195 -0
- basic_memory/cli/commands/cloud/rclone_commands.py +371 -0
- basic_memory/cli/commands/cloud/rclone_config.py +110 -0
- basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
- basic_memory/cli/commands/cloud/upload.py +233 -0
- basic_memory/cli/commands/cloud/upload_command.py +124 -0
- basic_memory/cli/commands/command_utils.py +77 -0
- basic_memory/cli/commands/db.py +44 -0
- basic_memory/cli/commands/format.py +198 -0
- basic_memory/cli/commands/import_chatgpt.py +84 -0
- basic_memory/cli/commands/import_claude_conversations.py +87 -0
- basic_memory/cli/commands/import_claude_projects.py +86 -0
- basic_memory/cli/commands/import_memory_json.py +87 -0
- basic_memory/cli/commands/mcp.py +76 -0
- basic_memory/cli/commands/project.py +889 -0
- basic_memory/cli/commands/status.py +174 -0
- basic_memory/cli/commands/telemetry.py +81 -0
- basic_memory/cli/commands/tool.py +341 -0
- basic_memory/cli/main.py +28 -0
- basic_memory/config.py +616 -0
- basic_memory/db.py +394 -0
- basic_memory/deps.py +705 -0
- basic_memory/file_utils.py +478 -0
- basic_memory/ignore_utils.py +297 -0
- basic_memory/importers/__init__.py +27 -0
- basic_memory/importers/base.py +79 -0
- basic_memory/importers/chatgpt_importer.py +232 -0
- basic_memory/importers/claude_conversations_importer.py +180 -0
- basic_memory/importers/claude_projects_importer.py +148 -0
- basic_memory/importers/memory_json_importer.py +108 -0
- basic_memory/importers/utils.py +61 -0
- basic_memory/markdown/__init__.py +21 -0
- basic_memory/markdown/entity_parser.py +279 -0
- basic_memory/markdown/markdown_processor.py +160 -0
- basic_memory/markdown/plugins.py +242 -0
- basic_memory/markdown/schemas.py +70 -0
- basic_memory/markdown/utils.py +117 -0
- basic_memory/mcp/__init__.py +1 -0
- basic_memory/mcp/async_client.py +139 -0
- basic_memory/mcp/project_context.py +141 -0
- basic_memory/mcp/prompts/__init__.py +19 -0
- basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
- basic_memory/mcp/prompts/continue_conversation.py +62 -0
- basic_memory/mcp/prompts/recent_activity.py +188 -0
- basic_memory/mcp/prompts/search.py +57 -0
- basic_memory/mcp/prompts/utils.py +162 -0
- basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
- basic_memory/mcp/resources/project_info.py +71 -0
- basic_memory/mcp/server.py +81 -0
- basic_memory/mcp/tools/__init__.py +48 -0
- basic_memory/mcp/tools/build_context.py +120 -0
- basic_memory/mcp/tools/canvas.py +152 -0
- basic_memory/mcp/tools/chatgpt_tools.py +190 -0
- basic_memory/mcp/tools/delete_note.py +242 -0
- basic_memory/mcp/tools/edit_note.py +324 -0
- basic_memory/mcp/tools/list_directory.py +168 -0
- basic_memory/mcp/tools/move_note.py +551 -0
- basic_memory/mcp/tools/project_management.py +201 -0
- basic_memory/mcp/tools/read_content.py +281 -0
- basic_memory/mcp/tools/read_note.py +267 -0
- basic_memory/mcp/tools/recent_activity.py +534 -0
- basic_memory/mcp/tools/search.py +385 -0
- basic_memory/mcp/tools/utils.py +540 -0
- basic_memory/mcp/tools/view_note.py +78 -0
- basic_memory/mcp/tools/write_note.py +230 -0
- basic_memory/models/__init__.py +15 -0
- basic_memory/models/base.py +10 -0
- basic_memory/models/knowledge.py +226 -0
- basic_memory/models/project.py +87 -0
- basic_memory/models/search.py +85 -0
- basic_memory/repository/__init__.py +11 -0
- basic_memory/repository/entity_repository.py +503 -0
- basic_memory/repository/observation_repository.py +73 -0
- basic_memory/repository/postgres_search_repository.py +379 -0
- basic_memory/repository/project_info_repository.py +10 -0
- basic_memory/repository/project_repository.py +128 -0
- basic_memory/repository/relation_repository.py +146 -0
- basic_memory/repository/repository.py +385 -0
- basic_memory/repository/search_index_row.py +95 -0
- basic_memory/repository/search_repository.py +94 -0
- basic_memory/repository/search_repository_base.py +241 -0
- basic_memory/repository/sqlite_search_repository.py +439 -0
- basic_memory/schemas/__init__.py +86 -0
- basic_memory/schemas/base.py +297 -0
- basic_memory/schemas/cloud.py +50 -0
- basic_memory/schemas/delete.py +37 -0
- basic_memory/schemas/directory.py +30 -0
- basic_memory/schemas/importer.py +35 -0
- basic_memory/schemas/memory.py +285 -0
- basic_memory/schemas/project_info.py +212 -0
- basic_memory/schemas/prompt.py +90 -0
- basic_memory/schemas/request.py +112 -0
- basic_memory/schemas/response.py +229 -0
- basic_memory/schemas/search.py +117 -0
- basic_memory/schemas/sync_report.py +72 -0
- basic_memory/schemas/v2/__init__.py +27 -0
- basic_memory/schemas/v2/entity.py +129 -0
- basic_memory/schemas/v2/resource.py +46 -0
- basic_memory/services/__init__.py +8 -0
- basic_memory/services/context_service.py +601 -0
- basic_memory/services/directory_service.py +308 -0
- basic_memory/services/entity_service.py +864 -0
- basic_memory/services/exceptions.py +37 -0
- basic_memory/services/file_service.py +541 -0
- basic_memory/services/initialization.py +216 -0
- basic_memory/services/link_resolver.py +121 -0
- basic_memory/services/project_service.py +880 -0
- basic_memory/services/search_service.py +404 -0
- basic_memory/services/service.py +15 -0
- basic_memory/sync/__init__.py +6 -0
- basic_memory/sync/background_sync.py +26 -0
- basic_memory/sync/sync_service.py +1259 -0
- basic_memory/sync/watch_service.py +510 -0
- basic_memory/telemetry.py +249 -0
- basic_memory/templates/prompts/continue_conversation.hbs +110 -0
- basic_memory/templates/prompts/search.hbs +101 -0
- basic_memory/utils.py +468 -0
- basic_memory-0.17.1.dist-info/METADATA +617 -0
- basic_memory-0.17.1.dist-info/RECORD +171 -0
- basic_memory-0.17.1.dist-info/WHEEL +4 -0
- basic_memory-0.17.1.dist-info/entry_points.txt +3 -0
- basic_memory-0.17.1.dist-info/licenses/LICENSE +661 -0
basic_memory/__init__.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# A generic, single database configuration.
|
|
2
|
+
|
|
3
|
+
[alembic]
|
|
4
|
+
# path to migration scripts
|
|
5
|
+
# Use forward slashes (/) also on windows to provide an os agnostic path
|
|
6
|
+
script_location = .
|
|
7
|
+
|
|
8
|
+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
|
9
|
+
# Uncomment the line below if you want the files to be prepended with date and time
|
|
10
|
+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
|
11
|
+
# for all available tokens
|
|
12
|
+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
|
13
|
+
|
|
14
|
+
# sys.path path, will be prepended to sys.path if present.
|
|
15
|
+
# defaults to the current working directory.
|
|
16
|
+
prepend_sys_path = .
|
|
17
|
+
|
|
18
|
+
# timezone to use when rendering the date within the migration file
|
|
19
|
+
# as well as the filename.
|
|
20
|
+
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
|
|
21
|
+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
|
|
22
|
+
# string value is passed to ZoneInfo()
|
|
23
|
+
# leave blank for localtime
|
|
24
|
+
# timezone =
|
|
25
|
+
|
|
26
|
+
# max length of characters to apply to the "slug" field
|
|
27
|
+
# truncate_slug_length = 40
|
|
28
|
+
|
|
29
|
+
# set to 'true' to run the environment during
|
|
30
|
+
# the 'revision' command, regardless of autogenerate
|
|
31
|
+
# revision_environment = false
|
|
32
|
+
|
|
33
|
+
# set to 'true' to allow .pyc and .pyo files without
|
|
34
|
+
# a source .py file to be detected as revisions in the
|
|
35
|
+
# versions/ directory
|
|
36
|
+
# sourceless = false
|
|
37
|
+
|
|
38
|
+
# version location specification; This defaults
|
|
39
|
+
# to migrations/versions. When using multiple version
|
|
40
|
+
# directories, initial revisions must be specified with --version-path.
|
|
41
|
+
# The path separator used here should be the separator specified by "version_path_separator" below.
|
|
42
|
+
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
|
43
|
+
|
|
44
|
+
# version path separator; As mentioned above, this is the character used to split
|
|
45
|
+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
|
46
|
+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
|
47
|
+
# Valid values for version_path_separator are:
|
|
48
|
+
#
|
|
49
|
+
# version_path_separator = :
|
|
50
|
+
# version_path_separator = ;
|
|
51
|
+
# version_path_separator = space
|
|
52
|
+
# version_path_separator = newline
|
|
53
|
+
#
|
|
54
|
+
# Use os.pathsep. Default configuration used for new projects.
|
|
55
|
+
version_path_separator = os
|
|
56
|
+
|
|
57
|
+
# set to 'true' to search source files recursively
|
|
58
|
+
# in each "version_locations" directory
|
|
59
|
+
# new in Alembic version 1.10
|
|
60
|
+
# recursive_version_locations = false
|
|
61
|
+
|
|
62
|
+
# the output encoding used when revision files
|
|
63
|
+
# are written from script.py.mako
|
|
64
|
+
# output_encoding = utf-8
|
|
65
|
+
|
|
66
|
+
sqlalchemy.url = driver://user:pass@localhost/dbname
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
[post_write_hooks]
|
|
70
|
+
# post_write_hooks defines scripts or Python functions that are run
|
|
71
|
+
# on newly generated revision scripts. See the documentation for further
|
|
72
|
+
# detail and examples
|
|
73
|
+
|
|
74
|
+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
|
75
|
+
# hooks = black
|
|
76
|
+
# black.type = console_scripts
|
|
77
|
+
# black.entrypoint = black
|
|
78
|
+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
|
79
|
+
|
|
80
|
+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
|
81
|
+
# hooks = ruff
|
|
82
|
+
# ruff.type = exec
|
|
83
|
+
# ruff.executable = %(here)s/.venv/bin/ruff
|
|
84
|
+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
|
85
|
+
|
|
86
|
+
# Logging configuration
|
|
87
|
+
[loggers]
|
|
88
|
+
keys = root,sqlalchemy,alembic
|
|
89
|
+
|
|
90
|
+
[handlers]
|
|
91
|
+
keys = console
|
|
92
|
+
|
|
93
|
+
[formatters]
|
|
94
|
+
keys = generic
|
|
95
|
+
|
|
96
|
+
[logger_root]
|
|
97
|
+
level = WARNING
|
|
98
|
+
handlers = console
|
|
99
|
+
qualname =
|
|
100
|
+
|
|
101
|
+
[logger_sqlalchemy]
|
|
102
|
+
level = WARNING
|
|
103
|
+
handlers =
|
|
104
|
+
qualname = sqlalchemy.engine
|
|
105
|
+
|
|
106
|
+
[logger_alembic]
|
|
107
|
+
level = INFO
|
|
108
|
+
handlers =
|
|
109
|
+
qualname = alembic
|
|
110
|
+
|
|
111
|
+
[handler_console]
|
|
112
|
+
class = StreamHandler
|
|
113
|
+
args = (sys.stderr,)
|
|
114
|
+
level = NOTSET
|
|
115
|
+
formatter = generic
|
|
116
|
+
|
|
117
|
+
[formatter_generic]
|
|
118
|
+
format = %(levelname)-5.5s [%(name)s] %(message)s
|
|
119
|
+
datefmt = %H:%M:%S
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Alembic environment configuration."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from logging.config import fileConfig
|
|
6
|
+
|
|
7
|
+
# Allow nested event loops (needed for pytest-asyncio and other async contexts)
|
|
8
|
+
# Note: nest_asyncio doesn't work with uvloop, so we handle that case separately
|
|
9
|
+
try:
|
|
10
|
+
import nest_asyncio
|
|
11
|
+
|
|
12
|
+
nest_asyncio.apply()
|
|
13
|
+
except (ImportError, ValueError):
|
|
14
|
+
# nest_asyncio not available or can't patch this loop type (e.g., uvloop)
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
from sqlalchemy import engine_from_config, pool
|
|
18
|
+
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
|
19
|
+
|
|
20
|
+
from alembic import context
|
|
21
|
+
|
|
22
|
+
from basic_memory.config import ConfigManager
|
|
23
|
+
|
|
24
|
+
# Trigger: only set test env when actually running under pytest
|
|
25
|
+
# Why: alembic/env.py is imported during normal operations (MCP server startup, migrations)
|
|
26
|
+
# but we only want test behavior during actual test runs
|
|
27
|
+
# Outcome: prevents is_test_env from returning True in production, enabling watch service
|
|
28
|
+
if os.getenv("PYTEST_CURRENT_TEST") is not None:
|
|
29
|
+
os.environ["BASIC_MEMORY_ENV"] = "test"
|
|
30
|
+
|
|
31
|
+
# Import after setting environment variable # noqa: E402
|
|
32
|
+
from basic_memory.models import Base # noqa: E402
|
|
33
|
+
|
|
34
|
+
# this is the Alembic Config object, which provides
|
|
35
|
+
# access to the values within the .ini file in use.
|
|
36
|
+
config = context.config
|
|
37
|
+
|
|
38
|
+
# Load app config - this will read environment variables (BASIC_MEMORY_DATABASE_BACKEND, etc.)
|
|
39
|
+
# due to Pydantic's env_prefix="BASIC_MEMORY_" setting
|
|
40
|
+
app_config = ConfigManager().config
|
|
41
|
+
|
|
42
|
+
# Set the SQLAlchemy URL based on database backend configuration
|
|
43
|
+
# If the URL is already set in config (e.g., from run_migrations), use that
|
|
44
|
+
# Otherwise, get it from app config
|
|
45
|
+
# Note: alembic.ini has a placeholder URL "driver://user:pass@localhost/dbname" that we need to override
|
|
46
|
+
current_url = config.get_main_option("sqlalchemy.url")
|
|
47
|
+
if not current_url or current_url == "driver://user:pass@localhost/dbname":
|
|
48
|
+
from basic_memory.db import DatabaseType
|
|
49
|
+
|
|
50
|
+
sqlalchemy_url = DatabaseType.get_db_url(
|
|
51
|
+
app_config.database_path, DatabaseType.FILESYSTEM, app_config
|
|
52
|
+
)
|
|
53
|
+
config.set_main_option("sqlalchemy.url", sqlalchemy_url)
|
|
54
|
+
|
|
55
|
+
# Interpret the config file for Python logging.
|
|
56
|
+
if config.config_file_name is not None:
|
|
57
|
+
fileConfig(config.config_file_name)
|
|
58
|
+
|
|
59
|
+
# add your model's MetaData object here
|
|
60
|
+
# for 'autogenerate' support
|
|
61
|
+
target_metadata = Base.metadata
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# Add this function to tell Alembic what to include/exclude
|
|
65
|
+
def include_object(object, name, type_, reflected, compare_to):
|
|
66
|
+
# Ignore SQLite FTS tables
|
|
67
|
+
if type_ == "table" and name.startswith("search_index"):
|
|
68
|
+
return False
|
|
69
|
+
return True
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def run_migrations_offline() -> None:
|
|
73
|
+
"""Run migrations in 'offline' mode.
|
|
74
|
+
|
|
75
|
+
This configures the context with just a URL
|
|
76
|
+
and not an Engine, though an Engine is acceptable
|
|
77
|
+
here as well. By skipping the Engine creation
|
|
78
|
+
we don't even need a DBAPI to be available.
|
|
79
|
+
|
|
80
|
+
Calls to context.execute() here emit the given string to the
|
|
81
|
+
script output.
|
|
82
|
+
"""
|
|
83
|
+
url = config.get_main_option("sqlalchemy.url")
|
|
84
|
+
context.configure(
|
|
85
|
+
url=url,
|
|
86
|
+
target_metadata=target_metadata,
|
|
87
|
+
literal_binds=True,
|
|
88
|
+
dialect_opts={"paramstyle": "named"},
|
|
89
|
+
include_object=include_object,
|
|
90
|
+
render_as_batch=True,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
with context.begin_transaction():
|
|
94
|
+
context.run_migrations()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def do_run_migrations(connection):
|
|
98
|
+
"""Execute migrations with the given connection."""
|
|
99
|
+
context.configure(
|
|
100
|
+
connection=connection,
|
|
101
|
+
target_metadata=target_metadata,
|
|
102
|
+
include_object=include_object,
|
|
103
|
+
render_as_batch=True,
|
|
104
|
+
compare_type=True,
|
|
105
|
+
)
|
|
106
|
+
with context.begin_transaction():
|
|
107
|
+
context.run_migrations()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def run_async_migrations(connectable):
|
|
111
|
+
"""Run migrations asynchronously with AsyncEngine."""
|
|
112
|
+
async with connectable.connect() as connection:
|
|
113
|
+
await connection.run_sync(do_run_migrations)
|
|
114
|
+
await connectable.dispose()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_migrations_online() -> None:
|
|
118
|
+
"""Run migrations in 'online' mode.
|
|
119
|
+
|
|
120
|
+
Supports both sync engines (SQLite) and async engines (PostgreSQL with asyncpg).
|
|
121
|
+
"""
|
|
122
|
+
# Check if a connection/engine was provided (e.g., from run_migrations)
|
|
123
|
+
connectable = context.config.attributes.get("connection", None)
|
|
124
|
+
|
|
125
|
+
if connectable is None:
|
|
126
|
+
# No connection provided, create engine from config
|
|
127
|
+
url = context.config.get_main_option("sqlalchemy.url")
|
|
128
|
+
|
|
129
|
+
# Check if it's an async URL (sqlite+aiosqlite or postgresql+asyncpg)
|
|
130
|
+
if url and ("+asyncpg" in url or "+aiosqlite" in url):
|
|
131
|
+
# Create async engine for asyncpg or aiosqlite
|
|
132
|
+
connectable = create_async_engine(
|
|
133
|
+
url,
|
|
134
|
+
poolclass=pool.NullPool,
|
|
135
|
+
future=True,
|
|
136
|
+
)
|
|
137
|
+
else:
|
|
138
|
+
# Create sync engine for regular sqlite or postgresql
|
|
139
|
+
connectable = engine_from_config(
|
|
140
|
+
context.config.get_section(context.config.config_ini_section, {}),
|
|
141
|
+
prefix="sqlalchemy.",
|
|
142
|
+
poolclass=pool.NullPool,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# Handle async engines (PostgreSQL with asyncpg)
|
|
146
|
+
if isinstance(connectable, AsyncEngine):
|
|
147
|
+
# Try to run async migrations
|
|
148
|
+
# nest_asyncio allows asyncio.run() from within event loops, but doesn't work with uvloop
|
|
149
|
+
try:
|
|
150
|
+
asyncio.run(run_async_migrations(connectable))
|
|
151
|
+
except RuntimeError as e:
|
|
152
|
+
if "cannot be called from a running event loop" in str(e):
|
|
153
|
+
# We're in a running event loop (likely uvloop) - need to use a different approach
|
|
154
|
+
# Create a new thread to run the async migrations
|
|
155
|
+
import concurrent.futures
|
|
156
|
+
|
|
157
|
+
def run_in_thread():
|
|
158
|
+
"""Run async migrations in a new event loop in a separate thread."""
|
|
159
|
+
new_loop = asyncio.new_event_loop()
|
|
160
|
+
asyncio.set_event_loop(new_loop)
|
|
161
|
+
try:
|
|
162
|
+
new_loop.run_until_complete(run_async_migrations(connectable))
|
|
163
|
+
finally:
|
|
164
|
+
new_loop.close()
|
|
165
|
+
|
|
166
|
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
|
167
|
+
future = executor.submit(run_in_thread)
|
|
168
|
+
future.result() # Wait for completion and re-raise any exceptions
|
|
169
|
+
else:
|
|
170
|
+
raise
|
|
171
|
+
else:
|
|
172
|
+
# Handle sync engines (SQLite) or sync connections
|
|
173
|
+
if hasattr(connectable, "connect"):
|
|
174
|
+
# It's an engine, get a connection
|
|
175
|
+
with connectable.connect() as connection:
|
|
176
|
+
do_run_migrations(connection)
|
|
177
|
+
else:
|
|
178
|
+
# It's already a connection
|
|
179
|
+
do_run_migrations(connectable)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if context.is_offline_mode():
|
|
183
|
+
run_migrations_offline()
|
|
184
|
+
else:
|
|
185
|
+
run_migrations_online()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Functions for managing database migrations."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from loguru import logger
|
|
5
|
+
from alembic.config import Config
|
|
6
|
+
from alembic import command
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_alembic_config() -> Config: # pragma: no cover
|
|
10
|
+
"""Get alembic config with correct paths."""
|
|
11
|
+
migrations_path = Path(__file__).parent
|
|
12
|
+
alembic_ini = migrations_path / "alembic.ini"
|
|
13
|
+
|
|
14
|
+
config = Config(alembic_ini)
|
|
15
|
+
config.set_main_option("script_location", str(migrations_path))
|
|
16
|
+
return config
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def reset_database(): # pragma: no cover
|
|
20
|
+
"""Drop and recreate all tables."""
|
|
21
|
+
logger.info("Resetting database...")
|
|
22
|
+
config = get_alembic_config()
|
|
23
|
+
command.downgrade(config, "base")
|
|
24
|
+
command.upgrade(config, "head")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""${message}
|
|
2
|
+
|
|
3
|
+
Revision ID: ${up_revision}
|
|
4
|
+
Revises: ${down_revision | comma,n}
|
|
5
|
+
Create Date: ${create_date}
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
from typing import Sequence, Union
|
|
9
|
+
|
|
10
|
+
from alembic import op
|
|
11
|
+
import sqlalchemy as sa
|
|
12
|
+
${imports if imports else ""}
|
|
13
|
+
|
|
14
|
+
# revision identifiers, used by Alembic.
|
|
15
|
+
revision: str = ${repr(up_revision)}
|
|
16
|
+
down_revision: Union[str, None] = ${repr(down_revision)}
|
|
17
|
+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
|
18
|
+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def upgrade() -> None:
|
|
22
|
+
${upgrades if upgrades else "pass"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def downgrade() -> None:
|
|
26
|
+
${downgrades if downgrades else "pass"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Add Postgres full-text search support with tsvector and GIN indexes
|
|
2
|
+
|
|
3
|
+
Revision ID: 314f1ea54dc4
|
|
4
|
+
Revises: e7e1f4367280
|
|
5
|
+
Create Date: 2025-11-15 18:05:01.025405
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Sequence, Union
|
|
10
|
+
|
|
11
|
+
from alembic import op
|
|
12
|
+
import sqlalchemy as sa
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# revision identifiers, used by Alembic.
|
|
16
|
+
revision: str = "314f1ea54dc4"
|
|
17
|
+
down_revision: Union[str, None] = "e7e1f4367280"
|
|
18
|
+
branch_labels: Union[str, Sequence[str], None] = None
|
|
19
|
+
depends_on: Union[str, Sequence[str], None] = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def upgrade() -> None:
|
|
23
|
+
"""Add PostgreSQL full-text search support.
|
|
24
|
+
|
|
25
|
+
This migration:
|
|
26
|
+
1. Creates search_index table for Postgres (SQLite uses FTS5 virtual table)
|
|
27
|
+
2. Adds generated tsvector column for full-text search
|
|
28
|
+
3. Creates GIN index on the tsvector column for fast text queries
|
|
29
|
+
4. Creates GIN index on metadata JSONB column for fast containment queries
|
|
30
|
+
|
|
31
|
+
Note: These changes only apply to Postgres. SQLite continues to use FTS5 virtual tables.
|
|
32
|
+
"""
|
|
33
|
+
# Check if we're using Postgres
|
|
34
|
+
connection = op.get_bind()
|
|
35
|
+
if connection.dialect.name == "postgresql":
|
|
36
|
+
# Create search_index table for Postgres
|
|
37
|
+
# For SQLite, this is a FTS5 virtual table created elsewhere
|
|
38
|
+
from sqlalchemy.dialects.postgresql import JSONB
|
|
39
|
+
|
|
40
|
+
op.create_table(
|
|
41
|
+
"search_index",
|
|
42
|
+
sa.Column("id", sa.Integer(), nullable=False), # Entity IDs are integers
|
|
43
|
+
sa.Column("project_id", sa.Integer(), nullable=False), # Multi-tenant isolation
|
|
44
|
+
sa.Column("title", sa.Text(), nullable=True),
|
|
45
|
+
sa.Column("content_stems", sa.Text(), nullable=True),
|
|
46
|
+
sa.Column("content_snippet", sa.Text(), nullable=True),
|
|
47
|
+
sa.Column("permalink", sa.String(), nullable=True), # Nullable for non-markdown files
|
|
48
|
+
sa.Column("file_path", sa.String(), nullable=True),
|
|
49
|
+
sa.Column("type", sa.String(), nullable=True),
|
|
50
|
+
sa.Column("from_id", sa.Integer(), nullable=True), # Relation IDs are integers
|
|
51
|
+
sa.Column("to_id", sa.Integer(), nullable=True), # Relation IDs are integers
|
|
52
|
+
sa.Column("relation_type", sa.String(), nullable=True),
|
|
53
|
+
sa.Column("entity_id", sa.Integer(), nullable=True), # Entity IDs are integers
|
|
54
|
+
sa.Column("category", sa.String(), nullable=True),
|
|
55
|
+
sa.Column("metadata", JSONB(), nullable=True), # Use JSONB for Postgres
|
|
56
|
+
sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),
|
|
57
|
+
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
|
58
|
+
sa.PrimaryKeyConstraint(
|
|
59
|
+
"id", "type", "project_id"
|
|
60
|
+
), # Composite key: id can repeat across types
|
|
61
|
+
sa.ForeignKeyConstraint(
|
|
62
|
+
["project_id"],
|
|
63
|
+
["project.id"],
|
|
64
|
+
name="fk_search_index_project_id",
|
|
65
|
+
ondelete="CASCADE",
|
|
66
|
+
),
|
|
67
|
+
if_not_exists=True,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Create index on project_id for efficient multi-tenant queries
|
|
71
|
+
op.create_index(
|
|
72
|
+
"ix_search_index_project_id",
|
|
73
|
+
"search_index",
|
|
74
|
+
["project_id"],
|
|
75
|
+
unique=False,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Create unique partial index on permalink for markdown files
|
|
79
|
+
# Non-markdown files don't have permalinks, so we use a partial index
|
|
80
|
+
op.execute("""
|
|
81
|
+
CREATE UNIQUE INDEX uix_search_index_permalink_project
|
|
82
|
+
ON search_index (permalink, project_id)
|
|
83
|
+
WHERE permalink IS NOT NULL
|
|
84
|
+
""")
|
|
85
|
+
|
|
86
|
+
# Add tsvector column as a GENERATED ALWAYS column
|
|
87
|
+
# This automatically updates when title or content_stems change
|
|
88
|
+
op.execute("""
|
|
89
|
+
ALTER TABLE search_index
|
|
90
|
+
ADD COLUMN textsearchable_index_col tsvector
|
|
91
|
+
GENERATED ALWAYS AS (
|
|
92
|
+
to_tsvector('english',
|
|
93
|
+
coalesce(title, '') || ' ' ||
|
|
94
|
+
coalesce(content_stems, '')
|
|
95
|
+
)
|
|
96
|
+
) STORED
|
|
97
|
+
""")
|
|
98
|
+
|
|
99
|
+
# Create GIN index on tsvector column for fast full-text search
|
|
100
|
+
op.create_index(
|
|
101
|
+
"idx_search_index_fts",
|
|
102
|
+
"search_index",
|
|
103
|
+
["textsearchable_index_col"],
|
|
104
|
+
unique=False,
|
|
105
|
+
postgresql_using="gin",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# Create GIN index on metadata JSONB for fast containment queries
|
|
109
|
+
# Using jsonb_path_ops for smaller index size and better performance
|
|
110
|
+
op.execute("""
|
|
111
|
+
CREATE INDEX idx_search_index_metadata_gin
|
|
112
|
+
ON search_index
|
|
113
|
+
USING GIN (metadata jsonb_path_ops)
|
|
114
|
+
""")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def downgrade() -> None:
|
|
118
|
+
"""Remove PostgreSQL full-text search support."""
|
|
119
|
+
connection = op.get_bind()
|
|
120
|
+
if connection.dialect.name == "postgresql":
|
|
121
|
+
# Drop indexes first
|
|
122
|
+
op.execute("DROP INDEX IF EXISTS idx_search_index_metadata_gin")
|
|
123
|
+
op.drop_index("idx_search_index_fts", table_name="search_index")
|
|
124
|
+
op.execute("DROP INDEX IF EXISTS uix_search_index_permalink_project")
|
|
125
|
+
op.drop_index("ix_search_index_project_id", table_name="search_index")
|
|
126
|
+
|
|
127
|
+
# Drop the generated column
|
|
128
|
+
op.execute("ALTER TABLE search_index DROP COLUMN IF EXISTS textsearchable_index_col")
|
|
129
|
+
|
|
130
|
+
# Drop the search_index table
|
|
131
|
+
op.drop_table("search_index")
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""initial schema
|
|
2
|
+
|
|
3
|
+
Revision ID: 3dae7c7b1564
|
|
4
|
+
Revises:
|
|
5
|
+
Create Date: 2025-02-12 21:23:00.336344
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Sequence, Union
|
|
10
|
+
|
|
11
|
+
from alembic import op
|
|
12
|
+
import sqlalchemy as sa
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# revision identifiers, used by Alembic.
|
|
16
|
+
revision: str = "3dae7c7b1564"
|
|
17
|
+
down_revision: Union[str, None] = None
|
|
18
|
+
branch_labels: Union[str, Sequence[str], None] = None
|
|
19
|
+
depends_on: Union[str, Sequence[str], None] = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def upgrade() -> None:
|
|
23
|
+
# ### commands auto generated by Alembic - please adjust! ###
|
|
24
|
+
op.create_table(
|
|
25
|
+
"entity",
|
|
26
|
+
sa.Column("id", sa.Integer(), nullable=False),
|
|
27
|
+
sa.Column("title", sa.String(), nullable=False),
|
|
28
|
+
sa.Column("entity_type", sa.String(), nullable=False),
|
|
29
|
+
sa.Column("entity_metadata", sa.JSON(), nullable=True),
|
|
30
|
+
sa.Column("content_type", sa.String(), nullable=False),
|
|
31
|
+
sa.Column("permalink", sa.String(), nullable=False),
|
|
32
|
+
sa.Column("file_path", sa.String(), nullable=False),
|
|
33
|
+
sa.Column("checksum", sa.String(), nullable=True),
|
|
34
|
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
|
35
|
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
|
36
|
+
sa.PrimaryKeyConstraint("id"),
|
|
37
|
+
sa.UniqueConstraint("permalink", name="uix_entity_permalink"),
|
|
38
|
+
)
|
|
39
|
+
op.create_index("ix_entity_created_at", "entity", ["created_at"], unique=False)
|
|
40
|
+
op.create_index(op.f("ix_entity_file_path"), "entity", ["file_path"], unique=True)
|
|
41
|
+
op.create_index(op.f("ix_entity_permalink"), "entity", ["permalink"], unique=True)
|
|
42
|
+
op.create_index("ix_entity_title", "entity", ["title"], unique=False)
|
|
43
|
+
op.create_index("ix_entity_type", "entity", ["entity_type"], unique=False)
|
|
44
|
+
op.create_index("ix_entity_updated_at", "entity", ["updated_at"], unique=False)
|
|
45
|
+
op.create_table(
|
|
46
|
+
"observation",
|
|
47
|
+
sa.Column("id", sa.Integer(), nullable=False),
|
|
48
|
+
sa.Column("entity_id", sa.Integer(), nullable=False),
|
|
49
|
+
sa.Column("content", sa.Text(), nullable=False),
|
|
50
|
+
sa.Column("category", sa.String(), nullable=False),
|
|
51
|
+
sa.Column("context", sa.Text(), nullable=True),
|
|
52
|
+
sa.Column("tags", sa.JSON(), server_default="[]", nullable=True),
|
|
53
|
+
sa.ForeignKeyConstraint(["entity_id"], ["entity.id"], ondelete="CASCADE"),
|
|
54
|
+
sa.PrimaryKeyConstraint("id"),
|
|
55
|
+
)
|
|
56
|
+
op.create_index("ix_observation_category", "observation", ["category"], unique=False)
|
|
57
|
+
op.create_index("ix_observation_entity_id", "observation", ["entity_id"], unique=False)
|
|
58
|
+
op.create_table(
|
|
59
|
+
"relation",
|
|
60
|
+
sa.Column("id", sa.Integer(), nullable=False),
|
|
61
|
+
sa.Column("from_id", sa.Integer(), nullable=False),
|
|
62
|
+
sa.Column("to_id", sa.Integer(), nullable=True),
|
|
63
|
+
sa.Column("to_name", sa.String(), nullable=False),
|
|
64
|
+
sa.Column("relation_type", sa.String(), nullable=False),
|
|
65
|
+
sa.Column("context", sa.Text(), nullable=True),
|
|
66
|
+
sa.ForeignKeyConstraint(["from_id"], ["entity.id"], ondelete="CASCADE"),
|
|
67
|
+
sa.ForeignKeyConstraint(["to_id"], ["entity.id"], ondelete="CASCADE"),
|
|
68
|
+
sa.PrimaryKeyConstraint("id"),
|
|
69
|
+
sa.UniqueConstraint("from_id", "to_id", "relation_type", name="uix_relation"),
|
|
70
|
+
)
|
|
71
|
+
op.create_index("ix_relation_from_id", "relation", ["from_id"], unique=False)
|
|
72
|
+
op.create_index("ix_relation_to_id", "relation", ["to_id"], unique=False)
|
|
73
|
+
op.create_index("ix_relation_type", "relation", ["relation_type"], unique=False)
|
|
74
|
+
# ### end Alembic commands ###
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def downgrade() -> None:
|
|
78
|
+
# ### commands auto generated by Alembic - please adjust! ###
|
|
79
|
+
op.drop_index("ix_relation_type", table_name="relation")
|
|
80
|
+
op.drop_index("ix_relation_to_id", table_name="relation")
|
|
81
|
+
op.drop_index("ix_relation_from_id", table_name="relation")
|
|
82
|
+
op.drop_table("relation")
|
|
83
|
+
op.drop_index("ix_observation_entity_id", table_name="observation")
|
|
84
|
+
op.drop_index("ix_observation_category", table_name="observation")
|
|
85
|
+
op.drop_table("observation")
|
|
86
|
+
op.drop_index("ix_entity_updated_at", table_name="entity")
|
|
87
|
+
op.drop_index("ix_entity_type", table_name="entity")
|
|
88
|
+
op.drop_index("ix_entity_title", table_name="entity")
|
|
89
|
+
op.drop_index(op.f("ix_entity_permalink"), table_name="entity")
|
|
90
|
+
op.drop_index(op.f("ix_entity_file_path"), table_name="entity")
|
|
91
|
+
op.drop_index("ix_entity_created_at", table_name="entity")
|
|
92
|
+
op.drop_table("entity")
|
|
93
|
+
# ### end Alembic commands ###
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""remove required from entity.permalink
|
|
2
|
+
|
|
3
|
+
Revision ID: 502b60eaa905
|
|
4
|
+
Revises: b3c3938bacdb
|
|
5
|
+
Create Date: 2025-02-24 13:33:09.790951
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Sequence, Union
|
|
10
|
+
|
|
11
|
+
from alembic import op
|
|
12
|
+
import sqlalchemy as sa
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# revision identifiers, used by Alembic.
|
|
16
|
+
revision: str = "502b60eaa905"
|
|
17
|
+
down_revision: Union[str, None] = "b3c3938bacdb"
|
|
18
|
+
branch_labels: Union[str, Sequence[str], None] = None
|
|
19
|
+
depends_on: Union[str, Sequence[str], None] = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def upgrade() -> None:
|
|
23
|
+
# ### commands auto generated by Alembic - please adjust! ###
|
|
24
|
+
with op.batch_alter_table("entity", schema=None) as batch_op:
|
|
25
|
+
batch_op.alter_column("permalink", existing_type=sa.VARCHAR(), nullable=True)
|
|
26
|
+
batch_op.drop_index("ix_entity_permalink")
|
|
27
|
+
batch_op.create_index(batch_op.f("ix_entity_permalink"), ["permalink"], unique=False)
|
|
28
|
+
batch_op.drop_constraint("uix_entity_permalink", type_="unique")
|
|
29
|
+
batch_op.create_index(
|
|
30
|
+
"uix_entity_permalink",
|
|
31
|
+
["permalink"],
|
|
32
|
+
unique=True,
|
|
33
|
+
sqlite_where=sa.text("content_type = 'text/markdown' AND permalink IS NOT NULL"),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
# ### end Alembic commands ###
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def downgrade() -> None:
|
|
40
|
+
# ### commands auto generated by Alembic - please adjust! ###
|
|
41
|
+
with op.batch_alter_table("entity", schema=None) as batch_op:
|
|
42
|
+
batch_op.drop_index(
|
|
43
|
+
"uix_entity_permalink",
|
|
44
|
+
sqlite_where=sa.text("content_type = 'text/markdown' AND permalink IS NOT NULL"),
|
|
45
|
+
)
|
|
46
|
+
batch_op.create_unique_constraint("uix_entity_permalink", ["permalink"])
|
|
47
|
+
batch_op.drop_index(batch_op.f("ix_entity_permalink"))
|
|
48
|
+
batch_op.create_index("ix_entity_permalink", ["permalink"], unique=1)
|
|
49
|
+
batch_op.alter_column("permalink", existing_type=sa.VARCHAR(), nullable=False)
|
|
50
|
+
|
|
51
|
+
# ### end Alembic commands ###
|