Skip to content

Execute a BlendSQL Query

BlendSQL Class

Core BlendSQL class that provides high level interface for executing BlendSQL queries.

Parameters:

Name Type Description Default
db Union[DataFrame, dict, str, Database]

Database to connect to. Can be:

  • pandas DataFrame or dict of DataFrames

  • Path to SQLite database file

  • PostgreSQL connection string

  • Database object

None
model Optional[Model]

Model instance to use for LLM operations. Can also be provided during query execution.

None
ingredients Optional[Collection[Type[Ingredient]]]

Collection of ingredients to make available for queries. Can also be provided during query execution.

list()
verbose bool

Whether to output debug logging information. Defaults to False.

False
infer_gen_constraints bool

Whether to automatically infer constraints for LLM generation based on query context. Defaults to True.

True
table_to_title Optional[Dict[str, str]]

Optional mapping from table names to descriptive titles, useful for datasets where table titles contain metadata.

None
Source code in blendsql/blendsql.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
@dataclass
class BlendSQL:
    """Core `BlendSQL` class that provides high level interface for executing BlendSQL queries.

    Args:
        db (Union[pd.DataFrame, dict, str, Database]): Database to connect to. Can be:

            - pandas DataFrame or dict of DataFrames

            - Path to SQLite database file

            - PostgreSQL connection string

            - `Database` object
        model (Optional[Model]): Model instance to use for LLM operations. Can also be
            provided during query execution.
        ingredients (Optional[Collection[Type[Ingredient]]]): Collection of ingredients to
            make available for queries. Can also be
                provided during query execution.
        verbose (bool): Whether to output debug logging information. Defaults to False.
        infer_gen_constraints (bool): Whether to automatically infer constraints for
            LLM generation based on query context. Defaults to True.
        table_to_title (Optional[Dict[str, str]]): Optional mapping from table names to
            descriptive titles, useful for datasets where table titles contain metadata.
    """

    db: pd.DataFrame | dict | str | Path | Database = field(default=None)
    model: Model | None = field(default=None)
    ingredients: Collection[Type[Ingredient]] | None = field(default_factory=list)

    verbose: bool = field(default=False)

    infer_gen_constraints: bool = field(default=True)
    enable_constrained_decoding: bool = field(default=True)
    enable_cascade_filter: bool = field(default=True)
    enable_early_exit: bool = field(default=True)

    table_to_title: dict[str, str] | None = field(default=None)

    def __post_init__(self):
        if not isinstance(self.db, Database):
            self.db = self._infer_db_type(self.db)
        if self.db is None:
            raise ValueError("df_or_db_path must be provided")
        self.ingredients = self._merge_default_ingredients(self.ingredients)
        self._toggle_verbosity(self.verbose)

    @staticmethod
    def _toggle_verbosity(verbose_in_use: bool):
        if verbose_in_use:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.ERROR)

    @staticmethod
    def _merge_default_ingredients(
        ingredients: Collection[Type[Ingredient]] | None,
    ) -> set[Type[Ingredient]]:
        from blendsql.ingredients import LLMQA, LLMMap, LLMJoin

        DEFAULT_INGREDIENTS = {LLMQA, LLMMap, LLMJoin}
        try:
            _ingredient_names = [i.__name__.upper() for i in ingredients]
        except AttributeError as e:
            raise IngredientException(
                "All arguments passed to `ingredients` should be `Ingredient` classes!"
            ) from e
        ingredient_names = set(_ingredient_names)
        if len(ingredient_names) != len(_ingredient_names):
            raise IngredientException(
                f"Duplicate ingredient names passed! These are case insensitive, be careful.\n{_ingredient_names=}"
            )
        ingredients = set(ingredients)
        for default_ingredient in DEFAULT_INGREDIENTS:
            if default_ingredient.__name__.upper() not in ingredient_names:
                ingredients.add(default_ingredient)
        return ingredients

    @staticmethod
    def _infer_db_type(df_or_db_path: pd.DataFrame | dict | str | Path) -> Database:
        if df_or_db_path is None:
            from .db.pandas import Pandas

            return Pandas({})  # Load an empty DuckDB connection

        elif isinstance(df_or_db_path, (pd.DataFrame, dict)):
            from .db.pandas import Pandas

            if isinstance(df_or_db_path, dict):
                if not isinstance(next(iter(df_or_db_path.values())), pd.DataFrame):
                    logger.debug(
                        Color.update("Converting dict values to pd.DataFrames...")
                    )
                    df_or_db_path = {
                        k: pd.DataFrame(v) for k, v in df_or_db_path.items()
                    }
            return Pandas(df_or_db_path)

        elif isinstance(df_or_db_path, (str, Path)):
            if Path(df_or_db_path).exists():
                if Path(df_or_db_path).suffix == ".duckdb":
                    from .db.duckdb import DuckDB

                    return DuckDB.from_file(df_or_db_path)
                else:
                    from .db.sqlite import SQLite

                    return SQLite(df_or_db_path)
            elif "://" in df_or_db_path:
                from .db.postgresql import PostgreSQL

                return PostgreSQL(df_or_db_path)
        else:
            raise ValueError(
                f"Could not resolve '{df_or_db_path}' to a valid database type!"
            )

    def visualize(self, query: str, output_path: str | None = None, format="pdf"):
        """Visualize query as a DAG with graphviz."""
        from .visualize import SQLGlotASTVisualizer

        visualizer = SQLGlotASTVisualizer()

        dialect: sqlglot.Dialect = get_dialect(self.db.__class__.__name__)

        # Generate visualization
        dot = visualizer.visualize(
            _parse_one(query, dialect=dialect, schema=self.db.sqlglot_schema)
        )

        if output_path is not None:
            # Save as PDF
            dot.render(output_path, format=format, cleanup=True)
        return dot

    def execute(
        self,
        query: str,
        ingredients: Collection[Type[Ingredient]] | None = None,
        model: str | None = None,
        infer_gen_constraints: bool | None = None,
        enable_cascade_filter: bool | None = None,
        enable_early_exit: bool | None = None,
        enable_constrained_decoding: bool | None = None,
        verbose: bool | None = None,
    ) -> Smoothie:
        '''The `execute()` function is used to execute a BlendSQL query against a database and
        return the final result, in addition to the intermediate reasoning steps taken.
        Execution is done on a database given an ingredient context.

        Args:
            query: The BlendSQL query to execute
            ingredients: Collection of ingredient objects, to use in interpreting BlendSQL query.
                {LLMQA, LLMMap, LLMJoin} are supplied by default.
            verbose: Boolean defining whether to run with logger in debug mode
            default_model: Which BlendSQL model to use in performing ingredient tasks in the current query
            infer_gen_constraints: Optionally infer the output format of an `IngredientMap` call, given the predicate context
                For example, in `{{LLMMap('convert to date', 'w::listing date')}} <= '1960-12-31'`
                We can infer the output format should look like '1960-12-31' and both:
                    1) Put this string in the `example_outputs` kwarg
                    2) If we have a LocalModel, pass the date regex pattern to guidance
            enable_cascade_filter: Enable cascade filtering optimization.
            enable_early_exit: Enable early exit optimization.
            enable_constrained_decoding: Enable constrained decoding for local models.

        Returns:
            smoothie: `Smoothie` dataclass containing pd.DataFrame output and execution metadata

        Examples:
            ```python
            import psutil
            import pandas as pd

            from blendsql import BlendSQL
            from blendsql.models import LlamaCpp

            # Prepare our BlendSQL connection
            bsql = BlendSQL(
                {
                    "People": pd.DataFrame(
                        {
                            "Name": [
                                "George Washington",
                                "John Quincy Adams",
                                "Thomas Jefferson",
                                "James Madison",
                                "James Monroe",
                                "Alexander Hamilton",
                                "Sabrina Carpenter",
                                "Charli XCX",
                                "Elon Musk",
                                "Michelle Obama",
                                "Elvis Presley",
                            ],
                            "Known_For": [
                                "Established federal government, First U.S. President",
                                "XYZ Affair, Alien and Sedition Acts",
                                "Louisiana Purchase, Declaration of Independence",
                                "War of 1812, Constitution",
                                "Monroe Doctrine, Missouri Compromise",
                                "Created national bank, Federalist Papers",
                                "Nonsense, Emails I Cant Send, Mean Girls musical",
                                "Crash, How Im Feeling Now, Boom Clap",
                                "Tesla, SpaceX, Twitter/X acquisition",
                                "Lets Move campaign, Becoming memoir",
                                "14 Grammys, King of Rock n Roll",
                            ],
                        }
                    ),
                    "Eras": pd.DataFrame({"Years": ["1800-1900", "1900-2000", "2000-Now"]}),
                },
                model = LlamaCpp(
                    model_name_or_path="unsloth/gemma-3-4b-it-GGUF",
                    filename="gemma-3-4b-it-Q4_K_M.gguf",
                    config={
                        "n_gpu_layers": -1,
                        "n_ctx": 1028,
                        "seed": 100,
                        "n_threads": psutil.cpu_count(logical=False),
                    }
                )
            )

            smoothie = bsql.execute(
                """
                SELECT * FROM People P
                WHERE P.Name IN {{
                    LLMQA('First 3 presidents of the U.S?', quantifier='{3}')
                }}
                """
            )

            print(smoothie.df)
            # ┌───────────────────┬───────────────────────────────────────────────────────┐
            # │ Name              │ Known_For                                             │
            # ├───────────────────┼───────────────────────────────────────────────────────┤
            # │ George Washington │ Established federal government, First U.S. Preside... │
            # │ John Quincy Adams │ XYZ Affair, Alien and Sedition Acts                   │
            # │ Thomas Jefferson  │ Louisiana Purchase, Declaration of Independence       │
            # └───────────────────┴───────────────────────────────────────────────────────┘
            smoothie.print_summary()
            # ┌────────────┬──────────────────────┬─────────────────┬─────────────────────┐
            # │   Time (s) │   # Generation Calls │   Prompt Tokens │   Completion Tokens │
            # ├────────────┼──────────────────────┼─────────────────┼─────────────────────┤
            # │    1.25158 │                    1 │             296 │                  16 │
            # └────────────┴──────────────────────┴─────────────────┴─────────────────────┘
            ```
        '''
        self._toggle_verbosity(verbose if verbose is not None else self.verbose)
        logger.debug(Color.horizontal_line())
        start = time.time()
        model_in_use = model or self.model
        try:
            smoothie = _blend(
                query=query,
                db=self.db,
                default_model=model_in_use,
                ingredients=self._merge_default_ingredients(
                    ingredients or self.ingredients
                ),
                infer_gen_constraints=infer_gen_constraints
                if infer_gen_constraints is not None
                else self.infer_gen_constraints,
                enable_constrained_decoding=enable_constrained_decoding
                if enable_constrained_decoding is not None
                else self.enable_constrained_decoding,
                enable_cascade_filter=enable_cascade_filter
                if enable_cascade_filter is not None
                else self.enable_cascade_filter,
                enable_early_exit=enable_early_exit
                if enable_early_exit is not None
                else self.enable_early_exit,
                table_to_title=self.table_to_title,
            )
        except Exception as error:
            raise error
        finally:
            # In the case of a recursive `_blend()` call,
            #   this logic allows temp tables to persist until
            #   the final base case is fulfilled.
            self.db._reset_connection()
            # Reset model stats, so future executions don't add here
            if model_in_use is not None:
                model_in_use.reset_stats()
        smoothie.meta.process_time_seconds = time.time() - start
        logger.debug(Color.horizontal_line())
        return smoothie

