casacore
Loading...
Searching...
No Matches
TableParseQuery.h
Go to the documentation of this file.
1// # TableParseQuery.h: Class getting the parser results and executing a query
2// # Copyright (C) 1994-2022
3// # Associated Universities, Inc. Washington DC, USA.
4// #
5// # This library is free software; you can redistribute it and/or modify it
6// # under the terms of the GNU Library General Public License as published by
7// # the Free Software Foundation; either version 2 of the License, or (at your
8// # option) any later version.
9// #
10// # This library is distributed in the hope that it will be useful, but WITHOUT
11// # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12// # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
13// # License for more details.
14// #
15// # You should have received a copy of the GNU Library General Public License
16// # along with this library; if not, write to the Free Software Foundation,
17// # Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
18// #
19// # Correspondence concerning AIPS++ should be addressed as follows:
20// # Internet email: casa-feedback@nrao.edu.
21// # Postal address: AIPS++ Project Office
22// # National Radio Astronomy Observatory
23// # 520 Edgemont Road
24// # Charlottesville, VA 22903-2475 USA
25
26#ifndef TABLES_TABLEPARSEQUERY_H
27#define TABLES_TABLEPARSEQUERY_H
28
29// # Includes
30#include <casacore/casa/aips.h>
31#include <casacore/tables/TaQL/TableParseTableList.h>
32#include <casacore/tables/TaQL/TableParseJoin.h>
33#include <casacore/tables/TaQL/TableParseProject.h>
34#include <casacore/tables/TaQL/TableParseUpdate.h>
35#include <casacore/tables/TaQL/TableParseSortKey.h>
36#include <casacore/tables/TaQL/TableParseGroupby.h>
37#include <casacore/tables/Tables/Table.h>
38#include <casacore/tables/TaQL/ExprNode.h>
39#include <casacore/tables/TaQL/ExprGroup.h>
40#include <casacore/casa/Arrays/ArrayFwd.h>
41#include <casacore/casa/BasicSL/String.h>
42#include <casacore/casa/Utilities/Sort.h>
43#include <casacore/casa/Containers/Block.h>
44#include <vector>
45
46namespace casacore { // # NAMESPACE CASACORE - BEGIN
47
48// # Forward Declarations
52class TableDesc;
53class TableColumn;
54class AipsIO;
55class Record;
56class TableRecord;
57template <class T>
58class ArrayColumn;
59
60// <summary>
61// Class getting the parser results and executing a query
62// </summary>
63
64// <use visibility=local>
65
66// <reviewed reviewer="UNKNOWN" date="before2004/08/25" tests="">
67// </reviewed>
68
69// <prerequisite>
70// # Classes you should understand before using this one.
71// <li> TableGram.ll and .yy (flex and bison grammar)
72// <li> TaQLNodeHandler
73// </prerequisite>
74
75// <synopsis>
76// The results of the bison parser TableGram.yy and flex scanner TableGram.ll
77// are stored in a tree of TaQLNode objects. When the parsing of a TaQL command
78// is fully done, the tree is traversed by TaQLNodeHandler which creates and
79// fills a stack of TableParseQuery objects, one object per (nested) query.
80// A nested query is executed once it is fully handled.
81// </synopsis>
82
83// <motivation>
84// It is necessary to be able to give a table select command in ASCII.
85// This can be used in a CLI or in the table browser to get a subset
86// of a table or to sort a table.
87// </motivation>
88
89// # <todo asof="$DATE:$">
90// # A List of bugs, limitations, extensions or planned refinements.
91// # </todo>
92
94 public:
107
108 // Construct.
110
111 // Destructor.
113
114 // Return the command type.
116
117 // Return the expression node.
118 TableExprNode getNode() const { return node_p; }
119
120 // Return the table name list.
122
124
125 // Execute the select command (select/sort/projection/groupby/having/giving).
126 // The setInGiving flag tells if a set in the GIVING part is allowed.
127 // The mustSelect flag tells if a SELECT command must do something.
128 // Usually that is required, but not for a SELECT in an INSERT command.
129 // Optionally the maximum nr of rows to be selected can be given.
130 // It will be used as the default value for the LIMIT clause.
131 // 0 = no maximum.
132 void execute(Bool showTimings, Bool setInGiving, Bool mustSelect, rownr_t maxRow,
133 Bool doTracing = False,
134 const std::vector<const Table*>& tempTables = std::vector<const Table*>(),
135 const std::vector<TableParseQuery*>& stack = std::vector<TableParseQuery*>());
136
137 // Execute a query in a FROM clause resulting in a Table.
138 Table doFromQuery(Bool showTimings);
139
140 // Execute a subquery and create an appropriate node for the result.
142
143 // Test if a subquery has sufficient elements.
144 // It uses default LIMIT=1, but that can be overidden in the subquery.
145 // The flag tells if NOT EXISTS or EXISTS was given.
146 TableExprNode doExists(Bool noexists, Bool showTimings);
147
148 // Show the expression tree.
149 void show(ostream& os) const;
150
151 // Create a temporary table if no tables are given in FROM.
153
154 // Keep the selection expression.
156
157 // Keep the groupby expressions.
158 // It checks if they are all scalar expressions.
159 void handleGroupby(const std::vector<TableExprNode>&, Bool rollup);
160
161 // Keep the having expression.
163
164 // Keep the expression of a calculate command.
166
167 // Handle the DROP TABLE command.
168 void handleDropTab(const std::vector<const Table*>& tempTables,
169 const std::vector<TableParseQuery*>& stack);
170
171 // Keep the create table command.
172 void handleCreTab(const Record& dmInfo, const std::vector<const Table*>& tempTables,
173 const std::vector<TableParseQuery*>& stack);
174
175 // Keep the column specification in a create table command.
176 void handleColSpec(const String& columnName, const String& likeColName, const String& dataType,
177 const Record& spec, Bool isCOrder = False);
178
179 // Reopen the table (for update) used in the ALTER TABLE command.
181
182 // Add columns to the table of ALTER TABLE.
183 // The column descriptions have already been added to tableDesc_p.
184 void handleAddCol(const Record& dmInfo);
185
186 // Handle copying of columns.
187 void handleCopyCol(Bool showTimings);
188
189 // Add a keyword or replace a keyword with a value.
190 // The keyword can be a table or column keyword (col::key).
191 // The data type string can be empty leaving the data type unchanged.
192 void handleSetKey(const String& name, const String& dtype, const ValueHolder& value);
193
194 // Rename a table or column keyword.
195 void handleRenameKey(const String& oldName, const String& newName);
196
197 // Remove a table or column keyword.
199
200 // Keep the update expressions.
202
203 // Make ready for the insert expression.
204 // The first one uses values (added via addUpdate),
205 // the second one a subquery.
206 // <group>
209 // </group>
210
211 // Make ready for a COUNT command.
212 // It checks if all column expressions are scalar.
214
215 // Keep the sort expressions.
216 void handleSort(const std::vector<TableParseSortKey>& sortList, Bool noDuplicates,
217 Sort::Order defaultSortOrder);
218
219 // Evaluate and keep limit/offset/stride given as start:end:incr
221
222 // Evaluate and keep the limit value.
223 void handleLimit(const TableExprNode& expr);
224
225 // Evaluate and keep the offset value.
226 void handleOffset(const TableExprNode& expr);
227
228 // Evaluate and add the rows.
229 void handleAddRow(const TableExprNode& expr);
230
231 // Add a join object.
233
234 // Find the keyword or column name and create a TableExprNode from it.
235 // If <src>tryProj=True</src> it is first tried if the column is a column
236 // in the projected table (i.e., result from the SELECT part).
238
239 // Handle a slice operator.
241 const TaQLStyle&);
242
243 // Handle a function.
245
246 // Add a column to the list of column names.
247 void handleColumn(Int type, const String& name, const TableExprNode& expr, const String& newName,
248 const String& nameMask, const String& newDtype);
249
250 // Finish the addition of columns to the list of column names.
251 void handleColumnFinish(Bool distinct);
252
253 // Handle the name and type given in a GIVING clause.
254 void handleGiving(const String& name, const Record& type);
255
256 // Handle the set given in a GIVING clause.
258
259 // Get the TableParseJoin objects.
260 const std::vector<TableParseJoin>& joins() const { return joins_p; }
261
262 // Initialize the table and data manager descriptions.
263 void initDescriptions(const TableDesc&, const Record& dminfo);
264
265 // Add a keyword or replace a keyword with the value of another keyword.
266 // The keywords can be table or column keywords (col::key).
268
269 // Split the given name into optional shorthand, column and fields.
270 // Find the keywordset for it and fill in the final keyword name.
271 // It is a helper function for handleSetKey, etc.
272 // If update=True, rwKeywordSet() is used to ensure the table is updated.
273 TableRecord& findKeyword(const String& name, String& keyName, Bool update = True);
274
275 // Add an update object.
276 void addUpdate(const std::shared_ptr<TableParseUpdate>& upd) { update_p.push_back(upd); }
277
278 // Set the insert expressions for all rows.
279 void setInsertExprs(const std::vector<TableExprNode> exprs) { insertExprs_p = exprs; }
280
281 // Replace the first table (used by CALC command).
282 void replaceTable(const Table& table);
283
284 // Set the DataManager info for a new table.
285 void setDMInfo(const Record& dminfo) { tableProject_p.setDMInfo(dminfo); }
286
287 // Get the projected column names.
288 const Block<String>& getColumnNames() const { return tableProject_p.getColumnNames(); }
289
290 // Get the resulting table.
291 const Table& getTable() const { return table_p; }
292
293 // Show the structure of fromTables_p[0] using the options given in parts[2:].
295
296 // Add a column node to applySelNodes_p.
297 void addApplySelNode(const TableExprNode& node) { applySelNodes_p.push_back(node); }
298
299 // Create a table using the given parameters.
300 // The variables set by handleGiven are used for name and type.
301 Table createTable(const TableDesc& td, Int64 nrow, const Record& dmInfo,
302 const std::vector<const Table*>& tempTables,
303 const std::vector<TableParseQuery*>& stack);
304
305 private:
306 // Do the update step.
307 // Rows 0,1,2,.. in UpdTable are updated from the expression result
308 // for the rows in the given rownrs vector.
309 void doUpdate(Bool showTimings, const Table& origTable, Table& updTable,
310 const Vector<rownr_t>& rownrs,
311 const std::shared_ptr<TableExprGroupResult>& groups =
312 std::shared_ptr<TableExprGroupResult>());
313
314 // Do the insert step and return a selection containing the new rows.
315 Table doInsert(Bool showTimings, Table& table);
316
317 // Do the delete step.
318 void doDelete(Bool showTimings, Table& table);
319
320 // Do the count step returning a memory table containing the unique
321 // column values and the counts of the column values.
322 Table doCount(Bool showTimings, const Table&);
323
324 // Do the projection step returning a table containing the projection.
325 Table doProject(Bool showTimings, const Table&,
326 const std::shared_ptr<TableExprGroupResult>& groups =
327 std::shared_ptr<TableExprGroupResult>());
328
329 // Do the projection containing column expressions.
330 // Use the selected or unselected columns depending on <src>useSel</src>.
331 Table doProjectExpr(Bool useSel, const std::shared_ptr<TableExprGroupResult>& groups);
332
333 // Create a subtable (used by createTable).
334 Table createSubTable(const String& subtableName, const TableDesc& td, Int64 nrow,
335 const Record& dmInfo, const std::vector<const Table*>& tempTables,
336 const std::vector<TableParseQuery*>& stack);
337
338 // Set the selected rows for the column objects in applySelNodes_p.
339 // These nodes refer the original table. They requires different row
340 // numbers than the selected groups and projected columns.
341 // rownrs_p is changed to use row 0..n.
342 // It returns the Table containing the subset of rows in the input Table.
344
345 // Do the groupby/aggregate step and return its result.
346 std::shared_ptr<TableExprGroupResult> doGroupby(bool showTimings);
347
348 // Do the HAVING step.
349 // It returns False if no HAVING step was given.
350 Bool doHaving(Bool showTimings, const std::shared_ptr<TableExprGroupResult>& groups);
351
352 // Do the sort step.
353 void doSort(Bool showTimings);
354
355 // Do the limit/offset step.
356 void doLimOff(Bool showTimings);
357 Table doLimOff(Bool showTimings, const Table& table);
358
359 // Do the 'select distinct' step.
360 Table doDistinct(Bool showTimings, const Table& table);
361
362 // Finish the table (rename, copy, and/or flush).
363 Table doFinish(Bool showTimings, Table& table, const std::vector<const Table*>& tempTables,
364 const std::vector<TableParseQuery*>& stack);
365
366 // Make an array from the contents of a column in a subquery.
368
369 // Make a set from the results of the subquery.
371
372 // Evaluate an int scalar expression.
374
375 // # Data mambers.
376 // # Command type.
378 // # List of TableParsePair objects (from WITH and FROM clause).
380 // # A join object per join clause.
381 std::vector<TableParseJoin> joins_p;
382 // # Object holding the info of table projection (i.e., column selection).
384 // # Name and type of the resulting table (from GIVING part).
386 uInt resultType_p; // # 0-unknown 1=memory 2=scratch 3=plain
387 Bool resultCreated_p; // # Has the result table been created?
391 // # Resulting set (from GIVING part).
393 // # The WHERE expression tree.
395 // # The GROUPBY, aggregate and HAVING info.
397 // # Distinct values in output?
399 // # The possible limit (= max nr of selected rows) (0 means no limit).
401 // # The possible last row (0 means no end; can be <0).
402 // # limit_p and endrow_p cannot be both !=0.
404 // # The possible offset (= nr of selected rows to skip).
406 // # The possible stride in offset:endrow:stride.
408 // # The update and insert list.
409 std::vector<std::shared_ptr<TableParseUpdate>> update_p;
410 // # The insert expressions (possibly for multiple rows).
411 std::vector<TableExprNode> insertExprs_p;
412 // # The table selection to be inserted.
414 // # The sort list.
415 std::vector<TableParseSortKey> sort_p;
416 // # The noDuplicates sort switch.
418 // # The default sort order.
420 // # All nodes that need to be adjusted for a selection of rownrs.
421 // # It can consist of column nodes and the rowid function node.
422 // # Some nodes (in aggregate functions) can later be disabled for adjustment.
423 std::vector<TableExprNode> applySelNodes_p;
424 // # The resulting table.
426 // # The table resulting from a projection with expressions.
428 // # The resulting row numbers.
430};
431
432} // namespace casacore
433
434#endif
Order
Enumerate the sort order:
Definition Sort.h:252
String: the storage and methods of handling collections of characters.
Definition String.h:355
The index of an array element in a table select expression.
Class to hold the table expression nodes for an element in a set.
void handleOffset(const TableExprNode &expr)
Evaluate and keep the offset value.
void handleCount()
Make ready for a COUNT command.
const Table & getTable() const
Get the resulting table.
Table::EndianFormat endianFormat_p
const std::vector< TableParseJoin > & joins() const
Get the TableParseJoin objects.
void setInsertExprs(const std::vector< TableExprNode > exprs)
Set the insert expressions for all rows.
TableParseTableList & tableList()
Return the table name list.
TableExprNode getNode() const
Return the expression node.
std::vector< TableExprNode > applySelNodes_p
void handleLimit(const TableExprNode &expr)
Evaluate and keep the limit value.
Table doFinish(Bool showTimings, Table &table, const std::vector< const Table * > &tempTables, const std::vector< TableParseQuery * > &stack)
Finish the table (rename, copy, and/or flush).
std::vector< TableParseJoin > joins_p
void handleLimit(const TableExprNodeSetElem &expr)
Evaluate and keep limit/offset/stride given as start:end:incr.
TableExprNode doExists(Bool noexists, Bool showTimings)
Test if a subquery has sufficient elements.
Table doLimOff(Bool showTimings, const Table &table)
TableParseProject tableProject_p
Table doDistinct(Bool showTimings, const Table &table)
Do the 'select distinct' step.
void handleColSpec(const String &columnName, const String &likeColName, const String &dataType, const Record &spec, Bool isCOrder=False)
Keep the column specification in a create table command.
Table doCount(Bool showTimings, const Table &)
Do the count step returning a memory table containing the unique column values and the counts of the ...
void handleCalcComm(const TableExprNode &)
Keep the expression of a calculate command.
void doLimOff(Bool showTimings)
Do the limit/offset step.
TableExprNode handleKeyCol(const String &name, Bool tryProj)
Find the keyword or column name and create a TableExprNode from it.
void doSort(Bool showTimings)
Do the sort step.
TableExprNode makeSubSet() const
Make a set from the results of the subquery.
void handleInsert(TableParseQuery *sel)
TableRecord & findKeyword(const String &name, String &keyName, Bool update=True)
Split the given name into optional shorthand, column and fields.
TableParseJoin & addJoin()
Add a join object.
void handleGiving(const String &name, const Record &type)
Handle the name and type given in a GIVING clause.
Table createSubTable(const String &subtableName, const TableDesc &td, Int64 nrow, const Record &dmInfo, const std::vector< const Table * > &tempTables, const std::vector< TableParseQuery * > &stack)
Create a subtable (used by createTable).
void handleUpdate()
Keep the update expressions.
Int64 evalIntScaExpr(const TableExprNode &expr) const
Evaluate an int scalar expression.
std::vector< std::shared_ptr< TableParseUpdate > > update_p
void initDescriptions(const TableDesc &, const Record &dminfo)
Initialize the table and data manager descriptions.
void doDelete(Bool showTimings, Table &table)
Do the delete step.
void addUpdate(const std::shared_ptr< TableParseUpdate > &upd)
Add an update object.
std::vector< TableParseSortKey > sort_p
Bool doHaving(Bool showTimings, const std::shared_ptr< TableExprGroupResult > &groups)
Do the HAVING step.
TableParseGroupby groupby_p
std::shared_ptr< TableExprGroupResult > doGroupby(bool showTimings)
Do the groupby/aggregate step and return its result.
void handleSort(const std::vector< TableParseSortKey > &sortList, Bool noDuplicates, Sort::Order defaultSortOrder)
Keep the sort expressions.
TableExprNode doSubQuery(Bool showTimings)
Execute a subquery and create an appropriate node for the result.
void handleDropTab(const std::vector< const Table * > &tempTables, const std::vector< TableParseQuery * > &stack)
Handle the DROP TABLE command.
void handleGroupby(const std::vector< TableExprNode > &, Bool rollup)
Keep the groupby expressions.
std::vector< TableExprNode > insertExprs_p
Table doProject(Bool showTimings, const Table &, const std::shared_ptr< TableExprGroupResult > &groups=std::shared_ptr< TableExprGroupResult >())
Do the projection step returning a table containing the projection.
CommandType commandType() const
Return the command type.
void replaceTable(const Table &table)
Replace the first table (used by CALC command).
void setDMInfo(const Record &dminfo)
Set the DataManager info for a new table.
TableParseTableList tableList_p
TableExprNodeSet * resultSet_p
void handleColumn(Int type, const String &name, const TableExprNode &expr, const String &newName, const String &nameMask, const String &newDtype)
Add a column to the list of column names.
Table adjustApplySelNodes(const Table &)
Set the selected rows for the column objects in applySelNodes_p.
void handleRenameKey(const String &oldName, const String &newName)
Rename a table or column keyword.
void handleWhere(const TableExprNode &)
Keep the selection expression.
void addApplySelNode(const TableExprNode &node)
Add a column node to applySelNodes_p.
void handleGiving(const TableExprNodeSet &)
Handle the set given in a GIVING clause.
const Block< String > & getColumnNames() const
Get the projected column names.
static TableExprNode handleSlice(const TableExprNode &array, const TableExprNodeSet &indices, const TaQLStyle &)
Handle a slice operator.
void handleHaving(const TableExprNode &)
Keep the having expression.
TableExprNode handleFunc(const String &name, const TableExprNodeSet &arguments, const TaQLStyle &)
Handle a function.
Table createTable(const TableDesc &td, Int64 nrow, const Record &dmInfo, const std::vector< const Table * > &tempTables, const std::vector< TableParseQuery * > &stack)
Create a table using the given parameters.
void handleAltTab()
Reopen the table (for update) used in the ALTER TABLE command.
Table doInsert(Bool showTimings, Table &table)
Do the insert step and return a selection containing the new rows.
~TableParseQuery()
Destructor.
String getTableStructure(const Vector< String > &parts, const TaQLStyle &style)
Show the structure of fromTables_p[0] using the options given in parts[2:].
void handleTableNoFrom()
Create a temporary table if no tables are given in FROM.
void show(ostream &os) const
Show the expression tree.
void handleAddRow(const TableExprNode &expr)
Evaluate and add the rows.
TableExprNode getColSet()
Make an array from the contents of a column in a subquery.
ValueHolder getRecFld(const String &name)
Add a keyword or replace a keyword with the value of another keyword.
void handleInsert()
Make ready for the insert expression.
TableParseQuery(CommandType type)
Construct.
void handleSetKey(const String &name, const String &dtype, const ValueHolder &value)
Add a keyword or replace a keyword with a value.
void handleRemoveKey(const String &name)
Remove a table or column keyword.
void doUpdate(Bool showTimings, const Table &origTable, Table &updTable, const Vector< rownr_t > &rownrs, const std::shared_ptr< TableExprGroupResult > &groups=std::shared_ptr< TableExprGroupResult >())
Do the update step.
void handleAddCol(const Record &dmInfo)
Add columns to the table of ALTER TABLE.
Table doProjectExpr(Bool useSel, const std::shared_ptr< TableExprGroupResult > &groups)
Do the projection containing column expressions.
void handleCopyCol(Bool showTimings)
Handle copying of columns.
void execute(Bool showTimings, Bool setInGiving, Bool mustSelect, rownr_t maxRow, Bool doTracing=False, const std::vector< const Table * > &tempTables=std::vector< const Table * >(), const std::vector< TableParseQuery * > &stack=std::vector< TableParseQuery * >())
Execute the select command (select/sort/projection/groupby/having/giving).
void handleColumnFinish(Bool distinct)
Finish the addition of columns to the list of column names.
Table doFromQuery(Bool showTimings)
Execute a query in a FROM clause resulting in a Table.
void handleCreTab(const Record &dmInfo, const std::vector< const Table * > &tempTables, const std::vector< TableParseQuery * > &stack)
Keep the create table command.
Class containing two lists of TableParsePair objects.
EndianFormat
Define the possible endian formats in which table data can be stored.
Definition Table.h:192
For temporary backward namespace compatibility, use casa as alias for casacore.
Definition mainpage.dox:28
const Bool False
Definition aipstype.h:42
T * array
The actual storage.
Definition Block.h:689
unsigned int uInt
Definition aipstype.h:49
long long Int64
Define the extra non-standard types used by Casacore (like proposed uSize, Size).
Definition aipsxtype.h:36
String name() const
Return the name of the field.
int Int
Definition aipstype.h:48
bool Bool
Define the standard types used by Casacore.
Definition aipstype.h:40
const Bool True
Definition aipstype.h:41
NewDelAllocator< T > NewDelAllocator< T >::value
Definition Allocator.h:360
uInt64 rownr_t
Define the type of a row number in a table.
Definition aipsxtype.h:44
DataType dataType(const RecordFieldId &) const