Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

RLS AI improvements (#26895)

Greg Richardson801ad65603fa
diff --git a/apps/studio/pages/api/ai/sql/generate-v2.ts b/apps/studio/pages/api/ai/sql/generate-v2.ts
index 882b6faa275..cd1f2bc269c 100644
--- a/apps/studio/pages/api/ai/sql/generate-v2.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v2.ts
@@ -1,5 +1,5 @@
import { StreamingTextResponse } from 'ai'
-import { generateV2 } from 'ai-commands/edge'
+import { chatSql } from 'ai-commands/edge'
import { NextRequest } from 'next/server'
import OpenAI from 'openai'
@@ -48,7 +48,7 @@ async function handlePost(request: NextRequest) {
const { messages, existingSql, entityDefinitions } = body
try {
- const stream = await generateV2(openai, messages, existingSql, entityDefinitions)
+ const stream = await chatSql(openai, messages, existingSql, entityDefinitions)
return new StreamingTextResponse(stream)
} catch (error) {
if (error instanceof Error) {
diff --git a/package-lock.json b/package-lock.json
index bccfec2311a..dbe1053f661 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10684,6 +10684,86 @@
"node": ">= 8"
}
},
+ "node_modules/@npmcli/agent": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-2.2.2.tgz",
+ "integrity": "sha512-OrcNPXdpSl9UX7qPVRWbmWMCSXrcDa2M9DvrbOTj7ao1S4PlqVFYv9/yLKMkrJKZ/V5A/kDBC690or307i26Og==",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "http-proxy-agent": "^7.0.0",
+ "https-proxy-agent": "^7.0.1",
+ "lru-cache": "^10.0.1",
+ "socks-proxy-agent": "^8.0.3"
+ },
+ "engines": {
+ "node": "^16.14.0 || >=18.0.0"
+ }
+ },
+ "node_modules/@npmcli/agent/node_modules/agent-base": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
+ "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==",
+ "dependencies": {
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@npmcli/agent/node_modules/http-proxy-agent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@npmcli/agent/node_modules/https-proxy-agent": {
+ "version": "7.0.4",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.4.tgz",
+ "integrity": "sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==",
+ "dependencies": {
+ "agent-base": "^7.0.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@npmcli/agent/node_modules/lru-cache": {
+ "version": "10.2.2",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
+ "integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
+ "engines": {
+ "node": "14 || >=16.14"
+ }
+ },
+ "node_modules/@npmcli/fs": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-3.1.1.tgz",
+ "integrity": "sha512-q9CRWjpHCMIh5sVyefoD1cA7PkvILqCZsnSOEUUivORLjxCO/Irmue2DprETiNgEqktDBZaM1Bi+jrarx1XdCg==",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
+ "node_modules/@npmcli/fs/node_modules/semver": {
+ "version": "7.6.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz",
+ "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/@npmcli/move-file": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-1.1.2.tgz",
@@ -11463,6 +11543,11 @@
"node": ">=14"
}
},
+ "node_modules/@pgsql/types": {
+ "version": "15.0.2",
+ "resolved": "https://registry.npmjs.org/@pgsql/types/-/types-15.0.2.tgz",
+ "integrity": "sha512-K3gtnbqbSUuUVmPm143qx5Gy2EmKuooshV95yMD48EUQ1256sgZBriEfY61OWJnlzdREdqHTIOxQqpZAb7XdZg=="
+ },
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"license": "MIT",
@@ -21372,7 +21457,6 @@
},
"node_modules/aggregate-error": {
"version": "3.1.0",
- "dev": true,
"license": "MIT",
"dependencies": {
"clean-stack": "^2.0.0",
@@ -23130,6 +23214,47 @@
"node": ">=8"
}
},
+ "node_modules/cacache": {
+ "version": "18.0.3",
+ "resolved": "https://registry.npmjs.org/cacache/-/cacache-18.0.3.tgz",
+ "integrity": "sha512-qXCd4rh6I07cnDqh8V48/94Tc/WSfj+o3Gn6NZ0aZovS255bUx8O13uKxRFd2eWG0xgsco7+YItQNPaa5E85hg==",
+ "dependencies": {
+ "@npmcli/fs": "^3.1.0",
+ "fs-minipass": "^3.0.0",
+ "glob": "^10.2.2",
+ "lru-cache": "^10.0.1",
+ "minipass": "^7.0.3",
+ "minipass-collect": "^2.0.1",
+ "minipass-flush": "^1.0.5",
+ "minipass-pipeline": "^1.2.4",
+ "p-map": "^4.0.0",
+ "ssri": "^10.0.0",
+ "tar": "^6.1.11",
+ "unique-filename": "^3.0.0"
+ },
+ "engines": {
+ "node": "^16.14.0 || >=18.0.0"
+ }
+ },
+ "node_modules/cacache/node_modules/fs-minipass": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz",
+ "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==",
+ "dependencies": {
+ "minipass": "^7.0.3"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
+ "node_modules/cacache/node_modules/lru-cache": {
+ "version": "10.2.2",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
+ "integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
+ "engines": {
+ "node": "14 || >=16.14"
+ }
+ },
"node_modules/call-bind": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz",
@@ -23463,7 +23588,6 @@
},
"node_modules/clean-stack": {
"version": "2.2.0",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -26207,7 +26331,6 @@
},
"node_modules/env-paths": {
"version": "2.2.1",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -26228,8 +26351,7 @@
"node_modules/err-code": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",
- "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",
- "dev": true
+ "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA=="
},
"node_modules/error-ex": {
"version": "1.3.2",
@@ -27618,6 +27740,11 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
+ "node_modules/exponential-backoff": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.1.tgz",
+ "integrity": "sha512-dX7e/LHVJ6W3DE1MHWi9S1EYzDESENfLrYohG2G++ovZrYOkm4Knwa0mc1cn84xJOR4KEU0WSchhLbd0UklbHw=="
+ },
"node_modules/expr-eval": {
"version": "2.0.2",
"dev": true,
@@ -30446,8 +30573,7 @@
"node_modules/http-cache-semantics": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz",
- "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==",
- "dev": true
+ "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ=="
},
"node_modules/http-errors": {
"version": "2.0.0",
@@ -30724,7 +30850,6 @@
},
"node_modules/indent-string": {
"version": "4.0.0",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -30833,7 +30958,6 @@
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz",
"integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==",
- "dev": true,
"dependencies": {
"jsbn": "1.1.0",
"sprintf-js": "^1.1.3"
@@ -30845,8 +30969,7 @@
"node_modules/ip-address/node_modules/sprintf-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
- "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
- "dev": true
+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="
},
"node_modules/ip-num": {
"version": "1.5.1",
@@ -31142,8 +31265,7 @@
"node_modules/is-lambda": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz",
- "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==",
- "dev": true
+ "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ=="
},
"node_modules/is-map": {
"version": "2.0.2",
@@ -33380,8 +33502,7 @@
"node_modules/jsbn": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",
- "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==",
- "dev": true
+ "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A=="
},
"node_modules/jscodeshift": {
"version": "0.15.2",
@@ -33835,13 +33956,14 @@
}
},
"node_modules/libpg-query": {
- "version": "15.1.0",
- "resolved": "https://registry.npmjs.org/libpg-query/-/libpg-query-15.1.0.tgz",
- "integrity": "sha512-bGtPycX7BLPmy/QEEG1HmsANKMU/yGSA2299Zj7KoVQJ5pPfnSZBFfUbq/3QvDq2ruVIa+ZaDjuMgX1uXdylVA==",
+ "version": "15.2.0",
+ "resolved": "https://registry.npmjs.org/libpg-query/-/libpg-query-15.2.0.tgz",
+ "integrity": "sha512-fBi14tsU3/ahtfU0C+/tvmtlt0EJM6kXe0Dl4/cSbiNmJ3IwLIuk3lawwiK5ByXU4sXwyAzbkvSl26jVXzYuaA==",
"hasInstallScript": true,
"dependencies": {
"@emnapi/runtime": "^0.43.1",
"@mapbox/node-pre-gyp": "^1.0.8",
+ "@pgsql/types": "^15.0.1",
"node-addon-api": "^7.0.0",
"node-gyp": "^10.0.1"
}
@@ -34257,6 +34379,36 @@
"devOptional": true,
"license": "ISC"
},
+ "node_modules/make-fetch-happen": {
+ "version": "13.0.1",
+ "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-13.0.1.tgz",
+ "integrity": "sha512-cKTUFc/rbKUd/9meOvgrpJ2WrNzymt6jfRDdwg5UCnVzv9dTpEj9JS5m3wtziXVCjluIXyL8pcaukYqezIzZQA==",
+ "dependencies": {
+ "@npmcli/agent": "^2.0.0",
+ "cacache": "^18.0.0",
+ "http-cache-semantics": "^4.1.1",
+ "is-lambda": "^1.0.1",
+ "minipass": "^7.0.2",
+ "minipass-fetch": "^3.0.0",
+ "minipass-flush": "^1.0.5",
+ "minipass-pipeline": "^1.2.4",
+ "negotiator": "^0.6.3",
+ "proc-log": "^4.2.0",
+ "promise-retry": "^2.0.1",
+ "ssri": "^10.0.0"
+ },
+ "engines": {
+ "node": "^16.14.0 || >=18.0.0"
+ }
+ },
+ "node_modules/make-fetch-happen/node_modules/proc-log": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-4.2.0.tgz",
+ "integrity": "sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA==",
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/makeerror": {
"version": "1.0.12",
"dev": true,
@@ -38529,11 +38681,37 @@
"node": ">=16 || 14 >=14.17"
}
},
+ "node_modules/minipass-collect": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz",
+ "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==",
+ "dependencies": {
+ "minipass": "^7.0.3"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/minipass-fetch": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-3.0.5.tgz",
+ "integrity": "sha512-2N8elDQAtSnFV0Dk7gt15KHsS0Fyz6CbYZ360h0WTYV1Ty46li3rAXVOQj1THMNLdmrD9Vt5pBPtWtVkpwGBqg==",
+ "dependencies": {
+ "minipass": "^7.0.3",
+ "minipass-sized": "^1.0.3",
+ "minizlib": "^2.1.2"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ },
+ "optionalDependencies": {
+ "encoding": "^0.1.13"
+ }
+ },
"node_modules/minipass-flush": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz",
"integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==",
- "dev": true,
"dependencies": {
"minipass": "^3.0.0"
},
@@ -38545,7 +38723,6 @@
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "dev": true,
"dependencies": {
"yallist": "^4.0.0"
},
@@ -38556,14 +38733,12 @@
"node_modules/minipass-flush/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "dev": true
+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
},
"node_modules/minipass-pipeline": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz",
"integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==",
- "dev": true,
"dependencies": {
"minipass": "^3.0.0"
},
@@ -38575,7 +38750,6 @@
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "dev": true,
"dependencies": {
"yallist": "^4.0.0"
},
@@ -38586,14 +38760,12 @@
"node_modules/minipass-pipeline/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "dev": true
+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
},
"node_modules/minipass-sized": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz",
"integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==",
- "dev": true,
"dependencies": {
"minipass": "^3.0.0"
},
@@ -38605,7 +38777,6 @@
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "dev": true,
"dependencies": {
"yallist": "^4.0.0"
},
@@ -38616,8 +38787,7 @@
"node_modules/minipass-sized/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "dev": true
+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
},
"node_modules/minizlib": {
"version": "2.1.2",
@@ -39070,7 +39240,6 @@
},
"node_modules/negotiator": {
"version": "0.6.3",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -39385,6 +39554,29 @@
"webidl-conversions": "^3.0.0"
}
},
+ "node_modules/node-gyp": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-10.1.0.tgz",
+ "integrity": "sha512-B4J5M1cABxPc5PwfjhbV5hoy2DP9p8lFXASnEN6hugXOa61416tnTZ29x9sSwAd0o99XNIcpvDDy1swAExsVKA==",
+ "dependencies": {
+ "env-paths": "^2.2.0",
+ "exponential-backoff": "^3.1.1",
+ "glob": "^10.3.10",
+ "graceful-fs": "^4.2.6",
+ "make-fetch-happen": "^13.0.0",
+ "nopt": "^7.0.0",
+ "proc-log": "^3.0.0",
+ "semver": "^7.3.5",
+ "tar": "^6.1.2",
+ "which": "^4.0.0"
+ },
+ "bin": {
+ "node-gyp": "bin/node-gyp.js"
+ },
+ "engines": {
+ "node": "^16.14.0 || >=18.0.0"
+ }
+ },
"node_modules/node-gyp-build": {
"version": "4.6.1",
"license": "MIT",
@@ -39396,6 +39588,61 @@
"node-gyp-build-test": "build-test.js"
}
},
+ "node_modules/node-gyp/node_modules/abbrev": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz",
+ "integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==",
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
+ "node_modules/node-gyp/node_modules/isexe": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz",
+ "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==",
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/node-gyp/node_modules/nopt": {
+ "version": "7.2.1",
+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz",
+ "integrity": "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==",
+ "dependencies": {
+ "abbrev": "^2.0.0"
+ },
+ "bin": {
+ "nopt": "bin/nopt.js"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
+ "node_modules/node-gyp/node_modules/semver": {
+ "version": "7.6.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz",
+ "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/node-gyp/node_modules/which": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz",
+ "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==",
+ "dependencies": {
+ "isexe": "^3.1.1"
+ },
+ "bin": {
+ "node-which": "bin/which.js"
+ },
+ "engines": {
+ "node": "^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/node-int64": {
"version": "0.4.0",
"dev": true,
@@ -40520,7 +40767,6 @@
},
"node_modules/p-map": {
"version": "4.0.0",
- "dev": true,
"license": "MIT",
"dependencies": {
"aggregate-error": "^3.0.0"
@@ -41128,6 +41374,18 @@
"node": ">=8"
}
},
+ "node_modules/pgsql-parser/node_modules/minipass-collect": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-1.0.2.tgz",
+ "integrity": "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==",
+ "dev": true,
+ "dependencies": {
+ "minipass": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/pgsql-parser/node_modules/minipass-fetch": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-1.4.1.tgz",
@@ -42047,6 +42305,14 @@
"node": ">=6"
}
},
+ "node_modules/proc-log": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-3.0.0.tgz",
+ "integrity": "sha512-++Vn7NS4Xf9NacaU9Xq3URUuqZETPsf8L4j5/ckhaRYsfPeRyzGw+iDjFhV/Jr3uNmTvvddEJFWh5R1gRgUH8A==",
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/process": {
"version": "0.11.10",
"dev": true,
@@ -42082,7 +42348,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",
"integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",
- "dev": true,
"dependencies": {
"err-code": "^2.0.2",
"retry": "^0.12.0"
@@ -45659,7 +45924,6 @@
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
- "dev": true,
"engines": {
"node": ">= 4"
}
@@ -46535,7 +46799,6 @@
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
- "dev": true,
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
@@ -46554,7 +46817,6 @@
"version": "2.8.3",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz",
"integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==",
- "dev": true,
"dependencies": {
"ip-address": "^9.0.5",
"smart-buffer": "^4.2.0"
@@ -46564,6 +46826,30 @@
"npm": ">= 3.0.0"
}
},
+ "node_modules/socks-proxy-agent": {
+ "version": "8.0.3",
+ "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.3.tgz",
+ "integrity": "sha512-VNegTZKhuGq5vSD6XNKlbqWhyt/40CgoEw8XxD6dhnm8Jq9IEa3nIa4HwnM8XOqU0CdB0BwWVXusqiFXfHB3+A==",
+ "dependencies": {
+ "agent-base": "^7.1.1",
+ "debug": "^4.3.4",
+ "socks": "^2.7.1"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/socks-proxy-agent/node_modules/agent-base": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
+ "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==",
+ "dependencies": {
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/solid-js": {
"version": "1.8.6",
"resolved": "https://registry.npmjs.org/solid-js/-/solid-js-1.8.6.tgz",
@@ -46721,6 +47007,17 @@
"resolved": "https://registry.npmjs.org/sse.js/-/sse.js-2.2.0.tgz",
"integrity": "sha512-v1ciaikunC99FKS23rS973HYU0DnnvugtX13UggNvrgRUSungaGeLmKlm57t0dI2E1TcCqzc2Pj2njBDXFIpKQ=="
},
+ "node_modules/ssri": {
+ "version": "10.0.6",
+ "resolved": "https://registry.npmjs.org/ssri/-/ssri-10.0.6.tgz",
+ "integrity": "sha512-MGrFH9Z4NP9Iyhqn16sDtBpRRNJ0Y2hNa6D65h736fVSaPCHr4DM4sWUNvVaSuC+0OBGhwsrydQwmgfg5LncqQ==",
+ "dependencies": {
+ "minipass": "^7.0.3"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/sswr": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/sswr/-/sswr-2.0.0.tgz",
@@ -49654,6 +49951,28 @@
"node": ">=4"
}
},
+ "node_modules/unique-filename": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-3.0.0.tgz",
+ "integrity": "sha512-afXhuC55wkAmZ0P18QsVE6kp8JaxrEokN2HGIoIVv2ijHQd419H0+6EigAFcIzXeMIkcIkNBpB3L/DXB3cTS/g==",
+ "dependencies": {
+ "unique-slug": "^4.0.0"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
+ "node_modules/unique-slug": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-4.0.0.tgz",
+ "integrity": "sha512-WrcA6AyEfqDX5bWige/4NQfPZMtASNVxdmWR76WESYQVAACSgWcR6e9i0mofqqBxYFtL4oAxPIptY73/0YE1DQ==",
+ "dependencies": {
+ "imurmurhash": "^0.1.4"
+ },
+ "engines": {
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+ }
+ },
"node_modules/unique-string": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz",
@@ -52096,7 +52415,6 @@
"config": "*",
"js-tiktoken": "^1.0.10",
"jsonrepair": "^3.5.0",
- "libpg-query": "^15.1.0",
"openai": "^4.26.1"
},
"devDependencies": {
@@ -52106,8 +52424,10 @@
"@types/common-tags": "^1.8.4",
"babel-jest": "^29.7.0",
"babel-plugin-transform-import-meta": "^2.2.1",
+ "chalk": "^5.3.0",
"dotenv": "^16.3.1",
"jest": "^29.7.0",
+ "libpg-query": "^15.2.0",
"mdast-util-from-markdown": "^2.0.0",
"sql-formatter": "^15.0.2",
"ts-jest": "^29.1.1",
@@ -52121,6 +52441,18 @@
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
"dev": true
},
+ "packages/ai-commands/node_modules/chalk": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",
+ "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==",
+ "dev": true,
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"packages/ai-commands/node_modules/sql-formatter": {
"version": "15.0.2",
"resolved": "https://registry.npmjs.org/sql-formatter/-/sql-formatter-15.0.2.tgz",
diff --git a/packages/ai-commands/edge.ts b/packages/ai-commands/edge.ts
index 269714fb334..d73e04b769f 100644
--- a/packages/ai-commands/edge.ts
+++ b/packages/ai-commands/edge.ts
@@ -1,2 +1,5 @@
export * from './src/errors'
-export * from './src/sql.edge'
+
+export * from './src/docs'
+export * from './src/sql/rls'
+export * from './src/sql/chat'
diff --git a/packages/ai-commands/jest.config.js b/packages/ai-commands/jest.config.js
index b970fa8370a..41dcba31882 100644
--- a/packages/ai-commands/jest.config.js
+++ b/packages/ai-commands/jest.config.js
@@ -8,8 +8,8 @@ module.exports = {
},
setupFiles: ['./test/setup.ts'],
setupFilesAfterEnv: ['./test/extensions.ts'],
- testTimeout: 15000,
+ testTimeout: 30000,
transformIgnorePatterns: [
- 'node_modules/(?!(mdast-.*|micromark|micromark-.*|unist-.*|decode-named-character-reference|character-entities)/)',
+ 'node_modules/(?!(mdast-.*|micromark|micromark-.*|unist-.*|decode-named-character-reference|character-entities|chalk)/)',
],
}
diff --git a/packages/ai-commands/package.json b/packages/ai-commands/package.json
index cb59f405009..c6fd2214ea2 100644
--- a/packages/ai-commands/package.json
+++ b/packages/ai-commands/package.json
@@ -4,6 +4,7 @@
"main": "./index.ts",
"types": "./index.ts",
"license": "MIT",
+ "sideEffects": false,
"scripts": {
"typecheck": "tsc --noEmit",
"test": "jest"
@@ -16,7 +17,6 @@
"config": "*",
"js-tiktoken": "^1.0.10",
"jsonrepair": "^3.5.0",
- "libpg-query": "^15.1.0",
"openai": "^4.26.1"
},
"devDependencies": {
@@ -26,8 +26,10 @@
"@types/common-tags": "^1.8.4",
"babel-jest": "^29.7.0",
"babel-plugin-transform-import-meta": "^2.2.1",
+ "chalk": "^5.3.0",
"dotenv": "^16.3.1",
"jest": "^29.7.0",
+ "libpg-query": "^15.2.0",
"mdast-util-from-markdown": "^2.0.0",
"sql-formatter": "^15.0.2",
"ts-jest": "^29.1.1",
diff --git a/packages/ai-commands/src/sql.edge.ts b/packages/ai-commands/src/docs.ts
similarity index 54%
rename from packages/ai-commands/src/sql.edge.ts
rename to packages/ai-commands/src/docs.ts
index fb5164e9bc2..f2c12ed4732 100644
--- a/packages/ai-commands/src/sql.edge.ts
+++ b/packages/ai-commands/src/docs.ts
@@ -1,169 +1,9 @@
import { SupabaseClient } from '@supabase/supabase-js'
-import { OpenAIStream } from 'ai'
-import { codeBlock, oneLine, stripIndent } from 'common-tags'
+import { codeBlock, oneLine } from 'common-tags'
import OpenAI from 'openai'
-
-import { ApplicationError, ContextLengthError, UserError } from './errors'
+import { ApplicationError, UserError } from './errors'
import { getChatRequestTokenCount, getMaxTokenCount, tokenizer } from './tokenizer'
-
-interface Message {
- role: 'user' | 'assistant'
- content: string
-}
-
-/**
- * Responds to a conversation about building an RLS policy.
- *
- * @returns A `ReadableStream` containing the response text and SQL.
- */
-export async function chatRlsPolicy(
- openai: OpenAI,
- messages: Message[],
- entityDefinitions?: string[],
- policyDefinition?: string
-): Promise<ReadableStream<Uint8Array>> {
- const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
- {
- role: 'system',
- content: stripIndent`
- You're an Postgres expert in writing row level security policies. Your purpose is to
- generate a policy with the constraints given by the user. You will be provided a schema
- on which the policy should be applied.
-
- The output should use the following instructions:
- - The generated SQL must be valid SQL.
- - Always use double apostrophe in SQL strings (eg. 'Night''s watch')
- - You can use only CREATE POLICY or ALTER POLICY queries, no other queries are allowed.
- - You can add short explanations to your messages.
- - The result should be a valid markdown. The SQL code should be wrapped in \`\`\`.
- - Always use "auth.uid()" instead of "current_user".
- - You can't use "USING" expression on INSERT policies.
- - Only use "WITH CHECK" expression on INSERT or UPDATE policies.
- - The policy name should be short text explaining the policy, enclosed in double quotes.
- - Always put explanations as separate text. Never use inline SQL comments.
- - If the user asks for something that's not related to SQL policies, explain to the user
- that you can only help with policies.
-
- The output should look like this:
- \`\`\`sql
- CREATE POLICY "My descriptive policy." ON users FOR INSERT USING (user_name = current_user) WITH (true);
- \`\`\`
- `,
- },
- ]
-
- if (entityDefinitions) {
- const definitions = codeBlock`${entityDefinitions.join('\n\n')}`
- initMessages.push({
- role: 'user',
- content: oneLine`Here is my database schema for reference: ${definitions}`,
- })
- }
-
- if (policyDefinition !== undefined) {
- const definitionBlock = codeBlock`${policyDefinition}`
- initMessages.push({
- role: 'user',
- content: codeBlock`
- Here is my policy definition for reference:
- ${definitionBlock}
- `.trim(),
- })
- }
-
- if (messages) {
- initMessages.push(...messages)
- }
-
- try {
- const response = await openai.chat.completions.create({
- model: 'gpt-3.5-turbo-0125',
- messages: initMessages,
- max_tokens: 1024,
- temperature: 0,
- stream: true,
- })
-
- // Transform the streamed SSE response from OpenAI to a ReadableStream
- return OpenAIStream(response)
- } catch (error) {
- if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {
- throw new ContextLengthError()
- }
- throw error
- }
-}
-
-/**
- * Responds to a conversation about writing a SQL query.
- *
- * @returns A `ReadableStream` containing the response text and SQL.
- */
-export async function generateV2(
- openai: OpenAI,
- messages: Message[],
- existingSql?: string,
- entityDefinitions?: string[]
-): Promise<ReadableStream<Uint8Array>> {
- const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
- {
- role: 'system',
- content: stripIndent`
- The generated SQL (must be valid SQL).
- - For primary keys, always use "id bigint primary key generated always as identity" (not serial)
- - Prefer creating foreign key references in the create statement
- - Prefer 'text' over 'varchar'
- - Prefer 'timestamp with time zone' over 'date'
- - Use vector(384) data type for any embedding/vector related query
- - Always use double apostrophe in SQL strings (eg. 'Night''s watch')
- - Always use semicolons
- - Output as markdown
- - Always include code snippets if available
- `,
- },
- ]
-
- if (entityDefinitions) {
- const definitions = codeBlock`${entityDefinitions.join('\n\n')}`
- initMessages.push({
- role: 'user',
- content: oneLine`Here is my database schema for reference: ${definitions}`,
- })
- }
-
- if (existingSql !== undefined && existingSql.length > 0) {
- const sqlBlock = codeBlock`${existingSql}`
- initMessages.push({
- role: 'user',
- content: codeBlock`
- Here is the existing SQL I wrote for reference:
- ${sqlBlock}
- `.trim(),
- })
- }
-
- if (messages) {
- initMessages.push(...messages)
- }
-
- try {
- const response = await openai.chat.completions.create({
- model: 'gpt-3.5-turbo-0125',
- messages: initMessages,
- max_tokens: 1024,
- temperature: 0,
- stream: true,
- })
-
- // Transform the streamed SSE response from OpenAI to a ReadableStream
- return OpenAIStream(response)
- } catch (error) {
- if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {
- throw new ContextLengthError()
- }
- throw error
- }
-}
+import { Message } from './types'
export async function clippy(
openai: OpenAI,
diff --git a/packages/ai-commands/src/__snapshots__/sql.test.ts.snap b/packages/ai-commands/src/sql/__snapshots__/functions.test.ts.snap
similarity index 68%
rename from packages/ai-commands/src/__snapshots__/sql.test.ts.snap
rename to packages/ai-commands/src/sql/__snapshots__/functions.test.ts.snap
index 6fc082f6c93..e9034ef2505 100644
--- a/packages/ai-commands/src/__snapshots__/sql.test.ts.snap
+++ b/packages/ai-commands/src/sql/__snapshots__/functions.test.ts.snap
@@ -20,12 +20,3 @@ exports[`debug fix typos 1`] = `
from
employees;"
`;
-
-exports[`rls chat select policy using table definition 1`] = `
-{
- "checkExpression": undefined,
- "command": "select",
- "table": "todos",
- "usingExpression": "user_id = auth.uid ()",
-}
-`;
diff --git a/packages/ai-commands/src/sql/chat.ts b/packages/ai-commands/src/sql/chat.ts
new file mode 100644
index 00000000000..0f7ba6f53e0
--- /dev/null
+++ b/packages/ai-commands/src/sql/chat.ts
@@ -0,0 +1,76 @@
+import { OpenAIStream } from 'ai'
+import { codeBlock, oneLine, stripIndent } from 'common-tags'
+import OpenAI from 'openai'
+import { ContextLengthError } from '../errors'
+import { Message } from '../types'
+
+/**
+ * Responds to a conversation about writing a SQL query.
+ *
+ * @returns A `ReadableStream` containing the response text and SQL.
+ */
+export async function chatSql(
+ openai: OpenAI,
+ messages: Message[],
+ existingSql?: string,
+ entityDefinitions?: string[]
+): Promise<ReadableStream<Uint8Array>> {
+ const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
+ {
+ role: 'system',
+ content: stripIndent`
+ The generated SQL (must be valid SQL).
+ - For primary keys, always use "id bigint primary key generated always as identity" (not serial)
+ - Prefer creating foreign key references in the create statement
+ - Prefer 'text' over 'varchar'
+ - Prefer 'timestamp with time zone' over 'date'
+ - Use vector(384) data type for any embedding/vector related query
+ - Always use double apostrophe in SQL strings (eg. 'Night''s watch')
+ - Always use semicolons
+ - Output as markdown
+ - Always include code snippets if available
+ `,
+ },
+ ]
+
+ if (entityDefinitions) {
+ const definitions = codeBlock`${entityDefinitions.join('\n\n')}`
+ initMessages.push({
+ role: 'user',
+ content: oneLine`Here is my database schema for reference: ${definitions}`,
+ })
+ }
+
+ if (existingSql !== undefined && existingSql.length > 0) {
+ const sqlBlock = codeBlock`${existingSql}`
+ initMessages.push({
+ role: 'user',
+ content: codeBlock`
+ Here is the existing SQL I wrote for reference:
+ ${sqlBlock}
+ `.trim(),
+ })
+ }
+
+ if (messages) {
+ initMessages.push(...messages)
+ }
+
+ try {
+ const response = await openai.chat.completions.create({
+ model: 'gpt-3.5-turbo-0125',
+ messages: initMessages,
+ max_tokens: 1024,
+ temperature: 0,
+ stream: true,
+ })
+
+ // Transform the streamed SSE response from OpenAI to a ReadableStream
+ return OpenAIStream(response)
+ } catch (error) {
+ if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {
+ throw new ContextLengthError()
+ }
+ throw error
+ }
+}
diff --git a/packages/ai-commands/src/sql.test.ts b/packages/ai-commands/src/sql/functions.test.ts
similarity index 59%
rename from packages/ai-commands/src/sql.test.ts
rename to packages/ai-commands/src/sql/functions.test.ts
index 24c5ab2f7ed..0780ab70d55 100644
--- a/packages/ai-commands/src/sql.test.ts
+++ b/packages/ai-commands/src/sql/functions.test.ts
@@ -1,15 +1,14 @@
import { describe, expect, test } from '@jest/globals'
import { codeBlock } from 'common-tags'
import OpenAI from 'openai'
-import { collectStream, extractMarkdownSql, formatSql, getPolicyInfo } from '../test/util'
-import { debugSql, titleSql } from './sql'
-import { chatRlsPolicy } from './sql.edge'
+import { formatSql } from '../../test/util'
+import { debugSql, titleSql } from './functions'
const openAiKey = process.env.OPENAI_API_KEY
const openai = new OpenAI({ apiKey: openAiKey })
describe('debug', () => {
- test('fix order of operations', async () => {
+ test.concurrent('fix order of operations', async () => {
const { sql } = await debugSql(
openai,
'relation "departments" does not exist',
@@ -31,7 +30,7 @@ describe('debug', () => {
expect(formatSql(sql)).toMatchSnapshot()
})
- test('fix typos', async () => {
+ test.concurrent('fix typos', async () => {
const { sql, solution } = await debugSql(
openai,
'syntax error at or near "fromm"',
@@ -68,36 +67,3 @@ describe('title', () => {
await expect(description).toMatchCriteria('describes employees and departments')
})
})
-
-describe('rls chat', () => {
- test('select policy using table definition', async () => {
- const responseStream = await chatRlsPolicy(
- openai,
- [
- {
- role: 'user',
- content: 'Users can only select their own todos',
- },
- ],
- [
- codeBlock`
- create table todos (
- id bigint primary key generated always as identity,
- task text,
- email text,
- user_id uuid references auth.users (id)
- );
- `,
- ]
- )
- const responseText = await collectStream(responseStream)
- const [sql] = extractMarkdownSql(responseText)
-
- const { name, ...otherInfo } = await getPolicyInfo(sql)
-
- expect(otherInfo).toMatchSnapshot()
- await expect(name).toMatchCriteria(
- 'policy says that users can select their own todos (not insert, update, delete, etc)'
- )
- })
-})
diff --git a/packages/ai-commands/src/sql.ts b/packages/ai-commands/src/sql/functions.ts
similarity index 99%
rename from packages/ai-commands/src/sql.ts
rename to packages/ai-commands/src/sql/functions.ts
index 3b58bdb0e5b..7955e9a30b3 100644
--- a/packages/ai-commands/src/sql.ts
+++ b/packages/ai-commands/src/sql/functions.ts
@@ -2,7 +2,7 @@ import { SchemaBuilder } from '@serafin/schema-builder'
import { codeBlock, stripIndent } from 'common-tags'
import { jsonrepair } from 'jsonrepair'
import OpenAI from 'openai'
-import { ContextLengthError, EmptyResponseError, EmptySqlError } from './errors'
+import { ContextLengthError, EmptyResponseError, EmptySqlError } from '../errors'
const debugSqlSchema = SchemaBuilder.emptySchema()
.addString('solution', {
diff --git a/packages/ai-commands/src/sql/index.ts b/packages/ai-commands/src/sql/index.ts
new file mode 100644
index 00000000000..74ac7958470
--- /dev/null
+++ b/packages/ai-commands/src/sql/index.ts
@@ -0,0 +1,2 @@
+export * from './chat'
+export * from './functions'
diff --git a/packages/ai-commands/src/sql/rls.test.ts b/packages/ai-commands/src/sql/rls.test.ts
new file mode 100644
index 00000000000..93dda53c743
--- /dev/null
+++ b/packages/ai-commands/src/sql/rls.test.ts
@@ -0,0 +1,486 @@
+import { describe, expect, test } from '@jest/globals'
+import { codeBlock } from 'common-tags'
+import OpenAI from 'openai'
+import {
+ assertAndRenderColumn,
+ assertAndUnwrapNode,
+ assertDefined,
+ assertEachSideOfExpression,
+ assertEitherSideOfExpression,
+ assertNodeType,
+ getPolicies,
+ getPolicyInfo,
+ parseConstant,
+ renderFields,
+ renderJsonExpression,
+ renderTargets,
+ unwrapNode,
+} from '../../test/sql-util'
+import { collectStream, extractMarkdownSql, withMetadata } from '../../test/util'
+import { chatRlsPolicy } from './rls'
+
+const openAiKey = process.env.OPENAI_API_KEY
+const openai = new OpenAI({ apiKey: openAiKey })
+
+const tableDefs = [
+ codeBlock`
+ create table libraries (
+ id bigint primary key generated always as identity,
+ name text not null
+ );
+
+ create table authors (
+ id bigint primary key generated always as identity,
+ name text not null
+ );
+
+ create table books (
+ id bigint primary key generated always as identity,
+ title text not null,
+ description text not null,
+ genre text not null,
+ author_id bigint references authors (id) not null,
+ library_id bigint references libraries (id) not null,
+ published_at timestamp with time zone not null
+ );
+
+ create table reviews (
+ id bigint primary key generated always as identity,
+ title text not null,
+ content text not null,
+ user_id uuid references auth.users (id) not null,
+ book_id bigint references books (id) not null,
+ published_at timestamp with time zone
+ )
+
+ create tables favorite_books (
+ id bigint primary key generated always as identity,
+ user_id uuid references auth.users (id) not null,
+ book_id bigint references books (id) not null
+ );
+
+ create table library_memberships (
+ id bigint primary key generated always as identity,
+ user_id uuid references auth.users (id) not null,
+ library_id bigint references libraries (id) not null
+ );
+ `,
+]
+
+describe('rls chat', () => {
+ test.concurrent('defaults to authenticated role', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Users can only see their own favorite books',
+ },
+ ],
+ tableDefs
+ )
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+ const { roles } = await getPolicyInfo(policy)
+
+ withMetadata({ sql }, () => {
+ expect(roles).toStrictEqual(['authenticated'])
+ })
+ })
+
+ test.concurrent('uses anon + authenticated roles when table viewable by anyone', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Published reviews can be seen by anyone',
+ },
+ ],
+ tableDefs
+ )
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+ const { roles } = await getPolicyInfo(policy)
+
+ withMetadata({ sql }, () => {
+ expect(roles.sort()).toStrictEqual(['anon', 'authenticated'].sort())
+ })
+ })
+
+ test.concurrent('wraps every function in select', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Users can only see their own favorite books',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+ const { usingNode } = await getPolicyInfo(policy)
+
+ withMetadata({ sql }, () => {
+ assertDefined(usingNode, 'Expected USING expression')
+ const usingExpression = assertAndUnwrapNode(
+ usingNode,
+ 'A_Expr',
+ 'Expected USING to contain an expression'
+ )
+
+ assertEitherSideOfExpression(usingExpression, (node) => {
+ const functionCall = unwrapNode(node, 'FuncCall')
+
+ if (functionCall) {
+ throw new Error('Expected function call to be wrapped in a select sub-query')
+ }
+
+ const subQuery = unwrapNode(node, 'SubLink')
+
+ if (!subQuery) {
+ throw new Error('Expected a sub-query wrapping the function')
+ }
+
+ assertDefined(subQuery.subselect, 'Expected SubLink to contain a subselect')
+ const selectStatement = assertAndUnwrapNode(
+ subQuery.subselect,
+ 'SelectStmt',
+ 'Expected subselect to contain a SELECT statement'
+ )
+
+ assertDefined(selectStatement.targetList, 'Expected SELECT statement to have a target list')
+
+ const [target] = selectStatement.targetList.map((node) =>
+ assertAndUnwrapNode(node, 'ResTarget', 'Expected every select target to be a ResTarget')
+ )
+
+ assertDefined(target, 'Expected select sub-query to have a function target')
+ assertDefined(target.val, 'Expected ResTarget to have a val')
+ assertNodeType(target.val, 'FuncCall', 'Expected sub-query to contain a function call')
+ })
+ })
+ })
+
+ test.concurrent('select policy has USING but not WITH CHECK', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'All published reviews can be seen publicly',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ expect(policy.cmd_name).toBe('select')
+ expect(policy.qual).not.toBeUndefined()
+ expect(policy.with_check).toBeUndefined()
+ })
+ })
+
+ test.concurrent('insert policy has WITH CHECK but not USING', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Users can only create their own reviews',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ expect(policy.cmd_name).toBe('insert')
+ expect(policy.qual).toBeUndefined()
+ expect(policy.with_check).not.toBeUndefined()
+ })
+ })
+
+ test.concurrent('update policy has USING and WITH CHECK', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: "You can't edit other people's reviews",
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ expect(policy.cmd_name).toBe('update')
+ expect(policy.qual).not.toBeUndefined()
+ expect(policy.with_check).not.toBeUndefined()
+ })
+ })
+
+ test.concurrent('delete policy has USING but not WITH CHECK', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: "You can't delete someone else's review",
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ expect(policy.cmd_name).toBe('delete')
+ expect(policy.qual).not.toBeUndefined()
+ expect(policy.with_check).toBeUndefined()
+ })
+ })
+
+ test.concurrent('splits multiple operations into separate policies', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Users can only access their own reviews',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const policies = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ const allPolicy = policies.find((policy) => policy.cmd_name === 'all')
+ const selectPolicy = policies.find((policy) => policy.cmd_name === 'select')
+ const insertPolicy = policies.find((policy) => policy.cmd_name === 'insert')
+ const updatePolicy = policies.find((policy) => policy.cmd_name === 'update')
+ const deletePolicy = policies.find((policy) => policy.cmd_name === 'delete')
+
+ expect(allPolicy).toBeUndefined()
+ expect(selectPolicy).not.toBeUndefined()
+ expect(insertPolicy).not.toBeUndefined()
+ expect(updatePolicy).not.toBeUndefined()
+ expect(deletePolicy).not.toBeUndefined()
+ })
+ })
+
+ test.concurrent('discourages restrictive policies', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Can I make a policy restrict access instead of give access?',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+
+ await expect(responseText).toMatchCriteria(
+ 'Discourages restrictive policies and provides reasons why'
+ )
+ })
+
+ test.concurrent('user id is on joined table and joins are minimized', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Users can only see books from libraries they are a member of',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ // Check that USING is a <column> IN <sub-query> expression
+ assertDefined(policy.qual, 'Expected a USING statement')
+ const sublink = assertAndUnwrapNode(policy.qual, 'SubLink', 'Expected USING to be a sublink')
+ expect(sublink.subLinkType).toBe('ANY_SUBLINK')
+
+ // Validate column
+ assertDefined(sublink.testexpr, 'Expected sublink to have a test expression')
+ const columnName = assertAndRenderColumn(
+ sublink.testexpr,
+ 'Expected sublink test expression to be a column'
+ )
+ expect(columnName).toBe('library_id')
+
+ // Validate sub-query
+ assertDefined(sublink.subselect, 'Expected sublink to have a subselect')
+ const selectStatement = assertAndUnwrapNode(
+ sublink.subselect,
+ 'SelectStmt',
+ 'Expected sublink subselect to be a SELECT statement'
+ )
+
+ assertDefined(selectStatement.targetList, 'Expected SELECT statement to have a target list')
+ const columns = renderTargets(selectStatement.targetList, (node) =>
+ assertAndRenderColumn(node, 'Expected target list to contain columns')
+ )
+ expect(columns).toContain('library_id')
+
+ assertDefined(selectStatement.fromClause, 'Expected SELECT statement to have a FROM clause')
+ const [fromNode] = selectStatement.fromClause
+
+ const fromRangeVar = assertAndUnwrapNode(
+ fromNode,
+ 'RangeVar',
+ 'Expected FROM clause to contain a RangeVar'
+ )
+ expect(fromRangeVar.relname).toBe('library_memberships')
+
+ assertDefined(selectStatement.whereClause, 'Expected SELECT statement to have a WHERE clause')
+ const whereClause = assertAndUnwrapNode(
+ selectStatement.whereClause,
+ 'A_Expr',
+ 'Expected WHERE clause to be an expression'
+ )
+
+ assertEachSideOfExpression(
+ whereClause,
+ (node) => {
+ const columnName = assertAndRenderColumn(
+ node,
+ 'Expected one side of WHERE clause to have a column'
+ )
+ expect(columnName).toBe('user_id')
+ },
+ (node) => {
+ const sublink = assertAndUnwrapNode(
+ node,
+ 'SubLink',
+ 'Expected one side of WHERE clause to contain a sub-query selecting auth.uid()'
+ )
+
+ assertDefined(sublink.subselect, 'Expected sublink to contain a subselect')
+ const selectStatement = assertAndUnwrapNode(
+ sublink.subselect,
+ 'SelectStmt',
+ 'Expected subselect to contain a SELECT statement'
+ )
+
+ assertDefined(
+ selectStatement.targetList,
+ 'Expected SELECT statement to contain a target list'
+ )
+ const [functionCall] = renderTargets(selectStatement.targetList, (node) => {
+ const funcCall = assertAndUnwrapNode(
+ node,
+ 'FuncCall',
+ 'Expected SELECT statement to contain a function call'
+ )
+ assertDefined(funcCall.funcname, 'Expected function call to have a name')
+ return renderFields(funcCall.funcname)
+ })
+ expect(functionCall).toBe('auth.uid')
+ }
+ )
+ })
+ })
+
+ test.concurrent('mfa', async () => {
+ const responseStream = await chatRlsPolicy(
+ openai,
+ [
+ {
+ role: 'user',
+ content: 'Users need a second form of auth to join a library',
+ },
+ ],
+ tableDefs
+ )
+
+ const responseText = await collectStream(responseStream)
+ const [sql] = extractMarkdownSql(responseText)
+ const [policy] = await getPolicies(sql)
+
+ withMetadata({ sql }, () => {
+ expect(policy.cmd_name).toBe('insert')
+
+ assertDefined(policy.with_check, 'Expected INSERT policy to have a WITH CHECK')
+ const expression = assertAndUnwrapNode(
+ policy.with_check,
+ 'A_Expr',
+ 'Expected WITH CHECK to be an expression'
+ )
+
+ assertEachSideOfExpression(
+ expression,
+ (node) => {
+ const constValue = assertAndUnwrapNode(
+ node,
+ 'A_Const',
+ 'Expected one side of expression to be a constant'
+ )
+ const stringValue = parseConstant(constValue)
+ expect(stringValue).toBe('aal2')
+ },
+ (node) => {
+ const sublink = assertAndUnwrapNode(
+ node,
+ 'SubLink',
+ 'Expected one side of expression to be a sub-query'
+ )
+
+ assertDefined(sublink.subselect, 'Expected sublink to have a subselect')
+ const selectStatement = assertAndUnwrapNode(
+ sublink.subselect,
+ 'SelectStmt',
+ 'Expected sub-query to be a SELECT statement'
+ )
+
+ assertDefined(
+ selectStatement.targetList,
+ 'Expected SELECT statement to have a target list'
+ )
+ const [jsonTarget] = renderTargets(selectStatement.targetList, (node) => {
+ const expression = assertAndUnwrapNode(
+ node,
+ 'A_Expr',
+ 'Expected SELECT target list to contain a JSON expression'
+ )
+ const jsonExpression = renderJsonExpression(expression)
+ return jsonExpression
+ })
+
+ expect(jsonTarget).toBe("auth.jwt()->>'aal'")
+ }
+ )
+ })
+ })
+})
diff --git a/packages/ai-commands/src/sql/rls.ts b/packages/ai-commands/src/sql/rls.ts
new file mode 100644
index 00000000000..d631d94cce7
--- /dev/null
+++ b/packages/ai-commands/src/sql/rls.ts
@@ -0,0 +1,302 @@
+import { OpenAIStream } from 'ai'
+import { codeBlock, oneLine, stripIndent } from 'common-tags'
+import OpenAI from 'openai'
+import { ContextLengthError } from '../errors'
+import { Message } from '../types'
+
+/**
+ * Responds to a conversation about building an RLS policy.
+ *
+ * @returns A `ReadableStream` containing the response text and SQL.
+ */
+export async function chatRlsPolicy(
+ openai: OpenAI,
+ messages: Message[],
+ entityDefinitions?: string[],
+ policyDefinition?: string
+): Promise<ReadableStream<Uint8Array>> {
+ const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
+ {
+ role: 'system',
+ content: stripIndent`
+ You're a Supabase Postgres expert in writing row level security policies. Your purpose is to
+ generate a policy with the constraints given by the user. You will be provided a schema
+ on which the policy should be applied.
+
+ The output should use the following instructions:
+ - The generated SQL must be valid SQL.
+ - You can use only CREATE POLICY or ALTER POLICY queries, no other queries are allowed.
+ - Always use double apostrophe in SQL strings (eg. 'Night''s watch')
+ - You can add short explanations to your messages.
+ - The result should be a valid markdown. The SQL code should be wrapped in \`\`\` (including sql language tag).
+ - Always use "auth.uid()" instead of "current_user".
+ - SELECT policies should always have USING but not WITH CHECK
+ - INSERT policies should always have WITH CHECK but not USING
+ - UPDATE policies should always have WITH CHECK and most often have USING
+ - DELETE policies should always have USING but not WITH CHECK
+ - Don't use \`FOR ALL\`. Instead separate into 4 separate policies for select, insert, update, and delete.
+ - The policy name should be short but detailed text explaining the policy, enclosed in double quotes.
+ - Always put explanations as separate text. Never use inline SQL comments.
+ - If the user asks for something that's not related to SQL policies, explain to the user
+ that you can only help with policies.
+ - Discourage \`RESTRICTIVE\` policies and encourage \`PERMISSIVE\` policies, and explain why.
+
+ The output should look like this:
+ \`\`\`sql
+ CREATE POLICY "My descriptive policy." ON books FOR INSERT to authenticated USING ( (select auth.uid()) = author_id ) WITH ( true );
+ \`\`\`
+
+ Since you are running in a Supabase environment, take note of these Supabase-specific additions:
+
+ ## Authenticated and unauthenticated roles
+
+ Supabase maps every request to one of the roles:
+
+ - \`anon\`: an unauthenticated request (the user is not logged in)
+ - \`authenticated\`: an authenticated request (the user is logged in)
+
+ These are actually [Postgres Roles](/docs/guides/database/postgres/roles). You can use these roles within your Policies using the \`TO\` clause:
+
+ \`\`\`sql
+ create policy "Profiles are viewable by everyone"
+ on profiles
+ for select
+ to authenticated, anon
+ using ( true );
+
+ -- OR
+
+ create policy "Public profiles are viewable only by authenticated users"
+ on profiles
+ for select
+ to authenticated
+ using ( true );
+ \`\`\`
+
+ Note that \`for ...\` must be added after the table but before the roles. \`to ...\` must be added after \`for ...\`:
+
+ ### Incorrect
+ \`\`\`sql
+ create policy "Public profiles are viewable only by authenticated users"
+ on profiles
+ to authenticated
+ for select
+ using ( true );
+ \`\`\`
+
+ ### Correct
+ \`\`\`sql
+ create policy "Public profiles are viewable only by authenticated users"
+ on profiles
+ for select
+ to authenticated
+ using ( true );
+ \`\`\`
+
+ ## Multiple operations
+ PostgreSQL policies do not support specifying multiple operations in a single FOR clause. You need to create separate policies for each operation.
+
+ ### Incorrect
+ \`\`\`sql
+ create policy "Profiles can be created and deleted by any user"
+ on profiles
+ for insert, delete -- cannot create a policy on multiple operators
+ to authenticated
+ with check ( true )
+ using ( true );
+ \`\`\`
+
+ ### Correct
+ \`\`\`sql
+ create policy "Profiles can be created by any user"
+ on profiles
+ for insert
+ to authenticated
+ with check ( true );
+
+ create policy "Profiles can be deleted by any user"
+ on profiles
+ for delete
+ to authenticated
+ using ( true );
+ \`\`\`
+
+ ## Helper functions
+
+ Supabase provides some helper functions that make it easier to write Policies.
+
+ ### \`auth.uid()\`
+
+ Returns the ID of the user making the request.
+
+ ### \`auth.jwt()\`
+
+ Returns the JWT of the user making the request. Anything that you store in the user's \`raw_app_meta_data\` column or the \`raw_user_meta_data\` column will be accessible using this function. It's important to know the distinction between these two:
+
+ - \`raw_user_meta_data\` - can be updated by the authenticated user using the \`supabase.auth.update()\` function. It is not a good place to store authorization data.
+ - \`raw_app_meta_data\` - cannot be updated by the user, so it's a good place to store authorization data.
+
+ The \`auth.jwt()\` function is extremely versatile. For example, if you store some team data inside \`app_metadata\`, you can use it to determine whether a particular user belongs to a team. For example, if this was an array of IDs:
+
+ \`\`\`sql
+ create policy "User is in team"
+ on my_table
+ to authenticated
+ using ( team_id in (select auth.jwt() -> 'app_metadata' -> 'teams'));
+ \`\`\`
+
+ ### MFA
+
+ The \`auth.jwt()\` function can be used to check for [Multi-Factor Authentication](/docs/guides/auth/auth-mfa#enforce-rules-for-mfa-logins). For example, you could restrict a user from updating their profile unless they have at least 2 levels of authentication (Assurance Level 2):
+
+ \`\`\`sql
+ create policy "Restrict updates."
+ on profiles
+ as restrictive
+ for update
+ to authenticated using (
+ (select auth.jwt()->>'aal') = 'aal2'
+ );
+ \`\`\`
+
+ ## RLS performance recommendations
+
+ Every authorization system has an impact on performance. While row level security is powerful, the performance impact is important to keep in mind. This is especially true for queries that scan every row in a table - like many \`select\` operations, including those using limit, offset, and ordering.
+
+ Based on a series of [tests](https://github.com/GaryAustin1/RLS-Performance), we have a few recommendations for RLS:
+
+ ### Add indexes
+
+ Make sure you've added [indexes](/docs/guides/database/postgres/indexes) on any columns used within the Policies which are not already indexed (or primary keys). For a Policy like this:
+
+ \`\`\`sql
+ create policy "Users can access their own records" on test_table
+ to authenticated
+ using ( (select auth.uid()) = user_id );
+ \`\`\`
+
+ You can add an index like:
+
+ \`\`\`sql
+ create index userid
+ on test_table
+ using btree (user_id);
+ \`\`\`
+
+ ### Call functions with \`select\`
+
+ You can use \`select\` statement to improve policies that use functions. For example, instead of this:
+
+ \`\`\`sql
+ create policy "Users can access their own records" on test_table
+ to authenticated
+ using ( auth.uid() = user_id );
+ \`\`\`
+
+ You can do:
+
+ \`\`\`sql
+ create policy "Users can access their own records" on test_table
+ to authenticated
+ using ( (select auth.uid()) = user_id );
+ \`\`\`
+
+ This method works well for JWT functions like \`auth.uid()\` and \`auth.jwt()\` as well as \`security definer\` Functions. Wrapping the function causes an \`initPlan\` to be run by the Postgres optimizer, which allows it to "cache" the results per-statement, rather than calling the function on each row.
+
+ Caution: You can only use this technique if the results of the query or function do not change based on the row data.
+
+ ### Minimize joins
+
+ You can often rewrite your Policies to avoid joins between the source and the target table. Instead, try to organize your policy to fetch all the relevant data from the target table into an array or set, then you can use an \`IN\` or \`ANY\` operation in your filter.
+
+ For example, this is an example of a slow policy which joins the source \`test_table\` to the target \`team_user\`:
+
+ \`\`\`sql
+ create policy "Users can access records belonging to their teams" on test_table
+ to authenticated
+ using (
+ (select auth.uid()) in (
+ select user_id
+ from team_user
+ where team_user.team_id = team_id -- joins to the source "test_table.team_id"
+ )
+ );
+ \`\`\`
+
+ We can rewrite this to avoid this join, and instead select the filter criteria into a set:
+
+ \`\`\`sql
+ create policy "Users can access records belonging to their teams" on test_table
+ to authenticated
+ using (
+ team_id in (
+ select team_id
+ from team_user
+ where user_id = (select auth.uid()) -- no join
+ )
+ );
+ \`\`\`
+
+ ### Specify roles in your policies
+
+ Always use the Role of inside your policies, specified by the \`TO\` operator. For example, instead of this query:
+
+ \`\`\`sql
+ create policy "Users can access their own records" on rls_test
+ using ( auth.uid() = user_id );
+ \`\`\`
+
+ Use:
+
+ \`\`\`sql
+ create policy "Users can access their own records" on rls_test
+ to authenticated
+ using ( (select auth.uid()) = user_id );
+ \`\`\`
+
+ This prevents the policy \`( (select auth.uid()) = user_id )\` from running for any \`anon\` users, since the execution stops at the \`to authenticated\` step.
+ `,
+ },
+ ]
+
+ if (entityDefinitions) {
+ const definitions = codeBlock`${entityDefinitions.join('\n\n')}`
+ initMessages.push({
+ role: 'user',
+ content: oneLine`Here is my database schema for reference: ${definitions}`,
+ })
+ }
+
+ if (policyDefinition !== undefined) {
+ const definitionBlock = codeBlock`${policyDefinition}`
+ initMessages.push({
+ role: 'user',
+ content: codeBlock`
+ Here is my policy definition for reference:
+ ${definitionBlock}
+ `.trim(),
+ })
+ }
+
+ if (messages) {
+ initMessages.push(...messages)
+ }
+
+ try {
+ const response = await openai.chat.completions.create({
+ model: 'gpt-4o-2024-05-13',
+ messages: initMessages,
+ max_tokens: 1024,
+ temperature: 0,
+ stream: true,
+ })
+
+ // Transform the streamed SSE response from OpenAI to a ReadableStream
+ return OpenAIStream(response)
+ } catch (error) {
+ if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {
+ throw new ContextLengthError()
+ }
+ throw error
+ }
+}
diff --git a/packages/ai-commands/src/types.ts b/packages/ai-commands/src/types.ts
new file mode 100644
index 00000000000..d9a24b087ff
--- /dev/null
+++ b/packages/ai-commands/src/types.ts
@@ -0,0 +1,4 @@
+export interface Message {
+ role: 'user' | 'assistant'
+ content: string
+}
diff --git a/packages/ai-commands/test/extensions.ts b/packages/ai-commands/test/extensions.ts
index 07352f141de..b99e4d8c179 100644
--- a/packages/ai-commands/test/extensions.ts
+++ b/packages/ai-commands/test/extensions.ts
@@ -7,7 +7,7 @@ const openai = new OpenAI({ apiKey: openAiKey })
expect.extend({
async toMatchCriteria(received: string, criteria: string) {
- const model = 'gpt-4-1106-preview'
+ const model = 'gpt-4o-2024-05-13'
const completionResponse = await openai.chat.completions.create({
model,
diff --git a/packages/ai-commands/test/sql-util.ts b/packages/ai-commands/test/sql-util.ts
new file mode 100644
index 00000000000..79fae6a4795
--- /dev/null
+++ b/packages/ai-commands/test/sql-util.ts
@@ -0,0 +1,366 @@
+import { A_Const, A_Expr, ColumnRef, CreatePolicyStmt, Node, parseQuery } from 'libpg-query'
+
+export type PolicyInfo = {
+ name: string
+ relation: string
+ command?: string
+ roles: string[]
+ usingNode?: Node
+ withCheckNode?: Node
+}
+
+/**
+ * Extracts keys from a union type.
+ */
+type ExtractKeys<T> = T extends T ? keyof T : never
+
+/**
+ * Unwraps a Node to get its underlying value.
+ */
+type NodeValue<T extends Node, U extends ExtractKeys<Node>> = T extends Record<U, infer V>
+ ? V
+ : never
+
+export class AssertionError extends Error {
+ constructor(message: string) {
+ super(message)
+
+ // Pop the top line from the stack trace so that
+ // debug tools will reference the code calling the
+ // assertion function and not this error within it
+ if (this.stack) {
+ // Capture the current stack trace and split it into lines
+ const stackLines = this.stack.split('\n')
+
+ // Remove the second line which is the current constructor
+ stackLines.splice(1, 1)
+
+ // Reassign the modified stack trace back to the error object
+ this.stack = stackLines.join('\n')
+ }
+ }
+}
+
+/**
+ * Asserts that a value is defined.
+ *
+ * Useful for type narrowing.
+ */
+export function assertDefined<T>(value: T | undefined, errorMessage: string): asserts value is T {
+ if (value === undefined) {
+ throw new AssertionError(errorMessage)
+ }
+}
+
+/**
+ * Asserts that a `Node` is a specific type.
+ *
+ * Useful for type narrowing.
+ */
+export function assertNodeType<T extends Node>(
+ node: Node,
+ type: ExtractKeys<T>,
+ errorMessage: string
+): asserts node is T {
+ if (!(type in node)) {
+ throw new AssertionError(errorMessage)
+ }
+}
+
+/**
+ * Asserts that a `Node` is a specific type and
+ * unwraps its underlying value.
+ *
+ * @returns The unwrapped `Node` value.
+ * @throws If `node` is not of type `type`.
+ */
+export function assertAndUnwrapNode<T extends Node, U extends ExtractKeys<Node>>(
+ node: Node,
+ type: U,
+ errorMessage: string
+): NodeValue<T, U> {
+ if (!(type in node)) {
+ throw new AssertionError(errorMessage)
+ }
+ return (node as any)[type]
+}
+
+/**
+ * Unwraps a `Node`'s underlying value.
+ *
+ * @returns The unwrapped `Node` value or `undefined` if
+ * the node is not of type `type`.
+ */
+export function unwrapNode<T extends Node, U extends ExtractKeys<Node>>(
+ node: Node,
+ type: U
+): NodeValue<T, U> | undefined {
+ if (!(type in node)) {
+ return undefined
+ }
+ return (node as any)[type]
+}
+
+/**
+ * Asserts that either the left or right side of the
+ * expression is processed through `fn` without throwing
+ * any errors.
+ *
+ * If both sides throw errors, the assertion fails and the
+ * error from the left side will be thrown.
+ */
+export function assertEitherSideOfExpression<U>(
+ expression: A_Expr,
+ fn: (node: Node, side: 'left' | 'right') => U
+): U {
+ assertDefined(expression.lexpr, 'Expected left side of expression to exist')
+ assertDefined(expression.rexpr, 'Expected right side of expression to exist')
+
+ try {
+ return fn(expression.lexpr, 'left')
+ } catch (leftError) {
+ try {
+ return fn(expression.rexpr, 'right')
+ } catch (rightError) {
+ throw leftError
+ }
+ }
+}
+/**
+ * Asserts that both sides of the expression are processed
+ * without throwing any errors.
+ *
+ * Order doesn't matter. As long as `firstFn` and `secondFn`
+ * pass separately on either side of the expression, the assertion
+ * will pass. Otherwise if `firstFn` and `secondFn` both fail
+ * after trying on both sides separately, the assertion will fail.
+ */
+export function assertEachSideOfExpression<U>(
+ expression: A_Expr,
+ firstFn: (node: Node) => void,
+ secondFn: (node: Node) => void
+): void {
+ assertDefined(expression.lexpr, 'Expected left side of expression to exist')
+ assertDefined(expression.rexpr, 'Expected right side of expression to exist')
+
+ let firstSide: Node
+ let secondSide: Node
+
+ try {
+ // Try `firstFn` on the left first
+ firstSide = expression.lexpr
+ secondSide = expression.rexpr
+ firstFn(firstSide)
+ } catch (firstError) {
+ // Otherwise try `firstFn` on the right
+ firstSide = expression.rexpr
+ secondSide = expression.lexpr
+ try {
+ firstFn(firstSide)
+ } catch (secondError) {
+ // `firstFn` failed on both sides, so we
+ // need to throw an error not matter what
+
+ // Perform one more test using `secondFn`
+ // to help determine which error to show
+ // for `firstFn`
+ try {
+ secondFn(secondSide)
+ } catch (_) {
+ throw firstError
+ }
+ throw secondError
+ }
+ }
+
+ try {
+ // `firstFn` passed on one of the sides, so
+ // try `secondFn` on the opposite side
+ secondFn(secondSide)
+ } catch (err) {
+ // `secondFn` failed, so we need to throw an error
+ throw err
+ }
+}
+
+/**
+ * Extracts all the `CREATE POLICY` statements
+ * from a SQL string as parsed ASTs.
+ */
+export async function getPolicies(sql: string) {
+ const result = await parseQuery(sql)
+
+ assertDefined(result.stmts, 'Expected parse result to contain statements')
+
+ return result.stmts.reduce<CreatePolicyStmt[]>((filtered, stmt) => {
+ assertDefined(stmt.stmt, 'Expected statement to exist')
+
+ const createPolicyStatement = unwrapNode(stmt.stmt, 'CreatePolicyStmt')
+
+ if (createPolicyStatement) {
+ return [...filtered, createPolicyStatement]
+ }
+
+ return filtered
+ }, [])
+}
+
+/**
+ * Parses a Postgres SQL policy.
+ *
+ * @returns Information about the policy, including its name, table, command, and expressions.
+ */
+export async function getPolicyInfo(createPolicyStatement: CreatePolicyStmt) {
+ assertDefined(createPolicyStatement.policy_name, 'Expected policy to have a name')
+ assertDefined(createPolicyStatement.table?.relname, 'Expected policy to have a relation')
+
+ const name = createPolicyStatement.policy_name
+ const relation = createPolicyStatement.table.relname
+ const command = createPolicyStatement.cmd_name
+
+ const roles =
+ createPolicyStatement.roles?.map((node) => {
+ const roleSpec = assertAndUnwrapNode(
+ node,
+ 'RoleSpec',
+ 'Expected roles to contain a list of RoleSpec'
+ )
+ assertDefined(roleSpec.rolename, 'Expected RoleSpec to have a rolename')
+
+ return roleSpec.rolename
+ }) ?? []
+
+ const usingExpression = createPolicyStatement.qual
+ const checkExpression = createPolicyStatement.with_check
+
+ const policyInfo: PolicyInfo = {
+ name,
+ relation,
+ command,
+ roles,
+ usingNode: usingExpression,
+ withCheckNode: checkExpression,
+ }
+
+ return policyInfo
+}
+
+export function renderTargets<T>(targets: Node[], renderTarget: (node: Node) => T): T[] {
+ return targets.map((node) => {
+ const target = assertAndUnwrapNode(
+ node,
+ 'ResTarget',
+ 'Expected target list to contain ResTargets'
+ )
+
+ assertDefined(target.val, 'Expected ResTarget to have a val')
+ return renderTarget(target.val)
+ })
+}
+
+export function renderColumn(column: ColumnRef) {
+ assertDefined(column.fields, 'Expected column to have fields')
+ return renderFields(column.fields)
+}
+
+export function assertAndRenderColumn(node: Node, errorMessage: string) {
+ const column = assertAndUnwrapNode(node, 'ColumnRef', errorMessage)
+ return renderColumn(column)
+}
+
+export function renderJsonExpression(expression: A_Expr): string {
+ assertDefined(expression.name, 'Expected expression to have an operator')
+
+ if (expression.name.length > 1) {
+ throw new AssertionError('Only one JSON operator supported per expression')
+ }
+
+ const [name] = expression.name
+ const operatorString = assertAndUnwrapNode(
+ name,
+ 'String',
+ 'Expected JSON operator to be a string'
+ )
+ assertDefined(operatorString.sval, 'PG string expected to have an sval')
+ const operator = operatorString.sval
+
+ if (!['->', '->>'].includes(operator)) {
+ throw new AssertionError(`Invalid JSON operator ${operator}`)
+ }
+
+ assertDefined(expression.lexpr, 'Expected JSON expression to have a left-side component')
+ assertDefined(expression.rexpr, 'Expected JSON expression to have a right-side component')
+
+ let left: string | number
+ let right: string | number
+
+ const leftConstant = unwrapNode(expression.lexpr, 'A_Const')
+ const leftColumn = unwrapNode(expression.lexpr, 'ColumnRef')
+ const leftFuncCall = unwrapNode(expression.lexpr, 'FuncCall')
+ const leftExpression = unwrapNode(expression.lexpr, 'A_Expr')
+
+ if (leftConstant) {
+ // JSON path cannot contain a float
+ if ('fval' in leftConstant) {
+ throw new AssertionError('Invalid JSON path: Expression cannot contain a float')
+ }
+ left = `'${parseConstant(leftConstant)}'`
+ } else if (leftColumn) {
+ left = renderColumn(leftColumn)
+ } else if (leftFuncCall) {
+ assertDefined(leftFuncCall.funcname, 'Expected function call to have a name')
+ const functionName = renderFields(leftFuncCall.funcname)
+ left = `${functionName}()`
+ } else if (leftExpression) {
+ left = renderJsonExpression(leftExpression)
+ } else {
+ throw new AssertionError('Invalid JSON path')
+ }
+
+ const rightConstant = unwrapNode(expression.rexpr, 'A_Const')
+
+ if (rightConstant) {
+ // JSON path cannot contain a float
+ if ('fval' in rightConstant) {
+ throw new AssertionError('Invalid JSON path: Expression cannot contain a float')
+ }
+ right = `'${parseConstant(rightConstant)}'`
+ } else {
+ throw new AssertionError('Invalid JSON path')
+ }
+
+ return `${left}${operator}${right}`
+}
+
+export function renderFields(fields: Node[]) {
+ const nameSegments = fields
+ .map((field) => {
+ const stringField = unwrapNode(field, 'String')
+ const starField = unwrapNode(field, 'A_Star')
+
+ if (stringField !== undefined) {
+ return stringField.sval
+ } else if (starField !== undefined) {
+ return '*'
+ } else {
+ const [internalType] = Object.keys(field)
+ throw new Error(`Unsupported internal type '${internalType}' for fields`)
+ }
+ })
+ .filter((name): name is string => name !== undefined)
+
+ return nameSegments.join('.')
+}
+
+export function parseConstant(constant: A_Const) {
+ if ('sval' in constant) {
+ return constant.sval?.sval ?? ''
+ } else if ('ival' in constant) {
+ // The PG parser turns 0 into undefined, so convert it back here
+ return constant.ival?.ival ?? 0
+ } else if ('fval' in constant) {
+ return constant.fval?.fval ? parseFloat(constant.fval.fval) : 0
+ } else {
+ throw new AssertionError(`Constant values must be a string, integer, or float`)
+ }
+}
diff --git a/packages/ai-commands/test/util.ts b/packages/ai-commands/test/util.ts
index c0b29f9c685..36b71b065ce 100644
--- a/packages/ai-commands/test/util.ts
+++ b/packages/ai-commands/test/util.ts
@@ -1,4 +1,4 @@
-import { parseQuery } from 'libpg-query'
+import chalk from 'chalk'
import { fromMarkdown } from 'mdast-util-from-markdown'
import type { Code } from 'mdast-util-from-markdown/lib'
import { format } from 'sql-formatter'
@@ -9,14 +9,6 @@ declare global {
}
}
-export type PolicyInfo = {
- name: string
- table: string
- command?: string
- usingExpression?: string
- checkExpression?: string
-}
-
/**
* Formats Postgres SQL into a consistent format.
*
@@ -56,50 +48,43 @@ export function extractMarkdownSql(markdown: string) {
}
/**
- * Parses a Postgres SQL policy.
+ * Prints the provided metadata along with any assertion errors.
+ * Works both synchronously and asynchronously.
*
- * @returns Information about the policy, including its name, table, command, and expressions.
+ * Useful for providing extra context for failed tests.
*/
-export async function getPolicyInfo(sql: string) {
- const result = await parseQuery(sql)
-
- if (result.stmts.length === 0) {
- throw new Error('Expected a statement, but received none')
- }
-
- if (result.stmts.length > 1) {
- throw new Error('Expected a single statement, but received multiple')
+export function withMetadata<T extends void | Promise<void>>(
+ metadata: Record<string, string>,
+ fn: () => T
+): T {
+ /**
+ * Prepends metadata to an Error's stack trace.
+ */
+ function modifyError(err: unknown) {
+ if (err instanceof Error && err.stack) {
+ const formattedMetadata = Object.entries(metadata).map(
+ ([key, value]) => `${chalk.bold.dim(key)}:\n\n${chalk.green.dim(value)}`
+ )
+ err.stack = `${formattedMetadata.join('\n\n')}\n\n${err.stack}`
+ }
+
+ return err
}
- const [{ stmt }] = result.stmts
-
- const createPolicyStatement = stmt.CreatePolicyStmt
-
- if (!createPolicyStatement) {
- throw new Error('Expected a create policy statement')
+ // Execute the function and handle both
+ // synchronous or asynchronous scenarios
+ try {
+ const maybePromise = fn()
+
+ if (maybePromise instanceof Promise) {
+ return maybePromise.catch((err) => {
+ // Re-throw the error
+ throw modifyError(err)
+ }) as T
+ }
+ return maybePromise
+ } catch (err) {
+ // Re-throw the error
+ throw modifyError(err)
}
-
- const formattedSql = formatSql(sql)
-
- const usingMatch = formattedSql.match(/using\s*\((.*)\)/is)
- let usingExpression
- if (usingMatch) {
- usingExpression = usingMatch[1]
- }
-
- const withCheckMatch = formattedSql.match(/with check\s*\((.*)\)/is)
- let checkExpression
- if (withCheckMatch) {
- checkExpression = withCheckMatch[1]
- }
-
- const policyInfo: PolicyInfo = {
- name: createPolicyStatement.policy_name,
- table: createPolicyStatement.table.relname,
- command: createPolicyStatement.cmd_name,
- usingExpression,
- checkExpression,
- }
-
- return policyInfo
}