GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add Query Tool result export enhancements. · dpage/pgadmin4@19151a0

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs/en_US
    • preferences.rst
    • query_tool_toolbar.rst
  • web/pgadmin
    • tools/sqleditor
      • __init__.py
      • static/js/components/sections
        • ResultSet.jsx
        • ResultSetToolbar.jsx
      • tests
        • test_download_csv_query_tool.py
      • utils
        • query_tool_preferences.py
    • utils/driver/psycopg3
      • connection.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/en_US/preferences.rst‎

Copy file name to clipboardExpand all lines: docs/en_US/preferences.rst
+10Lines changed: 10 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,13 @@ Use the fields on the *CSV/TXT Output* panel to control the CSV/TXT output.
589589
quoted in the CSV/TXT output; select *Strings*, *All*, or *None*.
590590
* Use the *Replace null values with* option to replace null values with
591591
specified string in the output file. Default is set to 'NULL'.
592+
* Use the *Output file encoding* drop-down listbox to specify the character
593+
encoding used when saving query results to a file. The default is utf-8; an
594+
encoding that is not listed can also be typed in.
595+
* Use the *Add byte order mark (BOM)?* switch to add a byte order mark at the
596+
start of the saved file when a UTF encoding is used. This helps applications
597+
such as Microsoft Excel detect the encoding correctly. This applies to the
598+
CSV/TXT output only.
592599

593600
.. image:: images/preferences_sql_display.png
594601
:alt: Preferences sqleditor display options
@@ -754,6 +761,9 @@ preferences for copied data.
754761
character for copied data.
755762
* Use the *Result copy quoting* drop-down listbox to select which type of fields
756763
require quoting; select *All*, *None*, or *Strings*.
764+
* When the *Copy with headers?* switch is set to true, the column headers are
765+
included by default when copying data from the results grid. This can still
766+
be toggled per-copy from the results grid copy options menu.
757767
* When the *Striped rows?* switch is set to true, the result grid will display
758768
rows with alternating background colors.
759769

Collapse file

‎docs/en_US/query_tool_toolbar.rst‎

Copy file name to clipboardExpand all lines: docs/en_US/query_tool_toolbar.rst
+6-4Lines changed: 6 additions & 4 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,12 @@ Data Editing Options
210210
| *Save Data Changes* | Click the *Save Data Changes* icon to save data changes (insert, update, or delete) in the Data | F6 |
211211
| | Output Panel to the server. | |
212212
+----------------------+---------------------------------------------------------------------------------------------------+----------------+
213-
| *Save results to* | Click the Save results to file icon to save the result set of the current query as a delimited | F8 |
214-
| *file* | text file (CSV, if the field separator is set to a comma). This button will only be enabled when | |
215-
| | a query has been executed and there are results in the data grid. You can specify the CSV/TXT | |
216-
| | settings in the Preference Dialogue under SQL Editor -> CSV/TXT output. | |
213+
| *Save results to* | Click the Save results to file icon to save the result set of the current query. By | F8 |
214+
| *file* | default it is saved as a delimited text file (CSV, if the field separator is set to a | |
215+
| | comma). Use the adjacent drop-down list to instead save the results as JSON or XML. | |
216+
| | This button is only enabled when a query has been executed and there are results in | |
217+
| | the data grid. You can specify the CSV/TXT settings (including the output file encoding | |
218+
| | and byte order mark) in the Preferences dialog under Query Tool -> CSV/TXT Output. | |
217219
+----------------------+---------------------------------------------------------------------------------------------------+----------------+
218220
| Graph Visualiser | Use the Graph Visualiser button to generate graphs of the query results. | |
219221
+----------------------+---------------------------------------------------------------------------------------------------+----------------+
Collapse file

‎web/pgadmin/tools/sqleditor/__init__.py‎

Copy file name to clipboardExpand all lines: web/pgadmin/tools/sqleditor/__init__.py
+49-10Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2179,20 +2179,59 @@ def start_query_download_tool(trans_id):
21792179
}
21802180
)
21812181