execute(query, ingredients=None, model=None, infer_gen_constraints=None, enable_cascade_filter=None, enable_early_exit=None, enable_constrained_decoding=None, verbose=None)

The execute() function is used to execute a BlendSQL query against a database and return the final result, in addition to the intermediate reasoning steps taken. Execution is done on a database given an ingredient context.

Parameters:

Name Type Description Default
query str

The BlendSQL query to execute

required
ingredients Collection[Type[Ingredient]] | None

Collection of ingredient objects, to use in interpreting BlendSQL query. {LLMQA, LLMMap, LLMJoin} are supplied by default.

None
verbose bool | None

Boolean defining whether to run with logger in debug mode

None
default_model

Which BlendSQL model to use in performing ingredient tasks in the current query

required
infer_gen_constraints bool | None

Optionally infer the output format of an IngredientMap call, given the predicate context For example, in {{LLMMap('convert to date', 'w::listing date')}} <= '1960-12-31' We can infer the output format should look like '1960-12-31' and both: 1) Put this string in the example_outputs kwarg 2) If we have a LocalModel, pass the date regex pattern to guidance

None
enable_cascade_filter bool | None

Enable cascade filtering optimization.

None
enable_early_exit bool | None

Enable early exit optimization.

None
enable_constrained_decoding bool | None

