From d81d6e874fcba2dbcc9c27dd2f76590d10a600b9 Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Sat, 22 Jul 2023 20:30:04 +0200 Subject: [PATCH] doc(sqldatabasechain): use views when jsonb column description is not available (#8133) I think the PR diff is self explaining ;) @baskaryan --- .../modules/chains/popular/sqlite.mdx | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/snippets/modules/chains/popular/sqlite.mdx b/docs/snippets/modules/chains/popular/sqlite.mdx index fd34900f45..5da8bcfbdb 100644 --- a/docs/snippets/modules/chains/popular/sqlite.mdx +++ b/docs/snippets/modules/chains/popular/sqlite.mdx @@ -447,6 +447,30 @@ db_chain.run("What are some example tracks by Bach?") +### SQL Views + +In some case, the table schema can be hidden behind a JSON or JSONB column. Adding row samples into the prompt might help won't always describe the data perfectly. + +For this reason, a custom SQL views can help. + +```sql +CREATE VIEW accounts_v AS + select id, firstname, lastname, email, created_at, updated_at, + cast(stats->>'total_post' as int) as total_post, + cast(stats->>'total_comments' as int) as total_comments, + cast(stats->>'ltv' as int) as ltv + + FROM accounts; +``` + +Then limit the tables visible from SQLDatabase to the created view. + +```python +db = SQLDatabase.from_uri( + "sqlite:///../../../../notebooks/Chinook.db", + include_tables=['accounts_v']) # we include only the view +``` + ## SQLDatabaseSequentialChain Chain for querying SQL database that is a sequential chain.