2182+
# Output format: csv (default), json or xml.
2183+
data_format = (data.get('format') or 'csv').lower()
2184+
if data_format not in ('csv', 'json', 'xml'):
2185+
data_format = 'csv'
2186+
2187+
# Encoding and BOM apply to the CSV/text output only; the structured
2188+
# formats are always emitted as UTF-8.
2189+
if data_format == 'csv':
2190+
output_encoding = blueprint.csv_output_encoding.get() or 'utf-8'
2191+
add_bom = blueprint.csv_add_bom.get()
2192+
else:
2193+
output_encoding = 'utf-8'
2194+
add_bom = False
2195+
is_utf = output_encoding.lower().replace('-', '').replace(
2196+
'_', '').startswith('utf')
2197+
2198+
str_gen = gen(conn_obj,
2199+
trans_obj,
2200+
quote=blueprint.csv_quoting.get(),
2201+
quote_char=blueprint.csv_quote_char.get(),
2202+
field_separator=blueprint.csv_field_separator.get(),
2203+
replace_nulls_with=blueprint.replace_nulls_with.get(),
2204+
data_format=data_format)
2205+
2206+
def encoded_gen(text_gen):
2207+
is_first_chunk = True
2208+
for chunk in text_gen:
2209+
if is_first_chunk:
2210+
is_first_chunk = False
2211+
if add_bom and is_utf:
2212+
chunk = '\ufeff' + chunk
2213+
yield chunk.encode(output_encoding, errors='replace')
2214+
2215+
if data_format == 'json':
2216+
base_mimetype = 'application/json'
2217+
elif data_format == 'xml':
2218+
base_mimetype = 'application/xml'
2219+
elif blueprint.csv_field_separator.get() == ',':
2220+
base_mimetype = 'text/csv'
2221+
else:
2222+
base_mimetype = 'text/plain'
2223+
21822224
r = Response(
2183-
gen(conn_obj,
2184-
trans_obj,
2185-
quote=blueprint.csv_quoting.get(),
2186-
quote_char=blueprint.csv_quote_char.get(),
2187-
field_separator=blueprint.csv_field_separator.get(),
2188-
replace_nulls_with=blueprint.replace_nulls_with.get()),
2189-
mimetype='text/csv' if
2190-
blueprint.csv_field_separator.get() == ','
2191-
else 'text/plain'
2225+
encoded_gen(str_gen),
2226+
mimetype='{0}; charset={1}'.format(base_mimetype, output_encoding)
21922227
)
21932228

21942229
import time
2195-
extn = 'csv' if blueprint.csv_field_separator.get() == ',' else 'txt'
2230+
if data_format == 'csv':
2231+
extn = 'csv' if blueprint.csv_field_separator.get() == ',' \
2232+
else 'txt'
2233+
else:
2234+
extn = data_format
21962235
filename = data['filename'] if data.get('filename', '') != "" else \
21972236
'{0}.{1}'.format(int(time.time()), extn)
21982237

Collapse file

‎web/pgadmin/tools/sqleditor/static/js/components/sections/ResultSet.jsx‎

Copy file name to clipboardExpand all lines: web/pgadmin/tools/sqleditor/static/js/components/sections/ResultSet.jsx
+8-6Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -476,16 +476,17 @@ export class ResultSetUtils {
476476
});
477477
}
478478

479-
async saveResultsToFile(fileName, onProgress) {
479+
async saveResultsToFile(fileName, onProgress, dataFormat='csv') {
480+
const mimeTypes = {csv: 'text/csv', json: 'application/json', xml: 'application/xml'};
480481
try {
481482
await DownloadUtils.downloadFileStream({
482483
url: url_for('sqleditor.query_tool_download', {
483484
'trans_id': this.transId,
484485
}),
485486
options: {
486487
method: 'POST',
487-
body: JSON.stringify({filename: fileName, query_commited: this.hasQueryCommitted})
488-
}}, fileName, 'text/csv', onProgress);
488+
body: JSON.stringify({filename: fileName, query_commited: this.hasQueryCommitted, format: dataFormat})
489+
}}, fileName, mimeTypes[dataFormat] ?? 'text/csv', onProgress);
489490
this.eventBus.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_SAVE_RESULTS_END);
490491
} catch (error) {
491492
this.eventBus.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_SAVE_RESULTS_END);
@@ -1052,16 +1053,17 @@ export function ResultSet() {
10521053
setLoaderText(null);
10531054
});
10541055

