@rebasepro/studio 0.27.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchesView-Df00LXAI.js → BranchesView-DqIfywjf.js} +3 -13
- package/dist/BranchesView-DqIfywjf.js.map +1 -0
- package/dist/{CronJobsView-CMNK7eWO.js → CronJobsView-CMa1E-Tx.js} +7 -3
- package/dist/CronJobsView-CMa1E-Tx.js.map +1 -0
- package/dist/{JSEditor-BgGMMbJ-.js → JSEditor-CXffIL9J.js} +2 -2
- package/dist/{JSEditor-BgGMMbJ-.js.map → JSEditor-CXffIL9J.js.map} +1 -1
- package/dist/{MonacoEditor-e9vF1eRi.js → MonacoEditor-7IlHFZU5.js} +21 -4
- package/dist/MonacoEditor-7IlHFZU5.js.map +1 -0
- package/dist/{RLSEditor-DEjuy8XH.js → RLSEditor-DCzA167e.js} +49 -21
- package/dist/RLSEditor-DCzA167e.js.map +1 -0
- package/dist/{SQLEditor-Cb9TIAz6.js → SQLEditor-DrqUDpD8.js} +36 -17
- package/dist/SQLEditor-DrqUDpD8.js.map +1 -0
- package/dist/components/RLSEditor/policyListing.d.ts +11 -0
- package/dist/index.es.js +5 -5
- package/dist/{sql_utils-BZD31xE3.js → sql_utils-DXvmxiCq.js} +20 -2
- package/dist/sql_utils-DXvmxiCq.js.map +1 -0
- package/dist/utils/sql_utils.d.ts +14 -0
- package/package.json +9 -9
- package/dist/BranchesView-Df00LXAI.js.map +0 -1
- package/dist/CronJobsView-CMNK7eWO.js.map +0 -1
- package/dist/MonacoEditor-e9vF1eRi.js.map +0 -1
- package/dist/RLSEditor-DEjuy8XH.js.map +0 -1
- package/dist/SQLEditor-Cb9TIAz6.js.map +0 -1
- package/dist/sql_utils-BZD31xE3.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useModeController } from "@rebasepro/app";
|
|
2
|
-
import { useImperativeHandle, useRef } from "react";
|
|
2
|
+
import { useEffect, useImperativeHandle, useRef } from "react";
|
|
3
3
|
import { cls } from "@rebasepro/ui";
|
|
4
4
|
import { jsx } from "react/jsx-runtime";
|
|
5
5
|
import Editor from "@monaco-editor/react";
|
|
@@ -10,6 +10,10 @@ function selectedTextOf(instance) {
|
|
|
10
10
|
if (!selection || selection.isEmpty()) return void 0;
|
|
11
11
|
return instance.getModel()?.getValueInRange(selection)?.trim() || void 0;
|
|
12
12
|
}
|
|
13
|
+
/** `text` as a regular expression that matches exactly it. */
|
|
14
|
+
function escapeRegExp(text) {
|
|
15
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
16
|
+
}
|
|
13
17
|
var MonacoEditor = ({ ref, value, onChange, onRun, className, readOnly = false, autoFocus = true, schemas }) => {
|
|
14
18
|
const { mode } = useModeController();
|
|
15
19
|
const editorRef = useRef(null);
|
|
@@ -18,6 +22,18 @@ var MonacoEditor = ({ ref, value, onChange, onRun, className, readOnly = false,
|
|
|
18
22
|
onRunRef.current = onRun;
|
|
19
23
|
const schemasRef = useRef(schemas);
|
|
20
24
|
schemasRef.current = schemas;
|
|
25
|
+
/**
|
|
26
|
+
* The completion provider this editor registered. Monaco keeps one
|
|
27
|
+
* language registry for the whole page, so a provider outlives the editor
|
|
28
|
+
* that registered it unless it is disposed: each visit to the console
|
|
29
|
+
* would add another, offering every table and keyword once per visit —
|
|
30
|
+
* the earlier ones from the schemas of the database picked back then.
|
|
31
|
+
*/
|
|
32
|
+
const completionProviderRef = useRef(null);
|
|
33
|
+
useEffect(() => () => {
|
|
34
|
+
completionProviderRef.current?.dispose();
|
|
35
|
+
completionProviderRef.current = null;
|
|
36
|
+
}, []);
|
|
21
37
|
useImperativeHandle(ref, () => ({
|
|
22
38
|
getSelectedText: () => editorRef.current ? selectedTextOf(editorRef.current) : void 0,
|
|
23
39
|
getValue: () => editorRef.current?.getValue()
|
|
@@ -88,7 +104,8 @@ var MonacoEditor = ({ ref, value, onChange, onRun, className, readOnly = false,
|
|
|
88
104
|
"CAST",
|
|
89
105
|
"COALESCE"
|
|
90
106
|
];
|
|
91
|
-
|
|
107
|
+
completionProviderRef.current?.dispose();
|
|
108
|
+
completionProviderRef.current = monaco.languages.registerCompletionItemProvider("pgsql", {
|
|
92
109
|
triggerCharacters: [
|
|
93
110
|
".",
|
|
94
111
|
" ",
|
|
@@ -199,7 +216,7 @@ var MonacoEditor = ({ ref, value, onChange, onRun, className, readOnly = false,
|
|
|
199
216
|
const fullText = model.getValue();
|
|
200
217
|
const activeTables = /* @__PURE__ */ new Set();
|
|
201
218
|
for (const [, tables] of Object.entries(allSchemas)) tables.forEach((table) => {
|
|
202
|
-
if (new RegExp(`\\b${table.tableName}\\b`, "i").test(fullText)) activeTables.add(table.tableName);
|
|
219
|
+
if (new RegExp(`\\b${escapeRegExp(table.tableName)}\\b`, "i").test(fullText)) activeTables.add(table.tableName);
|
|
203
220
|
});
|
|
204
221
|
const addedColumns = /* @__PURE__ */ new Set();
|
|
205
222
|
for (const [, tables] of Object.entries(allSchemas)) tables.forEach((table) => {
|
|
@@ -248,4 +265,4 @@ var MonacoEditor = ({ ref, value, onChange, onRun, className, readOnly = false,
|
|
|
248
265
|
//#endregion
|
|
249
266
|
export { MonacoEditor as t };
|
|
250
267
|
|
|
251
|
-
//# sourceMappingURL=MonacoEditor-
|
|
268
|
+
//# sourceMappingURL=MonacoEditor-7IlHFZU5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MonacoEditor-7IlHFZU5.js","names":[],"sources":["../src/components/SQLEditor/MonacoEditor.tsx"],"sourcesContent":["import React, { useEffect, useImperativeHandle, useRef } from \"react\";\nimport Editor, { Monaco, OnMount } from \"@monaco-editor/react\";\nimport type { editor, Position, IRange } from \"monaco-editor\";\nimport { cls, defaultBorderMixin } from \"@rebasepro/ui\";\nimport { useModeController } from \"@rebasepro/app\";\n\n/**\n * What a host can ask of the editor outside its own key bindings.\n *\n * The toolbar's buttons need the selection that Cmd+Enter already reads: a\n * button that runs the whole buffer while the shortcut beside it runs only the\n * highlighted statement is two answers to one question.\n */\nexport interface MonacoEditorHandle {\n /** The selected text, trimmed — `undefined` when nothing is selected. */\n getSelectedText: () => string | undefined;\n /**\n * The text the editor holds now — `undefined` before it has mounted.\n *\n * A host that acts on the text (Run, Format) reads it here, not from the\n * `value` it last rendered: `onChange` reaches the host's state only when\n * it re-renders, so a Run right after a paste read the text from before it.\n */\n getValue: () => string | undefined;\n}\n\n/** The editor's selection, trimmed — `undefined` when there is none. */\nfunction selectedTextOf(instance: editor.IStandaloneCodeEditor): string | undefined {\n const selection = instance.getSelection();\n if (!selection || selection.isEmpty()) return undefined;\n return instance.getModel()?.getValueInRange(selection)?.trim() || undefined;\n}\n\n/** `text` as a regular expression that matches exactly it. */\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport type MonacoEditorProps = {\n ref?: React.Ref<MonacoEditorHandle>;\n value: string;\n onChange: (value: string | undefined) => void;\n onRun?: (selectedText?: string) => void;\n className?: string;\n readOnly?: boolean;\n autoFocus?: boolean;\n schemas?: Record<string, { schemaName: string, tableName: string, columns: { name: string, dataType: string }[] }[]>;\n};\n\nexport const MonacoEditor = ({\n ref,\n value,\n onChange,\n onRun,\n className,\n readOnly = false,\n autoFocus = true,\n schemas\n}: MonacoEditorProps) => {\n const { mode } = useModeController();\n const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);\n const monacoRef = useRef<Monaco | null>(null);\n const onRunRef = useRef(onRun);\n onRunRef.current = onRun;\n\n const schemasRef = useRef(schemas);\n schemasRef.current = schemas;\n\n /**\n * The completion provider this editor registered. Monaco keeps one\n * language registry for the whole page, so a provider outlives the editor\n * that registered it unless it is disposed: each visit to the console\n * would add another, offering every table and keyword once per visit —\n * the earlier ones from the schemas of the database picked back then.\n */\n const completionProviderRef = useRef<ReturnType<Monaco[\"languages\"][\"registerCompletionItemProvider\"]> | null>(null);\n useEffect(() => () => {\n completionProviderRef.current?.dispose();\n completionProviderRef.current = null;\n }, []);\n\n useImperativeHandle(ref, () => ({\n getSelectedText: () => (editorRef.current ? selectedTextOf(editorRef.current) : undefined),\n getValue: () => editorRef.current?.getValue()\n }), []);\n\n const handleEditorOnMount: OnMount = (editor, monaco) => {\n editorRef.current = editor;\n monacoRef.current = monaco;\n\n editor.addAction({\n id: \"run-query\",\n label: \"Run Query\",\n keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],\n contextMenuGroupId: \"operation\",\n contextMenuOrder: 0,\n run: () => {\n onRunRef.current?.(selectedTextOf(editor));\n }\n });\n\n // Register custom autocomplete for tables, columns, and SQL keywords\n const sqlKeywords = [\n \"SELECT\", \"FROM\", \"WHERE\", \"INSERT INTO\", \"VALUES\", \"UPDATE\", \"SET\",\n \"DELETE FROM\", \"JOIN\", \"INNER JOIN\", \"LEFT JOIN\", \"RIGHT JOIN\", \"FULL JOIN\",\n \"ON\", \"GROUP BY\", \"HAVING\", \"ORDER BY\", \"ASC\", \"DESC\", \"LIMIT\", \"OFFSET\",\n \"AS\", \"AND\", \"OR\", \"NOT\", \"IN\", \"BETWEEN\", \"LIKE\", \"IS NULL\", \"IS NOT NULL\",\n \"CREATE TABLE\", \"ALTER TABLE\", \"DROP TABLE\", \"PRIMARY KEY\", \"FOREIGN KEY\",\n \"COUNT\", \"SUM\", \"AVG\", \"MIN\", \"MAX\", \"DISTINCT\", \"UNION\", \"ALL\", \"EXISTS\",\n \"CASE\", \"WHEN\", \"THEN\", \"ELSE\", \"END\", \"CAST\", \"COALESCE\"\n ];\n\n completionProviderRef.current?.dispose();\n completionProviderRef.current = monaco.languages.registerCompletionItemProvider(\"pgsql\", {\n triggerCharacters: [\".\", \" \", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"],\n provideCompletionItems: (model: editor.ITextModel, position: Position) => {\n const word = model.getWordUntilPosition(position);\n const range = {\n startLineNumber: position.lineNumber,\n endLineNumber: position.lineNumber,\n startColumn: word.startColumn,\n endColumn: word.endColumn\n };\n\n const textUntilPosition = model.getValueInRange({\n startLineNumber: position.lineNumber,\n startColumn: 1,\n endLineNumber: position.lineNumber,\n endColumn: position.column\n });\n\n // Check if user is typing `tableName.`\n const match = textUntilPosition.match(/([a-zA-Z0-9_]+)\\.$/);\n const tableNameMatch = match ? match[1] : null;\n\n const suggestions: { label: string; kind: number; insertText: string; range: IRange; detail: string; sortText: string }[] = [];\n const allSchemas = schemasRef.current || {};\n\n if (tableNameMatch) {\n // Provide columns for the matched table\n for (const [, tables] of Object.entries(allSchemas)) {\n const table = tables.find(t => t.tableName === tableNameMatch);\n if (table) {\n table.columns.forEach(col => {\n suggestions.push({\n label: col.name,\n kind: monaco.languages.CompletionItemKind.Field,\n insertText: col.name,\n range,\n detail: \"Column\",\n sortText: \"1\"\n });\n });\n }\n }\n } else {\n // Provide table names\n for (const [sName, tables] of Object.entries(allSchemas)) {\n tables.forEach(table => {\n suggestions.push({\n label: table.tableName,\n kind: monaco.languages.CompletionItemKind.Class,\n insertText: table.tableName,\n range,\n detail: `Table (${sName})`,\n sortText: \"2\"\n });\n });\n }\n\n // Provide SQL keywords\n sqlKeywords.forEach(keyword => {\n suggestions.push({\n label: keyword,\n kind: monaco.languages.CompletionItemKind.Keyword,\n insertText: keyword + \" \",\n range,\n detail: \"SQL Keyword\",\n sortText: \"3\"\n });\n });\n\n // Heuristic: Suggest columns for tables that are mentioned in the current editor text\n const fullText = model.getValue();\n const activeTables = new Set<string>();\n for (const [, tables] of Object.entries(allSchemas)) {\n tables.forEach(table => {\n // The name is text to find, not a pattern: a `[` or `(`\n // in it would throw, and take every suggestion with it.\n const regex = new RegExp(`\\\\b${escapeRegExp(table.tableName)}\\\\b`, \"i\");\n if (regex.test(fullText)) {\n activeTables.add(table.tableName);\n }\n });\n }\n\n const addedColumns = new Set<string>();\n for (const [, tables] of Object.entries(allSchemas)) {\n tables.forEach(table => {\n if (activeTables.has(table.tableName)) {\n table.columns.forEach(col => {\n if (!addedColumns.has(col.name)) {\n addedColumns.add(col.name);\n suggestions.push({\n label: col.name,\n kind: monaco.languages.CompletionItemKind.Field,\n insertText: col.name,\n range,\n detail: `Column (${table.tableName})`,\n sortText: \"1\" // Prioritize columns from active tables\n });\n }\n });\n }\n });\n }\n }\n\n return { suggestions };\n\n }\n });\n\n if (autoFocus) {\n editor.focus();\n }\n };\n\n return (\n <div className={cls(\"relative w-full h-full overflow-hidden\", className)}>\n <Editor\n height=\"100%\"\n defaultLanguage=\"pgsql\"\n value={value}\n onChange={onChange}\n onMount={handleEditorOnMount}\n theme={mode === \"dark\" ? \"vs-dark\" : \"vs\"}\n options={{\n minimap: { enabled: false },\n fontSize: 14,\n lineNumbers: \"on\",\n scrollBeyondLastLine: false,\n automaticLayout: true,\n readOnly,\n tabSize: 2,\n wordWrap: \"on\"\n }}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;AA2BA,SAAS,eAAe,UAA4D;CAChF,MAAM,YAAY,SAAS,aAAa;CACxC,IAAI,CAAC,aAAa,UAAU,QAAQ,GAAG,OAAO,KAAA;CAC9C,OAAO,SAAS,SAAS,CAAC,EAAE,gBAAgB,SAAS,CAAC,EAAE,KAAK,KAAK,KAAA;AACtE;;AAGA,SAAS,aAAa,MAAsB;CACxC,OAAO,KAAK,QAAQ,uBAAuB,MAAM;AACrD;AAaA,IAAa,gBAAgB,EACzB,KACA,OACA,UACA,OACA,WACA,WAAW,OACX,YAAY,MACZ,cACqB;CACrB,MAAM,EAAE,SAAS,kBAAkB;CACnC,MA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
|
+
import { o as quoteIdentifier } from "./sql_utils-DXvmxiCq.js";
|
|
2
|
+
import { t as MonacoEditor } from "./MonacoEditor-7IlHFZU5.js";
|
|
2
3
|
import { ConfirmationDialog, ErrorView, useApiBase, useApiConfig, useRebaseContext, useSnackbarController, useStudioCapabilities, useStudioCollectionRegistry, useStudioSchemaEditing, useTranslation } from "@rebasepro/app";
|
|
3
4
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
4
5
|
import { Alert, AlertTriangleIcon, Button, Chip, CircularProgress, DatabaseIcon, Dialog, DialogActions, DialogContent, DialogTitle, HelpCircleIcon, IconButton, KeyIcon, Link2Icon, LockIcon, MultiSelect, MultiSelectItem, Paper, RefreshCwIcon, ResizablePanels, Select, SelectItem, ShieldIcon, Tab, Tabs, TextField, Tooltip, Trash2Icon, Typography, cls, defaultBorderMixin, iconSize } from "@rebasepro/ui";
|
|
@@ -856,6 +857,45 @@ function sameRoles$1(a, b) {
|
|
|
856
857
|
}
|
|
857
858
|
//#endregion
|
|
858
859
|
//#region src/components/RLSEditor/policyListing.ts
|
|
860
|
+
/**
|
|
861
|
+
* The roles of a `pg_policies` row, from its `roles` column.
|
|
862
|
+
*
|
|
863
|
+
* A driver hands a `name[]` back as an array or as Postgres's text for one:
|
|
864
|
+
* `{public}`, `{anon,authenticated}`, and with an element quoted — a `"` or
|
|
865
|
+
* `\` in it escaped by a backslash — when it holds a comma, a brace, a quote,
|
|
866
|
+
* a backslash or a space: `{"my role",anon}`. Split on commas, that last one
|
|
867
|
+
* reads as the role `"my role"`, quotes and all: the policy shows drift that
|
|
868
|
+
* is not there, and an edit of it names a role that does not exist.
|
|
869
|
+
*/
|
|
870
|
+
function readPolicyRoles(value) {
|
|
871
|
+
if (Array.isArray(value)) return value.filter((role) => typeof role === "string");
|
|
872
|
+
if (typeof value !== "string") return [];
|
|
873
|
+
const body = value.trim().replace(/^\{/, "").replace(/\}$/, "");
|
|
874
|
+
const roles = [];
|
|
875
|
+
let i = 0;
|
|
876
|
+
while (i < body.length) {
|
|
877
|
+
if (body[i] === "\"") {
|
|
878
|
+
let role = "";
|
|
879
|
+
i++;
|
|
880
|
+
while (i < body.length && body[i] !== "\"") {
|
|
881
|
+
if (body[i] === "\\") i++;
|
|
882
|
+
role += body[i] ?? "";
|
|
883
|
+
i++;
|
|
884
|
+
}
|
|
885
|
+
roles.push(role);
|
|
886
|
+
i++;
|
|
887
|
+
} else {
|
|
888
|
+
const comma = body.indexOf(",", i);
|
|
889
|
+
const end = comma === -1 ? body.length : comma;
|
|
890
|
+
const role = body.slice(i, end).trim();
|
|
891
|
+
if (role) roles.push(role);
|
|
892
|
+
i = end;
|
|
893
|
+
}
|
|
894
|
+
while (i < body.length && body[i] !== ",") i++;
|
|
895
|
+
i++;
|
|
896
|
+
}
|
|
897
|
+
return roles;
|
|
898
|
+
}
|
|
859
899
|
var COMMANDS = {
|
|
860
900
|
select: "SELECT",
|
|
861
901
|
insert: "INSERT",
|
|
@@ -996,15 +1036,6 @@ function classifyTableClient(tableName, schemaName, junctionTableNames, isMapped
|
|
|
996
1036
|
if (junctionTableNames.has(tableName)) return "junction";
|
|
997
1037
|
return "other";
|
|
998
1038
|
}
|
|
999
|
-
/**
|
|
1000
|
-
* Validates and double-quotes a SQL identifier to prevent injection.
|
|
1001
|
-
* Only allows safe Postgres identifiers (letters, digits, underscores).
|
|
1002
|
-
* Throws if the identifier contains unsafe characters.
|
|
1003
|
-
*/
|
|
1004
|
-
function sanitizeSqlIdentifier(name) {
|
|
1005
|
-
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) throw new Error(`Invalid SQL identifier: "${name}". Only letters, digits, and underscores are allowed.`);
|
|
1006
|
-
return `"${name}"`;
|
|
1007
|
-
}
|
|
1008
1039
|
function SidebarSection({ title, icon, expanded, onToggle, count, children }) {
|
|
1009
1040
|
return /* @__PURE__ */ jsxs("div", {
|
|
1010
1041
|
className: "mb-2",
|
|
@@ -1121,7 +1152,7 @@ var RLSEditor = ({ apiUrl = "" }) => {
|
|
|
1121
1152
|
const action = enabled ? "DISABLE" : "ENABLE";
|
|
1122
1153
|
setConfirming(true);
|
|
1123
1154
|
try {
|
|
1124
|
-
await databaseAdmin.executeSql(`ALTER TABLE ${
|
|
1155
|
+
await databaseAdmin.executeSql(`ALTER TABLE ${quoteIdentifier(schema)}.${quoteIdentifier(table)} ${action} ROW LEVEL SECURITY`);
|
|
1125
1156
|
snackbarController.open({
|
|
1126
1157
|
type: "success",
|
|
1127
1158
|
message: `RLS ${action.toLowerCase()}d on ${table}`
|
|
@@ -1146,7 +1177,7 @@ var RLSEditor = ({ apiUrl = "" }) => {
|
|
|
1146
1177
|
const { policyName, table, schema } = confirmDropPolicy;
|
|
1147
1178
|
setConfirming(true);
|
|
1148
1179
|
try {
|
|
1149
|
-
await databaseAdmin.executeSql(`DROP POLICY ${
|
|
1180
|
+
await databaseAdmin.executeSql(`DROP POLICY ${quoteIdentifier(policyName)} ON ${quoteIdentifier(schema)}.${quoteIdentifier(table)}`);
|
|
1150
1181
|
snackbarController.open({
|
|
1151
1182
|
type: "success",
|
|
1152
1183
|
message: `Policy "${policyName}" dropped`
|
|
@@ -1269,10 +1300,7 @@ var RLSEditor = ({ apiUrl = "" }) => {
|
|
|
1269
1300
|
const table = p.tablename || p.TABLENAME || "";
|
|
1270
1301
|
const key = `${schema}.${table}`;
|
|
1271
1302
|
if (tableMap[key]) {
|
|
1272
|
-
|
|
1273
|
-
const r = p.roles || p.ROLES;
|
|
1274
|
-
if (Array.isArray(r)) parsedRoles = r;
|
|
1275
|
-
else if (typeof r === "string") parsedRoles = r.replace(/^{|}$/g, "").split(",").map((s) => s.trim());
|
|
1303
|
+
const parsedRoles = readPolicyRoles(p.roles || p.ROLES);
|
|
1276
1304
|
tableMap[key].policies.push({
|
|
1277
1305
|
policyname: p.policyname || p.POLICYNAME || "",
|
|
1278
1306
|
tablename: table,
|
|
@@ -1795,18 +1823,18 @@ var RLSEditor = ({ apiUrl = "" }) => {
|
|
|
1795
1823
|
return;
|
|
1796
1824
|
}
|
|
1797
1825
|
try {
|
|
1798
|
-
const qualifiedTable = `${
|
|
1799
|
-
const policyName =
|
|
1826
|
+
const qualifiedTable = `${quoteIdentifier(activeTableData.schemaName)}.${quoteIdentifier(activeTableData.tableName)}`;
|
|
1827
|
+
const policyName = quoteIdentifier(newPolicy.policyname || "unnamed_policy");
|
|
1800
1828
|
const cmd = newPolicy.cmd || "ALL";
|
|
1801
1829
|
const permissive = (newPolicy.permissive || "PERMISSIVE") === "PERMISSIVE" ? "PERMISSIVE" : "RESTRICTIVE";
|
|
1802
|
-
const roles = newPolicy.roles && newPolicy.roles.length > 0 ? newPolicy.roles.map((r) =>
|
|
1830
|
+
const roles = newPolicy.roles && newPolicy.roles.length > 0 ? newPolicy.roles.map((r) => quoteIdentifier(r)).join(", ") : "public";
|
|
1803
1831
|
let sql = `CREATE POLICY ${policyName} ON ${qualifiedTable}`;
|
|
1804
1832
|
sql += ` AS ${permissive}`;
|
|
1805
1833
|
sql += ` FOR ${cmd}`;
|
|
1806
1834
|
sql += ` TO ${roles}`;
|
|
1807
1835
|
if (newPolicy.qual) sql += ` USING (${newPolicy.qual})`;
|
|
1808
1836
|
if (newPolicy.with_check) sql += ` WITH CHECK (${newPolicy.with_check})`;
|
|
1809
|
-
if (editingPolicy !== "new") sql = `DROP POLICY IF EXISTS ${
|
|
1837
|
+
if (editingPolicy !== "new") sql = `DROP POLICY IF EXISTS ${quoteIdentifier(editingPolicy.policyname)} ON ${qualifiedTable}; ${sql}`;
|
|
1810
1838
|
await databaseAdmin.executeSql(sql);
|
|
1811
1839
|
snackbarController.open({
|
|
1812
1840
|
type: "success",
|
|
@@ -2095,4 +2123,4 @@ var RLSEditor = ({ apiUrl = "" }) => {
|
|
|
2095
2123
|
//#endregion
|
|
2096
2124
|
export { RLSEditor };
|
|
2097
2125
|
|
|
2098
|
-
//# sourceMappingURL=RLSEditor-
|
|
2126
|
+
//# sourceMappingURL=RLSEditor-DCzA167e.js.map
|