Enable constrained decoding for local models.

None

Returns:

Name Type Description
smoothie Smoothie

Smoothie dataclass containing pd.DataFrame output and execution metadata

Examples:

import psutil
import pandas as pd

from blendsql import BlendSQL
from blendsql.models import LlamaCpp

# Prepare our BlendSQL connection
bsql = BlendSQL(
    {
        "People": pd.DataFrame(
            {
                "Name": [
                    "George Washington",
                    "John Quincy Adams",
                    "Thomas Jefferson",
                    "James Madison",
                    "James Monroe",
                    "Alexander Hamilton",
                    "Sabrina Carpenter",
                    "Charli XCX",
                    "Elon Musk",
                    "Michelle Obama",
                    "Elvis Presley",
                ],
                "Known_For": [
                    "Established federal government, First U.S. President",
                    "XYZ Affair, Alien and Sedition Acts",
                    "Louisiana Purchase, Declaration of Independence",
                    "War of 1812, Constitution",
                    "Monroe Doctrine, Missouri Compromise",
                    "Created national bank, Federalist Papers",
                    "Nonsense, Emails I Cant Send, Mean Girls musical",
                    "Crash, How Im Feeling Now, Boom Clap",
                    "Tesla, SpaceX, Twitter/X acquisition",
                    "Lets Move campaign, Becoming memoir",
                    "14 Grammys, King of Rock n Roll",
                ],
            }
        ),
        "Eras": pd.DataFrame({"Years": ["1800-1900", "1900-2000", "2000-Now"]}),
    },
    model = LlamaCpp(
        model_name_or_path="unsloth/gemma-3-4b-it-GGUF",
        filename="gemma-3-4b-it-Q4_K_M.gguf",
        config={
            "n_gpu_layers": -1,
            "n_ctx": 1028,
            "seed": 100,
            "n_threads": psutil.cpu_count(logical=False),
        }
    )
)