1055-
eventBus.registerListener(QUERY_TOOL_EVENTS.TRIGGER_SAVE_RESULTS, async ()=>{
1056-
let extension = queryToolCtx.preferences?.sqleditor?.csv_field_separator === ',' ? '.csv': '.txt';
1056+
eventBus.registerListener(QUERY_TOOL_EVENTS.TRIGGER_SAVE_RESULTS, async (dataFormat='csv')=>{
1057+
const csvExtension = queryToolCtx.preferences?.sqleditor?.csv_field_separator === ',' ? '.csv': '.txt';
1058+
let extension = {csv: csvExtension, json: '.json', xml: '.xml'}[dataFormat] ?? csvExtension;
10571059
let fileName = 'data-' + new Date().getTime() + extension;
10581060
if(!queryToolCtx.params.is_query_tool) {
10591061
fileName = queryToolCtx.params.node_name + extension;
10601062
}
10611063
setLoaderText(gettext('Downloading results...'));
10621064
await rsu.current.saveResultsToFile(fileName, (p)=>{
10631065
setLoaderText(gettext('Downloading results(%s)...', p));
1064-
});
1066+
}, dataFormat);
10651067
setLoaderText('');
10661068
});
10671069

Collapse file

‎web/pgadmin/tools/sqleditor/static/js/components/sections/ResultSetToolbar.jsx‎

