Skip to content

Commit 2e4d3a5

Browse files
author
bdavis
committed
added neo4j db name
1 parent 37ff6bc commit 2e4d3a5

4 files changed

Lines changed: 38 additions & 9 deletions

File tree

src/codegraphcontext/cli/config_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
CONFIG_FILE = CONFIG_DIR / ".env"
1717

1818
# Database credential keys (stored in same .env file but not managed as config)
19-
DATABASE_CREDENTIAL_KEYS = {"NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD"}
19+
DATABASE_CREDENTIAL_KEYS = {"NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD", "NEO4J_DATABASE"}
2020

2121
# Default configuration values
2222
DEFAULT_CONFIG = {

src/codegraphcontext/cli/main.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,11 @@ def _load_credentials():
288288
os.environ.get("NEO4J_PASSWORD")
289289
])
290290
if has_neo4j_creds:
291-
console.print("[cyan]Using database: Neo4j[/cyan]")
291+
neo4j_db = os.environ.get("NEO4J_DATABASE")
292+
if neo4j_db:
293+
console.print(f"[cyan]Using database: Neo4j (database: {neo4j_db})[/cyan]")
294+
else:
295+
console.print("[cyan]Using database: Neo4j[/cyan]")
292296
else:
293297
console.print("[yellow]⚠ DEFAULT_DATABASE=neo4j but credentials not found. Falling back to FalkorDB.[/yellow]")
294298
else:
@@ -700,7 +704,7 @@ def doctor():
700704

701705
if uri and username and password:
702706
console.print(f" [cyan]Testing Neo4j connection to {uri}...[/cyan]")
703-
is_connected, error_msg = DatabaseManager.test_connection(uri, username, password)
707+
is_connected, error_msg = DatabaseManager.test_connection(uri, username, password, database=os.environ.get("NEO4J_DATABASE"))
704708
if is_connected:
705709
console.print(f" [green]✓[/green] Neo4j connection successful")
706710
else:

src/codegraphcontext/cli/setup_wizard.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ def configure_mcp_client():
377377
if line and not line.startswith("#") and "=" in line:
378378
key, value = line.split("=", 1)
379379
key = key.strip()
380-
if key in ["NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD"]:
380+
if key in ["NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD", "NEO4J_DATABASE"]:
381381
env_vars[key] = value.strip()
382382
except Exception:
383383
pass

src/codegraphcontext/core/database.py

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,24 @@
1010

1111
from codegraphcontext.utils.debug_log import debug_log, info_logger, error_logger, warning_logger
1212

13+
class Neo4jDriverWrapper:
14+
"""
15+
A simple wrapper around the Neo4j Driver to inject a database name into session() calls.
16+
"""
17+
def __init__(self, driver: Driver, database: str = None):
18+
self._driver = driver
19+
self._database = database
20+
21+
def session(self, **kwargs):
22+
"""Proxy method to get a session from the underlying driver."""
23+
if self._database and 'database' not in kwargs:
24+
kwargs["database"] = self._database
25+
return self._driver.session(**kwargs)
26+
27+
def close(self):
28+
"""Proxy method to close the underlying driver."""
29+
self._driver.close()
30+
1331
class DatabaseManager:
1432
"""
1533
Manages the Neo4j database driver as a singleton to ensure only one
@@ -42,6 +60,7 @@ def __init__(self):
4260
self.neo4j_uri = os.getenv('NEO4J_URI')
4361
self.neo4j_username = os.getenv('NEO4J_USERNAME', 'neo4j')
4462
self.neo4j_password = os.getenv('NEO4J_PASSWORD')
63+
self.neo4j_database = os.getenv('NEO4J_DATABASE') # Optional, if not set, will use default database configured in Neo4j
4564
self._initialized = True
4665

4766
def get_driver(self) -> Driver:
@@ -53,7 +72,7 @@ def get_driver(self) -> Driver:
5372
ValueError: If Neo4j credentials are not set in environment variables.
5473
5574
Returns:
56-
The active Neo4j Driver instance.
75+
The a wrapper for Neo4j Driver instance.
5776
"""
5877
if self._driver is None:
5978
with self._lock:
@@ -100,7 +119,7 @@ def get_driver(self) -> Driver:
100119
self._driver.close()
101120
self._driver = None
102121
raise
103-
return self._driver
122+
return Neo4jDriverWrapper(self._driver, database=self.neo4j_database)
104123

105124
def close_driver(self):
106125
"""Closes the Neo4j driver connection if it exists."""
@@ -116,7 +135,10 @@ def is_connected(self) -> bool:
116135
if self._driver is None:
117136
return False
118137
try:
119-
with self._driver.session() as session:
138+
session_kwargs = {}
139+
if self.neo4j_database:
140+
session_kwargs['database'] = self.neo4j_database
141+
with self._driver.session(**session_kwargs) as session:
120142
session.run("RETURN 1").consume()
121143
return True
122144
except Exception:
@@ -163,7 +185,7 @@ def validate_config(uri: str, username: str, password: str) -> Tuple[bool, Optio
163185
return True, None
164186

165187
@staticmethod
166-
def test_connection(uri: str, username: str, password: str) -> Tuple[bool, Optional[str]]:
188+
def test_connection(uri: str, username: str, password: str, database: str=None) -> Tuple[bool, Optional[str]]:
167189
"""
168190
Tests the Neo4j database connection.
169191
@@ -206,7 +228,10 @@ def test_connection(uri: str, username: str, password: str) -> Tuple[bool, Optio
206228
# Now test Neo4j authentication
207229
driver = GraphDatabase.driver(uri, auth=(username, password))
208230

209-
with driver.session() as session:
231+
session_kwargs = {}
232+
if database:
233+
session_kwargs['database'] = database # Pass database to session if provided
234+
with driver.session(**session_kwargs) as session:
210235
result = session.run("RETURN 'Connection successful' as status")
211236
result.single()
212237

0 commit comments

Comments
 (0)