smoothie = bsql.execute(
    """
    SELECT * FROM People P
    WHERE P.Name IN {{
        LLMQA('First 3 presidents of the U.S?', quantifier='{3}')
    }}
    """
)

print(smoothie.df)
# ┌───────────────────┬───────────────────────────────────────────────────────┐
# │ Name              │ Known_For                                             │
# ├───────────────────┼───────────────────────────────────────────────────────┤
# │ George Washington │ Established federal government, First U.S. Preside... │
# │ John Quincy Adams │ XYZ Affair, Alien and Sedition Acts                   │
# │ Thomas Jefferson  │ Louisiana Purchase, Declaration of Independence       │
# └───────────────────┴───────────────────────────────────────────────────────┘
smoothie.print_summary()
# ┌────────────┬──────────────────────┬─────────────────┬─────────────────────┐
# │   Time (s) │   # Generation Calls │   Prompt Tokens │   Completion Tokens │
# ├────────────┼──────────────────────┼─────────────────┼─────────────────────┤
# │    1.25158 │                    1 │             296 │                  16 │
# └────────────┴──────────────────────┴─────────────────┴─────────────────────┘
Source code in blendsql/blendsql.py
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
def execute(
    self,
    query: str,
    ingredients: Collection[Type[Ingredient]] | None = None,
    model: str | None = None,
    infer_gen_constraints: bool | None = None,
    enable_cascade_filter: bool | None = None,
    enable_early_exit: bool | None = None,
    enable_constrained_decoding: bool | None = None,
    verbose: bool | None = None,
) -> Smoothie:
    '''The `execute()` function is used to execute a BlendSQL query against a database and
    return the final result, in addition to the intermediate reasoning steps taken.
    Execution is done on a database given an ingredient context.

    Args:
        query: The BlendSQL query to execute
        ingredients: Collection of ingredient objects, to use in interpreting BlendSQL query.
            {LLMQA, LLMMap, LLMJoin} are supplied by default.
        verbose: Boolean defining whether to run with logger in debug mode
        default_model: Which BlendSQL model to use in performing ingredient tasks in the current query
        infer_gen_constraints: Optionally infer the output format of an `IngredientMap` call, given the predicate context
            For example, in `{{LLMMap('convert to date', 'w::listing date')}} <= '1960-12-31'`
            We can infer the output format should look like '1960-12-31' and both:
                1) Put this string in the `example_outputs` kwarg
                2) If we have a LocalModel, pass the date regex pattern to guidance
        enable_cascade_filter: Enable cascade filtering optimization.
        enable_early_exit: Enable early exit optimization.
        enable_constrained_decoding: Enable constrained decoding for local models.

    Returns:
        smoothie: `Smoothie` dataclass containing pd.DataFrame output and execution metadata

    Examples:
        ```python
        import psutil
        import pandas as pd

        from blendsql import BlendSQL
        from blendsql.models import LlamaCpp

        # Prepare our BlendSQL connection
        bsql = BlendSQL(
            {
                "People": pd.DataFrame(
                    {
                        "Name": [
                            "George Washington",
                            "John Quincy Adams",
                            "Thomas Jefferson",
                            "James Madison",
                            "James Monroe",
                            "Alexander Hamilton",
                            "Sabrina Carpenter",
                            "Charli XCX",
                            "Elon Musk",
                            "Michelle Obama",
                            "Elvis Presley",
                        ],
                        "Known_For": [
                            "Established federal government, First U.S. President",
                            "XYZ Affair, Alien and Sedition Acts",
                            "Louisiana Purchase, Declaration of Independence",
                            "War of 1812, Constitution",
                            "Monroe Doctrine, Missouri Compromise",
                            "Created national bank, Federalist Papers",
                            "Nonsense, Emails I Cant Send, Mean Girls musical",
                            "Crash, How Im Feeling Now, Boom Clap",
                            "Tesla, SpaceX, Twitter/X acquisition",
                            "Lets Move campaign, Becoming memoir",
                            "14 Grammys, King of Rock n Roll",
                        ],
                    }
                ),
                "Eras": pd.DataFrame({"Years": ["1800-1900", "1900-2000", "2000-Now"]}),
            },
            model = LlamaCpp(
                model_name_or_path="unsloth/gemma-3-4b-it-GGUF",
                filename="gemma-3-4b-it-Q4_K_M.gguf",
                config={
                    "n_gpu_layers": -1,
                    "n_ctx": 1028,
                    "seed": 100,
                    "n_threads": psutil.cpu_count(logical=False),
                }
            )
        )

        smoothie = bsql.execute(
            """
            SELECT * FROM People P
            WHERE P.Name IN {{
                LLMQA('First 3 presidents of the U.S?', quantifier='{3}')
            }}
            """
        )

        print(smoothie.df)
        # ┌───────────────────┬───────────────────────────────────────────────────────┐
        # │ Name              │ Known_For                                             │
        # ├───────────────────┼───────────────────────────────────────────────────────┤
        # │ George Washington │ Established federal government, First U.S. Preside... │
        # │ John Quincy Adams │ XYZ Affair, Alien and Sedition Acts                   │
        # │ Thomas Jefferson  │ Louisiana Purchase, Declaration of Independence       │
        # └───────────────────┴───────────────────────────────────────────────────────┘
        smoothie.print_summary()
        # ┌────────────┬──────────────────────┬─────────────────┬─────────────────────┐
        # │   Time (s) │   # Generation Calls │   Prompt Tokens │   Completion Tokens │
        # ├────────────┼──────────────────────┼─────────────────┼─────────────────────┤
        # │    1.25158 │                    1 │             296 │                  16 │
        # └────────────┴──────────────────────┴─────────────────┴─────────────────────┘
        ```
    '''
    self._toggle_verbosity(verbose if verbose is not None else self.verbose)
    logger.debug(Color.horizontal_line())
    start = time.time()
    model_in_use = model or self.model
    try:
        smoothie = _blend(
            query=query,
            db=self.db,
            default_model=model_in_use,
            ingredients=self._merge_default_ingredients(
                ingredients or self.ingredients
            ),
            infer_gen_constraints=infer_gen_constraints
            if infer_gen_constraints is not None
            else self.infer_gen_constraints,
            enable_constrained_decoding=enable_constrained_decoding
            if enable_constrained_decoding is not None
            else self.enable_constrained_decoding,
            enable_cascade_filter=enable_cascade_filter
            if enable_cascade_filter is not None
            else self.enable_cascade_filter,
            enable_early_exit=enable_early_exit
            if enable_early_exit is not None
            else self.enable_early_exit,
            table_to_title=self.table_to_title,
        )
    except Exception as error:
        raise error
    finally:
        # In the case of a recursive `_blend()` call,
        #   this logic allows temp tables to persist until
        #   the final base case is fulfilled.
        self.db._reset_connection()
        # Reset model stats, so future executions don't add here
        if model_in_use is not None:
            model_in_use.reset_stats()
    smoothie.meta.process_time_seconds = time.time() - start
    logger.debug(Color.horizontal_line())
    return smoothie

visualize(query, output_path=None, format='pdf')

Visualize query as a DAG with graphviz.

Source code in blendsql/blendsql.py
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
def visualize(self, query: str, output_path: str | None = None, format="pdf"):
    """Visualize query as a DAG with graphviz."""
    from .visualize import SQLGlotASTVisualizer

    visualizer = SQLGlotASTVisualizer()

    dialect: sqlglot.Dialect = get_dialect(self.db.__class__.__name__)

    # Generate visualization
    dot = visualizer.visualize(
        _parse_one(query, dialect=dialect, schema=self.db.sqlglot_schema)
    )

    if output_path is not None:
        # Save as PDF
        dot.render(output_path, format=format, cleanup=True)
    return dot