Copy file name to clipboardExpand all lines: web/pgadmin/tools/sqleditor/static/js/components/sections/ResultSetToolbar.jsx
+25-3Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@ export function ResultSetToolbar({query, canEdit, totalRowCount, pagination, all
282282
/* Menu button refs */
283283
const copyMenuRef = React.useRef(null);
284284
const pasetMenuRef = React.useRef(null);
285+
const downloadMenuRef = React.useRef(null);
285286

286287
const queryToolPref = queryToolCtx.preferences.sqleditor;
287288

@@ -309,8 +310,8 @@ export function ResultSetToolbar({query, canEdit, totalRowCount, pagination, all
309310
const addRow = useCallback(()=>{
310311
eventBus.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_ADD_ROWS, [[]], {isNewRow: true});
311312
}, []);
312-
const downloadResult = useCallback(()=>{
313-
eventBus.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_SAVE_RESULTS);
313+
const downloadResult = useCallback((fmt='csv')=>{
314+
eventBus.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_SAVE_RESULTS, fmt);
314315
}, []);
315316
const showGraphVisualiser = useCallback(()=>{
316317
eventBus.fireEvent(QUERY_TOOL_EVENTS.TRIGGER_GRAPH_VISUALISER);
@@ -348,6 +349,14 @@ export function ResultSetToolbar({query, canEdit, totalRowCount, pagination, all
348349
setDisableButton('save-result', (totalRowCount||0) < 1);
349350
}, [totalRowCount]);
350351

352+
useEffect(()=>{
353+
// Seed the "Copy with headers" toggle default from the user preference.
354+
setCheckedMenuItems((prev)=>({
355+
...prev,
356+
copy_with_headers: queryToolPref.copy_column_headers,
357+
}));
358+
}, [queryToolPref.copy_column_headers]);
359+
351360
useEffect(()=>{
352361
eventBus.registerListener(QUERY_TOOL_EVENTS.TRIGGER_COPY_DATA, copyData);
353362
return ()=>eventBus.deregisterListener(QUERY_TOOL_EVENTS.TRIGGER_COPY_DATA, copyData);
@@ -432,7 +441,10 @@ export function ResultSetToolbar({query, canEdit, totalRowCount, pagination, all
432441
</PgButtonGroup>
433442
<PgButtonGroup size="small">
434443
<PgIconButton title={gettext('Save results to file')} icon={<GetAppRoundedIcon />}
435-
onClick={downloadResult} shortcut={queryToolPref.download_results}
444+
onClick={()=>downloadResult('csv')} shortcut={queryToolPref.download_results}
445+
disabled={buttonsDisabled['save-result']} />
446+
<PgIconButton title={gettext('Save results options')} icon={<KeyboardArrowDownIcon />} splitButton
447+
name="menu-downloadoptions" ref={downloadMenuRef} onClick={openMenu}
436448
disabled={buttonsDisabled['save-result']} />
437449
</PgButtonGroup>
438450
<PgButtonGroup size="small">
@@ -490,6 +502,16 @@ export function ResultSetToolbar({query, canEdit, totalRowCount, pagination, all
490502
>
491503
<PgMenuItem hasCheck value="paste_with_serials" checked={checkedMenuItems['paste_with_serials']} onClick={checkMenuClick}>{gettext('Paste with SERIAL/IDENTITY values?')}</PgMenuItem>
492504
</PgMenu>
505+
<PgMenu
506+
anchorRef={downloadMenuRef}
507+
open={menuOpenId=='menu-downloadoptions'}
508+
onClose={handleMenuClose}
509+
label={gettext('Save Results Options Menu')}
510+
>
511+
<PgMenuItem onClick={()=>downloadResult('csv')}>{gettext('Save as CSV/Text')}</PgMenuItem>
512+
<PgMenuItem onClick={()=>downloadResult('json')}>{gettext('Save as JSON')}</PgMenuItem>
513+
<PgMenuItem onClick={()=>downloadResult('xml')}>{gettext('Save as XML')}</PgMenuItem>
514+
</PgMenu>
493515
</>
494516
);
495517
}
Collapse file

‎web/pgadmin/tools/sqleditor/tests/test_download_csv_query_tool.py‎

Copy file name to clipboardExpand all lines: web/pgadmin/tools/sqleditor/tests/test_download_csv_query_tool.py
+130Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,3 +240,133 @@ def tearDown(self):
240240
self.server['sslmode']
241241
)
242242
test_utils.drop_database(main_conn, self._db_name)
243+
244+
245+
class TestDownloadResultFormats(BaseTestGenerator):
246+
"""
247+
Validates downloading query results as JSON and XML, the UTF BOM option
248+
and the output file encoding option.
249+
"""
250+
SQL = 'SELECT 1 as "A", 2 as "B", \'x\' as "C"'
251+
INIT_URL = '/sqleditor/initialize/sqleditor/{0}/{1}/{2}/{3}'
252+
DOWNLOAD_URL = '/sqleditor/query_tool/download/{0}'
253+
254+
scenarios = [
255+
(
256+
'Download results as JSON',
257+
dict(data_format='json', add_bom=False, encoding='utf-8',
258+
expected_content_type='application/json',
259+
expected_extension='.json')
260+
),
261+
(
262+
'Download results as XML',
263+
dict(data_format='xml', add_bom=False, encoding='utf-8',
264+
expected_content_type='application/xml',
265+
expected_extension='.xml')
266+
),
267+
(
268+
'Download CSV with a UTF BOM',
269+
dict(data_format='csv', add_bom=True, encoding='utf-8',
270+
expected_content_type='text/csv',
271+
expected_extension='.csv')
272+
),
273+
(
274+
'Download CSV with a non-UTF output encoding',
275+
dict(data_format='csv', add_bom=True, encoding='latin-1',
276+
expected_content_type='text/csv',
277+
expected_extension='.csv')
278+
),
279+
]
280+
281+
def setUp(self):
282+
self._db_name = 'download_results_fmt_' + str(
283+
secrets.choice(range(10000, 65535)))
284+
self._sid = self.server_information['server_id']
285+
server_utils.connect_server(self, self._sid)
286+
self._did = test_utils.create_database(self.server, self._db_name)
287+
288+
def initiate_sql_query_tool(self, trans_id, sql_query):
289+
url = '/sqleditor/query_tool/start/{0}'.format(trans_id)
290+
response = self.tester.post(url, data=json.dumps({"sql": sql_query}),
291+
content_type='html/json')
292+
self.assertEqual(response.status_code, 200)
293+
return async_poll(tester=self.tester,
294+
poll_url='/sqleditor/poll/{0}'.format(trans_id))
295+
296+
def runTest(self):
297+
db_con = database_utils.connect_database(self,
298+
test_utils.SERVER_GROUP,
299+
self._sid,
300+
self._did)
301+
if not db_con["info"] == "Database connected.":
302+
raise Exception("Could not connect to the database.")
303+
304+
self.trans_id = str(secrets.choice(range(1, 9999999)))
305+
url = self.INIT_URL.format(
306+
self.trans_id, test_utils.SERVER_GROUP, self._sid, self._did)
307+
response = self.tester.post(url, data=json.dumps({
308+
"dbname": self._db_name
309+
}))
310+
self.assertEqual(response.status_code, 200)
311+
312+
self.initiate_sql_query_tool(self.trans_id, self.SQL)
313+
314+
url = self.DOWNLOAD_URL.format(self.trans_id)
315+
self.app.logger.disabled = True
316+
filename = 'test{0}'.format(self.expected_extension)
317+
with patch('pgadmin.tools.sqleditor.blueprint.'
318+
'csv_add_bom.get', return_value=self.add_bom), \
319+
patch('pgadmin.tools.sqleditor.blueprint.'
320+
'csv_output_encoding.get', return_value=self.encoding):
321+
response = self.tester.post(url, data={
322+
"query": self.SQL,
323+
"filename": filename,
324+
"format": self.data_format,
325+
"query_commited": True,
326+
})
327+
self.app.logger.disabled = False
328+
329+
headers = dict(response.headers)
330+
self.assertEqual(response.status_code, 200)
331+
self.assertIn(self.expected_content_type, headers['Content-Type'])
332+
self.assertIn('charset={0}'.format(self.encoding),
333+
headers['Content-Type'])
334+
self.assertIn(filename, headers['Content-Disposition'])
335+
336+
raw = response.data
337+
if self.add_bom and self.encoding.lower().startswith('utf'):
338+
self.assertTrue(raw.startswith(b'\xef\xbb\xbf'))
339+
else:
340+
self.assertFalse(raw.startswith(b'\xef\xbb\xbf'))
341+
342+
body = raw.decode(self.encoding)
343+
344+
if self.data_format == 'json':
345+
parsed = json.loads(body)
346+
self.assertIsInstance(parsed, list)
347+
self.assertEqual(parsed[0]['A'], 1)
348+
self.assertEqual(parsed[0]['B'], 2)
349+
self.assertEqual(parsed[0]['C'], 'x')
350+
elif self.data_format == 'xml':
351+
self.assertIn('<data_output>', body)
352+
self.assertIn('<column name="A">1</column>', body)
353+
self.assertIn('<column name="C">x</column>', body)
354+
self.assertIn('</data_output>', body)
355+
else:
356+
self.assertIn('"A","B","C"', body)
357+
358+
url = '/sqleditor/close/{0}'.format(self.trans_id)
359+
response = self.tester.delete(url)
360+
self.assertEqual(response.status_code, 200)
361+
database_utils.disconnect_database(self, self._sid, self._did)
362+
363+
def tearDown(self):
364+
main_conn = test_utils.get_db_connection(
365+
self.server['db'],
366+
self.server['username'],
367+
self.server['db_password'],
368+
self.server['host'],
369+
self.server['port'],
370+
self.server['sslmode']
371+
)
372+
test_utils.drop_database(main_conn, self._db_name)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.