# SQLAlchemy

<https://auth0.com/blog/sqlalchemy-orm-tutorial-for-python-developers/>

## 1. Engines: db connection

Engines = manage **Pools** and **Dialects**.

```python
engine = create_engine('postgresql://usr:pass@localhost:5432/sqlalchemy')
```

creating an engine does ***not*** connect to the database instantly

### Pool = to improve performance.

1. Opening and maintaining new connections is expensive
2. Easier management of # of connections simultaneously.

### Dialects = adopt to different DB.

## 2. Session vs Connection

session = exec ORM sql query

connection = exec RAW sql query

## 3. Sessions: sync orm & db

1. modifications ORM tracked & applied to DB.
2. guarantee the database consistency.

```python
# create a configured "Session" class
Session = sessionmaker(bind=engine)

# create a Session
session = Session()
```

## 4. Base: base class for all models

```python
Base = declarative_base()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huang-jason.gitbook.io/python/sqlalchemy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
