Series: Building Quorentra CRM from Zero — A Modular, ChatGPT-Native AI CRM
Connecting FastAPI to PostgreSQL with SQLAlchemy, environment-based configuration, database sessions, Alembic migrations, and database-aware health monitoring.

1. Introduction
In Part 4, Quorentra became running software.
We created:
Browser │ ▼Uvicorn │ ▼FastAPI │ ▼Quorentra API
The application can now respond to:
GET /api/v1/health
But Quorentra still has no memory.
If we restart the application, there is no persistent CRM state because we have not yet connected a database.
That changes in Part 5.
We will introduce PostgreSQL as Quorentra’s authoritative system of record.
Our architecture will become:
FastAPI │ ▼Application │ ▼SQLAlchemy │ ▼Psycopg │ ▼PostgreSQL
We will also introduce Alembic so that database structure evolves through controlled, versioned migrations.
By the end of this article:
GET /api/v1/health
will verify not only that FastAPI is running, but also that PostgreSQL is reachable.
This gives us:
Quorentra 0.0.3 — API + Persistent Database Foundation
2. Why PostgreSQL?
A CRM is fundamentally a transactional business application.
Quorentra will eventually store:
- organizations;
- users;
- memberships;
- companies;
- contacts;
- opportunities;
- pipeline stages;
- activities;
- tasks;
- notes;
- documents;
- workflow definitions;
- audit events;
- AI metadata.
These entities have strong relationships.
For example:
Organization │ ├── Users ├── Companies │ │ │ ├── Contacts │ └── Opportunities │ ├── Tasks └── Activities
A relational database is therefore a natural foundation.
PostgreSQL also gives us a major advantage later in the series.
With pgvector, the same database platform can support vector embeddings for semantic retrieval.
Our MVP can therefore use:
PostgreSQL │ ├── CRM relational data ├── transactions ├── metadata ├── audit information └── vector embeddings
without immediately introducing another database technology.
3. The Persistence Architecture
Before writing code, define the boundary.
We do not want FastAPI routes executing SQL directly.
The eventual architecture will be:
FastAPI Router │ ▼Application Service │ ▼Repository │ ▼SQLAlchemy │ ▼PostgreSQL
Not:
FastAPI Router │ ▼Raw SQL everywhere
In this article, the application-service and repository layers do not yet have meaningful CRM entities to operate on.
But the database infrastructure we create must support those layers cleanly.
4. Starting Checkpoint
Part 5 assumes the Part 4 backend structure:
backend/│├── .venv/│├── app/│ ├── __init__.py│ ││ ├── api/│ │ └── v1/│ │ ├── __init__.py│ │ ├── health.py│ │ ├── router.py│ │ └── schemas.py│ ││ ├── core/│ │ ├── __init__.py│ │ └── constants.py│ ││ └── main.py│├── tests/│ └── api/│ └── test_health.py│├── requirements.txt├── requirements-dev.txt└── README.md
Open PowerShell and move to:
quorentra\backend
Activate the environment:
.\.venv\Scripts\Activate.ps1
Verify:
python --version
and:
where.exe python
The first interpreter should point to:
backend\.venv\Scripts\python.exe
5. Verify PostgreSQL
Before integrating Python, verify that PostgreSQL itself is installed and running.
If the PostgreSQL command-line tools are available:
psql --version
You should receive output similar to:
psql (PostgreSQL) 17.x
If Windows reports:
'psql' is not recognized
that does not necessarily mean PostgreSQL is missing.
It often means the PostgreSQL bin directory is not in the Windows PATH.
For PostgreSQL 17, the default installation directory is commonly:
C:\Program Files\PostgreSQL\17\bin
You can either add that directory to PATH or use pgAdmin for database administration.
For this series, either approach is acceptable.
6. Create the Quorentra Database
Open pgAdmin.
Connect to your local PostgreSQL server.
Create a database named:
quorentra
You can do this through the pgAdmin interface:
Servers ↓PostgreSQL ↓Databases ↓Create ↓Database
Set:
Database: quorentra
and choose the appropriate database owner.
Alternatively, using psql:
CREATE DATABASE quorentra;
The database now exists.
7. Do Not Create CRM Tables Manually
It may be tempting to open pgAdmin and create tables for:
userscompaniescontactsopportunities
Do not do that.
Quorentra’s schema will be managed through:
SQLAlchemy models +Alembic migrations
This gives us a version-controlled database history.
The database itself should not become an undocumented collection of manually created tables.
8. Install SQLAlchemy
From:
quorentra\backend
run:
python -m pip install sqlalchemy
Verify:
python -m pip show sqlalchemy
SQLAlchemy will provide our Python database abstraction.
The architecture becomes:
Python │ ▼SQLAlchemy │ ▼Database Driver │ ▼PostgreSQL
9. Install Psycopg
SQLAlchemy does not communicate directly with PostgreSQL.
It uses a database driver.
For Quorentra, we will use Psycopg 3.
Install:
python -m pip install "psycopg[binary]"
Verify:
python -m pip show psycopg
Our connection stack is now:
Quorentra │ ▼SQLAlchemy │ ▼Psycopg │ ▼PostgreSQL
10. Install Pydantic Settings
We now have our first real environment-driven configuration requirement.
Install:
python -m pip install pydantic-settings
This will allow us to load configuration from environment variables and .env.
Verify:
python -m pip show pydantic-settings
11. Install Alembic
Install the migration framework:
python -m pip install alembic
Verify:
python -m alembic --version
Alembic will allow the database schema to evolve through migrations such as:
001 create foundation002 create organizations003 create users004 create memberships005 create companies006 create contacts...
The exact revisions will use Alembic-generated revision identifiers, but conceptually this is how our database history will evolve.
12. Update Runtime Dependencies
Update:
backend/requirements.txt
to contain:
fastapiuvicorn[standard]sqlalchemypsycopg[binary]pydantic-settingsalembic
Keep:
backend/requirements-dev.txt
as:
-r requirements.txtpytesthttpx
A new development environment can therefore be created with:
python -m pip install -r requirements-dev.txt
13. Introduce the Configuration Layer
In Part 4, we deliberately postponed a full configuration system.
Now we need one.
Create:
app/core/config.py
From PowerShell:
New-Item app\core\config.py -ItemType File
Add:
from functools import lru_cachefrom pydantic_settings import BaseSettings, SettingsConfigDictclass Settings(BaseSettings): app_env: str = "development" database_url: str model_config = SettingsConfigDict( env_file="../.env", env_file_encoding="utf-8", case_sensitive=False, extra="ignore", )lru_cachedef get_settings() -> Settings: return Settings()
This creates our first application configuration object.
14. Why ../.env?
Remember our repository structure:
quorentra/├── .env└── backend/ └── app/
Our canonical backend commands run from:
quorentra/backend
The repository-level .env is therefore one directory above:
../.env
That is why the settings configuration uses:
env_file="../.env"
This convention assumes backend commands are run from backend, as established earlier in the series.
Later, we can make configuration-path resolution more sophisticated if deployment requirements justify it.
For the MVP, consistency is more important than abstraction.
15. Configure the Database URL
Open the repository-level:
.env
Add:
DATABASE_URL=postgresql+psycopg://quorentra_user:your_password@localhost:5432/quorentra
Replace:
quorentra_user
and:
your_password
with your actual PostgreSQL credentials.
If you are using the default PostgreSQL administrative account during local development, the URL might temporarily resemble:
DATABASE_URL=postgresql+psycopg://postgres:your_password@localhost:5432/quorentra
Do not copy this literally without changing the password.
16. Update .env.example
The committed:
.env.example
must not contain the real password.
Add:
DATABASE_URL=postgresql+psycopg://quorentra_user:change_me@localhost:5432/quorentra
This tells future developers what configuration is required without exposing credentials.
17. Prefer a Dedicated Database User
For local experimentation, using the postgres account works.
But it is better to create a dedicated Quorentra database user.
For example:
CREATE USER quorentra_user WITH PASSWORD 'your_secure_password';
Then grant access:
GRANT ALL PRIVILEGES ON DATABASE quorentra TO quorentra_user;
Connect to the quorentra database and grant schema privileges if required:
GRANT USAGE, CREATE ON SCHEMA public TO quorentra_user;
This separates the application identity from the PostgreSQL superuser.
That is a healthier default.
18. Never Commit the Real Password
Run:
git status
You should not see:
.env
because Part 3 added it to .gitignore.
If .env appears in Git status, stop.
Do not commit.
Do not push.
Correct .gitignore first.
Secrets should never become part of repository history.
19. Verify Configuration Loading
From:
quorentra/backend
run:
python -c "from app.core.config import get_settings; print(get_settings().app_env)"
Expected:
development
Now verify that the database URL loads without printing the actual secret:
python -c "from app.core.config import get_settings; print(bool(get_settings().database_url))"
Expected:
True
Do not routinely print the full database URL because it contains credentials.
20. Create the Database Package
Create:
app/db/
From PowerShell:
mkdir app\dbNew-Item app\db\__init__.py -ItemType File
Our application structure now includes:
app/├── api/├── core/├── db/└── main.py
This db package will contain infrastructure shared across Quorentra modules.
21. Create the SQLAlchemy Engine
Create:
app/db/session.py
Run:
New-Item app\db\session.py -ItemType File
Add:
from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom app.core.config import get_settingssettings = get_settings()engine = create_engine( settings.database_url, pool_pre_ping=True,)SessionLocal = sessionmaker( bind=engine, autoflush=False, expire_on_commit=False,)
This creates the central SQLAlchemy engine and session factory.
22. What Is the SQLAlchemy Engine?
The engine manages connectivity between SQLAlchemy and PostgreSQL.
Conceptually:
Application │ ▼SQLAlchemy Engine │ ▼Connection Pool │ ▼Psycopg │ ▼PostgreSQL
The engine is not a single permanent database connection.
It manages database connections for the application.
23. Why pool_pre_ping=True?
Database connections can become stale.
For example:
- PostgreSQL restarts;
- a network connection drops;
- an idle connection expires.
With:
pool_pre_ping=True
SQLAlchemy checks a pooled connection before handing it to the application.
For a long-running web application, this is a useful resilience measure.
24. What Is SessionLocal?
The SQLAlchemy Session represents a unit of interaction with the database.
Later, application services and repositories will use sessions to:
- query records;
- add entities;
- update entities;
- commit transactions;
- roll back failed operations.
We want each request to have a controlled session lifecycle.
Conceptually:
HTTP Request │ ▼Open Session │ ▼Application Work │ ▼Commit / Rollback │ ▼Close Session
25. Create the Database Dependency
Create:
app/db/dependencies.py
Run:
New-Item app\db\dependencies.py -ItemType File
Add:
from collections.abc import Generatorfrom sqlalchemy.orm import Sessionfrom app.db.session import SessionLocaldef get_db() -> Generator[Session, None, None]: db = SessionLocal() try: yield db finally: db.close()
This function will later be used by FastAPI dependency injection.
For example:
db: Session = Depends(get_db)
The session is created for the operation and closed afterward.
26. Why Centralize Database Sessions?
We do not want routes doing this independently:
session = SessionLocal()
and forgetting to close the session.
Instead:
FastAPI │ ▼get_db() │ ▼Session
provides a consistent lifecycle.
Later, service and repository architecture will build on this foundation.
27. Test the Database Connection
Before adding the database to the API health endpoint, test it independently.
Create:
scripts/test_connection.py
Our repository already has the scripts directory from Part 3.
Add:
from sqlalchemy import textfrom app.db.session import enginedef main() -> None: with engine.connect() as connection: result = connection.execute( text("SELECT 1") ) print( "Database connection successful:", result.scalar_one(), )if __name__ == "__main__": main()
There is one important detail.
Our scripts directory lives at:
quorentra/scripts
while the Python application lives under:
quorentra/backend/app
Running this script directly from the repository root would therefore not automatically expose backend as the Python import root.
We should not solve this with sys.path hacks.
Instead, use Python’s module context deliberately or place backend-specific scripts inside the backend workspace.
For this first database test, the cleanest option is to create:
backend/scripts/
instead.
28. Create Backend-Specific Scripts
From:
quorentra/backend
run:
mkdir scriptsNew-Item scripts\test_connection.py -ItemType File
Place the database test there:
from sqlalchemy import textfrom app.db.session import enginedef main() -> None: with engine.connect() as connection: result = connection.execute( text("SELECT 1") ) print( "Database connection successful:", result.scalar_one(), )if __name__ == "__main__": main()
The structure becomes:
backend/├── app/├── scripts/│ └── test_connection.py└── tests/
This script belongs specifically to the backend and should execute within the backend Python context.
29. Run the Connection Test Correctly
A subtle Python import issue is worth addressing here.
If you run:
python scripts/test_connection.py
Python may treat:
backend/scripts
as the initial script path rather than the backend directory as the package root.
A cleaner approach is to make scripts a package.
Create:
New-Item scripts\__init__.py -ItemType File
Then run:
python -m scripts.test_connection
from:
quorentra/backend
Expected:
Database connection successful: 1
This verifies:
Python ↓SQLAlchemy ↓Psycopg ↓PostgreSQL
before FastAPI becomes involved.
30. Troubleshooting the Connection
If you receive an authentication error, check:
usernamepasswordhostportdatabase name
inside DATABASE_URL.
If PostgreSQL is using the default local port:
5432
the URL should contain:
localhost:5432
If you receive:
database "quorentra" does not exist
create the database first.
If you receive:
password authentication failed
verify the PostgreSQL credentials independently through pgAdmin or psql.
31. Create the SQLAlchemy Base
Our future ORM models need a common declarative base.
Create:
app/db/base.py
Add:
from sqlalchemy.orm import DeclarativeBaseclass Base(DeclarativeBase): pass
Future models will inherit from:
Base
For example:
class Company(Base): ...
We deliberately do not create Company yet.
That belongs to a later vertical slice.
32. Why SQLAlchemy 2.x Style?
Older SQLAlchemy tutorials often use:
declarative_base()
Modern SQLAlchemy supports:
class Base(DeclarativeBase): pass
Quorentra will use the SQLAlchemy 2.x style throughout the series.
This gives us a modern foundation rather than carrying older patterns into a new project.
33. Initialize Alembic
From:
quorentra/backend
run:
python -m alembic init alembic
Alembic creates:
backend/├── alembic/│ ├── versions/│ ├── env.py│ ├── README│ └── script.py.mako│└── alembic.ini
This becomes Quorentra’s schema migration infrastructure.
34. Do Not Store the Database Password in alembic.ini
Alembic generates a setting similar to:
sqlalchemy.url = driver://user:pass@localhost/dbname
We do not want a real database URL stored there.
Instead, Alembic should use Quorentra’s existing settings layer.
That gives us one authoritative configuration path.
35. Configure Alembic
Open:
alembic/env.py
Near the imports, add:
from app.core.config import get_settingsfrom app.db.base import Base
Then define:
settings = get_settings()
Set:
config.set_main_option( "sqlalchemy.url", settings.database_url,)
Then replace:
target_metadata = None
with:
target_metadata = Base.metadata
The important parts should conceptually look like:
from alembic import contextfrom sqlalchemy import engine_from_config, poolfrom app.core.config import get_settingsfrom app.db.base import Baseconfig = context.configsettings = get_settings()config.set_main_option( "sqlalchemy.url", settings.database_url,)target_metadata = Base.metadata
Keep the rest of Alembic’s generated migration functions unless there is a reason to modify them.
36. Why Base.metadata Matters
Alembic can compare:
SQLAlchemy model metadata
against:
current database schema
and generate migration operations.
Conceptually:
SQLAlchemy Models │ ▼Base.metadata │ ▼Alembic │ ▼Migration │ ▼PostgreSQL
We do not yet have application models, so the first migration will intentionally be small.
37. Create the First Migration
Run:
python -m alembic revision -m "initialize database foundation"
Alembic creates a revision inside:
alembic/versions/
The migration will not create CRM tables yet.
That is fine.
Its purpose is to establish the migration chain.
38. Apply the Migration
Run:
python -m alembic upgrade head
If successful, Alembic creates its version tracking table:
alembic_version
inside PostgreSQL.
You can verify this in pgAdmin.
Navigate to:
quorentra ↓Schemas ↓public ↓Tables
You should see:
alembic_version
Quorentra’s database is now migration-managed.
39. Check the Current Migration
Run:
python -m alembic current
You should see the current revision.
Also run:
python -m alembic history
This displays the migration chain.
It is currently tiny.
Later it will become the history of Quorentra’s data model.
40. Database-Aware Health Monitoring
Our current health endpoint returns:
{ "status": "healthy", "service": "quorentra-api", "version": "0.0.2"}
But this only proves that FastAPI can respond.
For a CRM, the database is essential.
If PostgreSQL is unavailable, the application is not fully healthy.
We therefore want:
GET /api/v1/health │ ▼FastAPI │ ▼PostgreSQL Check
41. Update the Health Schema
Open:
app/api/v1/schemas.py
Change the health response to:
from pydantic import BaseModelclass HealthResponse(BaseModel): status: str service: str version: str database: str
The response contract now includes database state.
42. Update the Health Endpoint
Open:
app/api/v1/health.py
Update it:
from fastapi import APIRouter, Dependsfrom sqlalchemy import textfrom sqlalchemy.orm import Sessionfrom app.api.v1.schemas import HealthResponsefrom app.core.constants import APP_VERSIONfrom app.db.dependencies import get_dbrouter = APIRouter()router.get( "/health", response_model=HealthResponse,)async def health_check( db: Session = Depends(get_db),) -> HealthResponse: db.execute(text("SELECT 1")) return HealthResponse( status="healthy", service="quorentra-api", version=APP_VERSION, database="connected", )
The endpoint now performs a real database query.
43. Run Quorentra
From:
quorentra/backend
run:
python -m uvicorn app.main:app --reload
Open:
http://127.0.0.1:8000/api/v1/health
Expected:
{ "status": "healthy", "service": "quorentra-api", "version": "0.0.2", "database": "connected"}
We have now reached:
Browser │ ▼FastAPI │ ▼SQLAlchemy Session │ ▼PostgreSQL
44. What Happens if PostgreSQL Stops?
Stop the PostgreSQL service temporarily and call the endpoint again.
The request should fail because:
db.execute(text("SELECT 1"))
cannot reach PostgreSQL.
This demonstrates an important distinction.
Previously:
FastAPI running = healthy
Now:
FastAPI running +Database reachable =Application health
Later we will distinguish more carefully between liveness and readiness.
For the current MVP stage, this database-aware health check is sufficient.
45. Update the Automated Health Test
Our Part 4 test assumes no database.
The endpoint now requires one.
For this article, we want to verify the real integration.
Update:
tests/api/test_health.py
to expect:
from fastapi.testclient import TestClientfrom app.main import appclient = TestClient(app)def test_health_check() -> None: response = client.get("/api/v1/health") assert response.status_code == 200 data = response.json() assert data["status"] == "healthy" assert data["service"] == "quorentra-api" assert data["database"] == "connected"
The version does not need to be hard-coded into every test unless the version itself is what we are testing.
46. Integration Test Versus Unit Test
This health test now depends on PostgreSQL.
Therefore it is no longer a pure isolated API test.
It is effectively an integration test.
That distinction will matter as our test suite grows.
Eventually we will have:
tests/├── unit/├── integration/└── api/
For now, the small test suite does not justify extensive restructuring.
But we should understand what the test actually proves:
FastAPI +Dependency Injection +SQLAlchemy +Psycopg +PostgreSQL
all work together.
That is valuable.
47. Run the Test
Make sure PostgreSQL is running.
Stop Uvicorn if necessary.
Run:
python -m pytest
Expected:
1 passed
If the test fails with a database connection error, debug the database configuration before continuing.
48. Add a Dedicated Database Health Function
The health endpoint currently knows how to query the database directly.
That is acceptable for one line, but we can make the responsibility clearer.
Create:
app/db/health.py
Add:
from sqlalchemy import textfrom sqlalchemy.orm import Sessiondef check_database_connection( db: Session,) -> bool: result = db.execute( text("SELECT 1") ) return result.scalar_one() == 1
Now update:
app/api/v1/health.py
to:
from fastapi import APIRouter, Dependsfrom sqlalchemy.orm import Sessionfrom app.api.v1.schemas import HealthResponsefrom app.core.constants import APP_VERSIONfrom app.db.dependencies import get_dbfrom app.db.health import check_database_connectionrouter = APIRouter()router.get( "/health", response_model=HealthResponse,)async def health_check( db: Session = Depends(get_db),) -> HealthResponse: database_connected = check_database_connection(db) return HealthResponse( status="healthy", service="quorentra-api", version=APP_VERSION, database=( "connected" if database_connected else "unavailable" ), )
The route now delegates database-specific behavior to the database infrastructure layer.
49. Why This Separation Matters
Today the check is:
SELECT 1
Later health monitoring may need to inspect:
- database connectivity;
- migration state;
- Redis;
- workflow workers;
- AI provider availability;
- object storage;
- MCP connectivity.
We do not want the HTTP route to become a large infrastructure diagnostics implementation.
The route should coordinate.
Infrastructure components should know how to check themselves.
50. Version Quorentra 0.0.3
Update:
app/core/constants.py
from:
APP_VERSION = "0.0.2"
to:
APP_VERSION = "0.0.3"
Now:
GET /api/v1/health
should return:
{ "status": "healthy", "service": "quorentra-api", "version": "0.0.3", "database": "connected"}
This is the correct milestone for the persistent database foundation.
51. Current Backend Structure
At the end of Part 5, the backend should resemble:
backend/│├── .venv/│├── alembic/│ ├── versions/│ ├── env.py│ ├── README│ └── script.py.mako│├── app/│ ├── __init__.py│ ││ ├── api/│ │ ├── __init__.py│ │ └── v1/│ │ ├── __init__.py│ │ ├── health.py│ │ ├── router.py│ │ └── schemas.py│ ││ ├── core/│ │ ├── __init__.py│ │ ├── config.py│ │ └── constants.py│ ││ ├── db/│ │ ├── __init__.py│ │ ├── base.py│ │ ├── dependencies.py│ │ ├── health.py│ │ └── session.py│ ││ └── main.py│├── scripts/│ ├── __init__.py│ └── test_connection.py│├── tests/│ ├── __init__.py│ └── api/│ ├── __init__.py│ └── test_health.py│├── alembic.ini├── requirements.txt├── requirements-dev.txt└── README.md
Our repository-level configuration contains:
quorentra/├── .env└── .env.example
with .env excluded from Git.
52. The Persistence Foundation We Have Built
The architecture now looks like:
FastAPI
│
▼
API Router
│
▼
DB Dependency
│
▼
SQLAlchemy Session
│
▼
Session Factory
│
▼
SQLAlchemy Engine
│
▼
Psycopg
│
▼
PostgreSQL
Alongside this runtime architecture, we have:
SQLAlchemy Models │ ▼Base.metadata │ ▼Alembic │ ▼Migrations │ ▼PostgreSQL Schema
We now have both:
runtime persistence
and:
schema lifecycle management.
53. A Critical Rule Going Forward
From this point onward:
Database schema changes are made through SQLAlchemy models and Alembic migrations—not manually through pgAdmin.
pgAdmin remains extremely useful for:
- inspecting tables;
- running diagnostic queries;
- viewing records;
- managing PostgreSQL;
- installing extensions;
- troubleshooting.
But it is not our schema-authoring system.
The schema belongs to the application repository.
54. Another Critical Rule: No SQL in Routers
As we begin building CRM modules, avoid this pattern:
router.get("/companies")def list_companies(db: Session = Depends(get_db)): return db.execute( text("SELECT * FROM companies") )
That would couple the API directly to persistence.
Instead, our target architecture remains:
Router │ ▼Service │ ▼Repository │ ▼SQLAlchemy
The health endpoint is an infrastructure exception because its purpose is specifically to verify infrastructure.
Business endpoints will follow the modular architecture.
55. What About Async SQLAlchemy?
FastAPI supports asynchronous database access.
We could use:
AsyncEngineAsyncSessionasyncpg
instead.
For the initial Quorentra MVP, we are deliberately using synchronous SQLAlchemy sessions.
Why?
Because they provide:
- simpler debugging;
- simpler tutorials;
- mature PostgreSQL support;
- fewer moving parts;
- perfectly adequate performance for the initial CRM workload.
FastAPI can work with synchronous database operations.
If real workload measurements later demonstrate that async database access provides meaningful value, the persistence layer can evolve.
We should not adopt asynchronous complexity merely because FastAPI supports it.
56. What About Docker PostgreSQL?
We could also run PostgreSQL immediately through Docker Compose.
That will become useful for reproducible environments.
But our current objective is to understand and verify the application/database relationship directly.
The progression is intentional:
Local PostgreSQL ↓Application Integration ↓Migrations ↓Working CRM ↓Containerized Environment
Later, Docker Compose will make the entire stack reproducible.
57. What About pgvector?
Quorentra will eventually use pgvector for:
- document embeddings;
- CRM knowledge retrieval;
- semantic search;
- RAG;
- AI context building.
But we do not need vector storage yet.
The current system contains no documents and no embedding pipeline.
We will therefore install and enable pgvector when the knowledge architecture reaches that stage.
Again:
Introduce infrastructure when a working feature requires it.
58. Run the Complete Verification Sequence
Before committing Part 5, run the complete checkpoint.
First verify configuration:
python -c "from app.core.config import get_settings; print(get_settings().app_env)"
Expected:
development
Verify database connectivity:
python -m scripts.test_connection
Expected:
Database connection successful: 1
Verify Alembic:
python -m alembic current
A revision should be reported.
Run tests:
python -m pytest
Expected:
1 passed
Start the application:
python -m uvicorn app.main:app --reload
Open:
http://127.0.0.1:8000/api/v1/health
Expected:
{ "status": "healthy", "service": "quorentra-api", "version": "0.0.3", "database": "connected"}
Only after all of these succeed should we consider Part 5 complete.
59. Troubleshooting: psql Not Found
If:
psql --version
fails but PostgreSQL is installed, check:
C:\Program Files\PostgreSQL\17\bin
You can run:
& "C:\Program Files\PostgreSQL\17\bin\psql.exe" --version
If that works, PostgreSQL is installed but its bin directory is missing from PATH.
You can continue using pgAdmin while correcting PATH separately.
60. Troubleshooting: No module named app
If:
python -m scripts.test_connection
reports:
ModuleNotFoundError: No module named 'app'
check:
Get-Location
You should be in:
quorentra\backend
Then:
python -c "import app; print(app)"
should succeed.
Do not add arbitrary sys.path manipulation.
61. Troubleshooting: Password Authentication Failed
An error similar to:
password authentication failed for user
means PostgreSQL was reached but rejected the credentials.
Check:
DATABASE_URL
inside .env.
Verify the same username/password through pgAdmin or psql.
Also remember that special characters in passwords may need URL encoding when embedded inside a database URL.
62. Troubleshooting: Connection Refused
If you receive a connection-refused error, check that PostgreSQL is running.
On Windows, open:
Services
and locate a service similar to:
postgresql-x64-17
Verify that its state is:
Running
Also verify that PostgreSQL is listening on the expected port, usually:
5432
63. Troubleshooting: Alembic Cannot Find app
Run Alembic from:
quorentra/backend
using:
python -m alembic current
The backend directory is the Python package root for this project.
This is the same convention we use for Uvicorn and pytest.
64. Troubleshooting: Permission Denied Creating Tables
If the dedicated quorentra_user can connect but Alembic cannot create its version table, the user may lack schema permissions.
Connect as an administrative user and grant:
GRANT USAGE, CREATE ON SCHEMA public TO quorentra_user;
Then retry:
python -m alembic upgrade head
65. Git Checkpoint
Stop Uvicorn:
Ctrl + C
Return to the repository root:
cd ..
Run:
git status
Carefully verify that:
.env
is not listed.
The migration file under:
backend/alembic/versions/
should be included.
Stage:
git add .
Review again:
git status
Then commit:
git commit -m "feat: add PostgreSQL persistence foundation"
Finally:
git status
Expected:
nothing to commit, working tree clean
66. Quorentra 0.0.3
We can now describe the system as:
Quorentra 0.0.3
Current capability:
Repository ✓Python environment ✓FastAPI ✓API routing ✓Health API ✓Pydantic contracts ✓PostgreSQL ✓SQLAlchemy ✓Psycopg ✓DB sessions ✓Configuration ✓Alembic ✓Migration chain ✓DB health check ✓Automated test ✓React -Authentication -Organizations -Users -Companies -Contacts -Opportunities -MCP -ChatGPT -AI -
The application still does very little from a user’s perspective.
Architecturally, however, something important has changed.
Quorentra now has durable infrastructure.
67. Acceptance Criteria
Part 5 is complete when:
✓ PostgreSQL database exists✓ Application database user can connect✓ SQLAlchemy is installed✓ Psycopg is installed✓ Pydantic Settings is installed✓ Alembic is installed✓ DATABASE_URL comes from environment configuration✓ Real credentials are excluded from Git✓ SQLAlchemy engine exists✓ Session factory exists✓ FastAPI database dependency exists✓ SQLAlchemy declarative Base exists✓ Database connection test succeeds✓ Alembic is initialized✓ First migration exists✓ alembic upgrade head succeeds✓ alembic_version exists in PostgreSQL✓ Health endpoint queries PostgreSQL✓ Health endpoint reports database connected✓ Automated health test succeeds✓ Quorentra reports version 0.0.3✓ Git checkpoint exists
Most importantly:
Do not continue until PostgreSQL connectivity and Alembic migrations both work reliably.
Every CRM module that follows depends on this foundation.
68. What We Deliberately Did Not Build
We still have no actual CRM tables.
There is no:
organizationusercompanycontactopportunitytask
table yet.
That is intentional.
Part 5 created the persistence mechanism.
The next articles will start placing actual domain models on top of it.
We have moved from:
FastAPI
to:
FastAPI │ ▼SQLAlchemy │ ▼PostgreSQL
The next architectural milestone is the first real domain state.
69. Why Organizations Must Come Before Companies
It might be tempting to make our first CRM table:
companies
After all, companies are central to a CRM.
But Quorentra is designed as a multi-tenant system.
Therefore every future CRM record needs an ownership boundary.
Conceptually:
Organization │ ├── Company ├── Contact ├── Opportunity ├── Activity └── Task
Before we create companies, we need to establish:
OrganizationUserMembership
because those entities define:
Who is using Quorentra, and which tenant owns the data?
This is the correct foundation for everything that follows.
70. The Next Architecture
Our current system is:
FastAPI │ ▼SQLAlchemy │ ▼PostgreSQL
The next step will introduce:
Organization
│
▼
User ──────────── Membership
│
▼
Tenant Context
That gives us the foundation for true multi-tenant CRM data.
Later:
Organization │ ├── Companies ├── Contacts ├── Opportunities ├── Activities └── Tasks
Every CRM module can then inherit the same tenant boundary.
71. Development Progress
Our MVO path now looks like:
Repository ✓ │FastAPI ✓ │PostgreSQL ✓ │Identity / Tenant Foundation ↓React ↓Companies ↓Contacts ↓Opportunities ↓Activities ↓Tasks ↓Basic Dashboard ↓MVO
Only after the basic CRM is operational do we need to move deeply into:
MCP ↓ChatGPT ↓Knowledge ↓AI Context ↓AI Actions
This sequencing is important.
ChatGPT should be connected to a functioning CRM platform—not used to compensate for an unfinished domain model.
72. Next Article
In Part 6, we will build the first real Quorentra domain foundation:
Organizations, Users, and Memberships.
We will introduce the first production SQLAlchemy models and migration.
The database will evolve from:
PostgreSQL │ └── alembic_version
to:
PostgreSQL │ ├── alembic_version │ ├── organizations │ ├── users │ └── memberships
We will establish:
- UUID primary keys;
- timestamps;
- organization identity;
- user identity;
- membership relationships;
- tenant ownership;
- initial role representation;
- SQLAlchemy relationships;
- database constraints;
- migration generation;
- migration inspection;
- persistence tests.
This is a major architectural step because it creates the ownership boundary for every CRM record that follows.
Once this foundation exists, Quorentra can safely begin adding actual CRM modules.
The progression is now:
Part 3Repository │ ▼Part 4FastAPI │ ▼Part 5PostgreSQL │ ▼Part 6Organizations + Users + Memberships │ ▼CRM Modules
Quorentra now has an API.
Quorentra now has persistent storage.
Next, Quorentra gets its first real domain model.